feat(arc/circle): ERC-8004 + ERC-8183 + arc-chains, swap-fee + DCW contract-exec

New packages (port/adapter pattern, zero new external deps, deterministic local impls + tests):
- @settlekit/erc8004: agent identity / reputation / validation on Arc (real Arc Testnet registry addresses); AgentRegistryClient + LocalErc8004Port.
- @settlekit/erc8183: autonomous-agent job lifecycle (create→fund→submit→evaluate→settle/refund) as a validated state machine; JobClient + LocalErc8183Port.
- @settlekit/arc-chains: single source of truth for Arc/Circle chain + token + contract constants.

Extensions:
- app-kit swap: slippage tolerance + custom swap-fee collection (Stablecoin-FX monetization), validateBps, LocalAppKitSdk.lastSwapConfig().
- circle-wallets: Developer-Controlled-Wallet contract execution + transaction polling (drives ERC-8004/8183 on-chain).

1130 tests across 192 suites, typecheck + full build green.
This commit is contained in:
caelum0x 2026-06-20 19:08:41 +03:00
parent a93f04ef8d
commit 9d2bc4eae0
44 changed files with 3716 additions and 3 deletions

View File

@ -18,7 +18,14 @@ import {
type TransferResult,
type TransferStatus,
} from "./types.js";
import { firstError, validateAddress, validateAmount, validateChain, validateToken } from "./validate.js";
import {
firstError,
validateAddress,
validateAmount,
validateBps,
validateChain,
validateToken,
} from "./validate.js";
/** Default token when a request omits one. */
const DEFAULT_TOKEN = "USDC";
@ -199,6 +206,12 @@ export class ArcPaymentClient<A> {
if (req.tokenIn === req.tokenOut) {
return err(validationError("tokenIn and tokenOut must differ", { token: req.tokenIn }));
}
const monetizationInvalid = firstError(
req.slippageBps !== undefined ? validateBps(req.slippageBps, "slippageBps") : null,
req.fee !== undefined ? validateBps(req.fee.bps, "fee.bps") : null,
req.fee !== undefined ? validateAddress(req.fee.recipient, "fee.recipient") : null,
);
if (monetizationInvalid !== null) return err(monetizationInvalid);
if (this.kitKey === undefined || this.kitKey.length === 0) {
return err(
new SettleKitError({
@ -208,13 +221,20 @@ export class ArcPaymentClient<A> {
);
}
const kitKey = this.kitKey;
const config = {
kitKey,
...(req.slippageBps !== undefined ? { slippageTolerance: req.slippageBps } : {}),
...(req.fee !== undefined ? { fee: { recipient: req.fee.recipient, bps: req.fee.bps } } : {}),
};
return this.run("swap", () =>
this.sdk.swap({
from: { adapter: req.adapter, chain: req.chain },
tokenIn: req.tokenIn,
tokenOut: req.tokenOut,
amountIn: req.amountIn,
config: { kitKey: this.kitKey },
config,
}),
);
}

View File

@ -38,6 +38,7 @@ export class LocalAppKitSdk implements AppKitSdk<string> {
private readonly throwOn: ReadonlySet<TransferKind>;
private counter = 0;
private readonly recorded: RecordedCall[] = [];
private lastSwapConfigValue: SdkSwapParams<string>["config"];
readonly unifiedBalance: {
deposit(params: SdkDepositParams<string>): Promise<SdkResult>;
@ -60,6 +61,21 @@ export class LocalAppKitSdk implements AppKitSdk<string> {
return [...this.recorded];
}
/**
* The `config` passed to the most recent {@link swap} call, or `undefined` if
* no swap has run yet. Returns a defensive copy so assertions cannot mutate
* recorded state.
*/
lastSwapConfig(): SdkSwapParams<string>["config"] {
if (this.lastSwapConfigValue === undefined) return undefined;
const { kitKey, slippageTolerance, fee } = this.lastSwapConfigValue;
return {
...(kitKey !== undefined ? { kitKey } : {}),
...(slippageTolerance !== undefined ? { slippageTolerance } : {}),
...(fee !== undefined ? { fee: { recipient: fee.recipient, bps: fee.bps } } : {}),
};
}
private async simulate(
kind: TransferKind,
name: string,
@ -93,6 +109,7 @@ export class LocalAppKitSdk implements AppKitSdk<string> {
}
swap(params: SdkSwapParams<string>): Promise<SdkResult> {
this.lastSwapConfigValue = params.config;
return this.simulate("swap", "swap", params.amountIn, params.from.chain);
}
}

View File

@ -49,7 +49,13 @@ export interface SdkSwapParams<A> {
tokenIn: string;
tokenOut: string;
amountIn: string;
config?: { kitKey?: string };
config?: {
kitKey?: string;
/** Slippage tolerance in basis points (mapped from request `slippageBps`). */
slippageTolerance?: number;
/** Custom spread fee to collect on the swap. */
fee?: { recipient: string; bps: number };
};
}
/** App Kit `unifiedBalance.deposit` parameters. */

View File

@ -110,6 +110,17 @@ export interface BridgeRequest<A> {
amount: string;
}
/**
* A custom spread fee collected on a swap (Stablecoin-FX monetization).
* The fee is taken as a share of the swap and routed to {@link SwapFee.recipient}.
*/
export interface SwapFee {
/** Wallet address that receives the collected fee. Must be non-empty. */
recipient: string;
/** Fee size in basis points (0..10000, where 10000 = 100%). */
bps: number;
}
/** Exchange one token for another on the same chain. */
export interface SwapRequest<A> {
adapter: A;
@ -118,6 +129,14 @@ export interface SwapRequest<A> {
tokenOut: SupportedToken;
/** Decimal input amount. */
amountIn: string;
/**
* Slippage tolerance in basis points (0..10000, where 100 = 1%). When set,
* the swap reverts if the realized price moves beyond this bound. Maps to the
* SDK's `config.slippageTolerance`.
*/
slippageBps?: number;
/** Optional custom spread fee to collect on this swap. */
fee?: SwapFee;
}
/** Deposit a token from one chain into the chain-abstracted Unified Balance. */

View File

@ -54,6 +54,27 @@ export function validateToken(token: string, field = "token"): SettleKitError |
return null;
}
/** Maximum basis points (100%). */
const MAX_BPS = 10000;
/**
* Validate a basis-points value: an integer in the inclusive range 0..10000.
* Relies on {@link Number.isInteger} so `NaN`/`Infinity`/fractions are rejected
* (range comparisons alone would let `NaN` slip through).
*/
export function validateBps(value: number, field: string): SettleKitError | null {
if (typeof value !== "number" || !Number.isInteger(value)) {
return validationError(`${field} must be an integer`, { field, value });
}
if (value < 0 || value > MAX_BPS) {
return validationError(`${field} must be between 0 and ${MAX_BPS} basis points`, {
field,
value,
});
}
return null;
}
/** Validate a non-empty wallet address. */
export function validateAddress(address: string, field = "address"): SettleKitError | null {
if (typeof address !== "string" || address.trim().length === 0) {

View File

@ -168,6 +168,109 @@ describe("swap", () => {
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("passes valid slippage and fee through to the SDK", async () => {
const sdk = new LocalAppKitSdk();
const { arc } = client({ kitKey: "kit_test", sdk });
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
slippageBps: 50,
fee: { recipient: "0xfeeacct", bps: 30 },
});
expect(isOk(res)).toBe(true);
expect(sdk.lastSwapConfig()).toEqual({
kitKey: "kit_test",
slippageTolerance: 50,
fee: { recipient: "0xfeeacct", bps: 30 },
});
});
it("omits slippage/fee from config when not provided", async () => {
const sdk = new LocalAppKitSdk();
const { arc } = client({ kitKey: "kit_test", sdk });
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
});
expect(isOk(res)).toBe(true);
expect(sdk.lastSwapConfig()).toEqual({ kitKey: "kit_test" });
});
it("accepts boundary basis points (0 slippage, 10000 fee)", async () => {
const sdk = new LocalAppKitSdk();
const { arc } = client({ kitKey: "kit_test", sdk });
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
slippageBps: 0,
fee: { recipient: "0xfeeacct", bps: 10000 },
});
expect(isOk(res)).toBe(true);
expect(sdk.lastSwapConfig()).toEqual({
kitKey: "kit_test",
slippageTolerance: 0,
fee: { recipient: "0xfeeacct", bps: 10000 },
});
});
it("rejects out-of-range or non-integer slippageBps", async () => {
const { arc } = client({ kitKey: "kit_test" });
for (const slippageBps of [-1, 10001, 1.5, Number.NaN]) {
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
slippageBps,
});
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
}
});
it("rejects out-of-range or non-integer fee.bps", async () => {
const { arc } = client({ kitKey: "kit_test" });
for (const bps of [20000, 12.3, -5]) {
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
fee: { recipient: "0xfeeacct", bps },
});
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
}
});
it("rejects an empty fee.recipient", async () => {
const { arc } = client({ kitKey: "kit_test" });
const res = await arc.swap({
adapter: ADAPTER,
chain: "Arc_Testnet",
tokenIn: "USDC",
tokenOut: "EURC",
amountIn: "1",
fee: { recipient: " ", bps: 30 },
});
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
});
describe("unified balance", () => {

View File

@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { validateBps } from "../src/index.js";
describe("validateBps", () => {
it("accepts the inclusive 0..10000 integer range", () => {
for (const value of [0, 1, 50, 5000, 10000]) {
expect(validateBps(value, "bps")).toBeNull();
}
});
it("rejects values outside the range", () => {
for (const value of [-1, 10001, 99999]) {
const error = validateBps(value, "bps");
expect(error).not.toBeNull();
expect(error?.code).toBe("validation_error");
}
});
it("rejects non-integers including NaN and Infinity", () => {
for (const value of [1.5, 12.3, Number.NaN, Number.POSITIVE_INFINITY]) {
const error = validateBps(value, "bps");
expect(error).not.toBeNull();
expect(error?.code).toBe("validation_error");
}
});
it("includes the field name in the error details", () => {
const error = validateBps(-1, "slippageBps");
expect(error?.details).toMatchObject({ field: "slippageBps", value: -1 });
});
});

View File

@ -0,0 +1,80 @@
# @settlekit/arc-chains
Dependency-light **source of truth** for Arc / Circle chain, token, and contract
constants. Every SettleKit package and app imports these definitions instead of
re-declaring chain ids, RPC URLs, explorer bases, or registry addresses.
**Pure data + pure functions only — no I/O, no side effects.**
## Why dependency-free
This package takes **zero `@settlekit` dependencies** and sits as a leaf in the
build graph. The ERC-8004 registry addresses and Arc Testnet endpoints are
**mirrored verbatim** from `packages/erc8004/src/addresses.ts` (the canonical
source) rather than imported, because `@settlekit/erc8004` exposes no barrel and
its `dist` is unbuilt. A test asserts the exact mirrored values so drift is
caught immediately. If the erc8004 addresses change, update both and re-run the
test.
## Exports
### Chains (`chains.ts`)
- `ChainDescriptor` — `{ key, displayName, chainId, rpcUrl, explorerUrl, testnet }`
- `SupportedChain` — 8-member union, identical to `@settlekit/app-kit`
- `CHAINS: Record<SupportedChain, ChainDescriptor>` — total record
- `SUPPORTED_CHAINS` — runtime allow-list derived from `CHAINS`
- `getChain(key)` — descriptor lookup (total record, never `undefined`)
- `explorerTxUrl(chain, hash)` → `` `${chain.explorerUrl}/tx/${hash}` ``
- `explorerAddressUrl(chain, addr)` → `` `${chain.explorerUrl}/address/${addr}` ``
> Note: these helpers take a `ChainDescriptor` (per chain), unlike the
> `@settlekit/erc8004` helpers which take a base-URL string. The path format is
> identical so URLs match across packages.
### Tokens (`tokens.ts`)
- `SupportedToken` — 7-member union (`USDC | EURC | USDT | USDe | DAI | PYUSD | cirBTC`)
- `TokenMetadata` — `{ symbol, decimals, address? }`
- `TOKENS: Record<SupportedToken, TokenMetadata>` — symbol-level metadata
- `CHAIN_TOKENS` — optional per-chain token placement
- `getToken(symbol)` — metadata lookup
### Contracts (`contracts.ts`)
- `Erc8004Registries` — `{ identityRegistry, reputationRegistry, validationRegistry }`
- `ARC_TESTNET_REGISTRIES` — the three documented Arc Testnet ERC-8004 addresses
- `CONTRACTS` — forward-compatible per-chain registry map
## Verified Arc Testnet endpoints
| Field | Value |
| ------------ | ------------------------------------ |
| RPC | `https://rpc.testnet.arc.network/` |
| Explorer | `https://testnet.arcscan.app` |
| Identity | `0x8004A818BFB912233c491871b3d84c89A494BD9e` |
| Reputation | `0x8004B663056A597Dffe9eCcC1965A193B7388713` |
| Validation | `0x8004Cb1BF31DAf7788923b405b754f57acEB4272` |
## TODO markers (values not yet in the Arc docs)
Nothing below is invented — each is left as a typed empty/undefined sentinel:
- **Arc Testnet `chainId`** — not published in the repo's Arc docs; left as the
`0` sentinel until verified. The verified RPC/explorer remain the source of
truth.
- **Arc Mainnet `rpcUrl` / `explorerUrl` / `chainId`** — not yet in Arc docs;
left as `""` / `0`. Excluded from the non-empty-endpoint test invariant.
- **All token on-chain addresses** — left `undefined`. Addresses are never
invented; they will be filled when published.
Non-Arc chains (Ethereum / Base / Arbitrum and their Sepolia variants) use
well-known public chain ids and canonical public explorer hostnames. Their RPC
URLs are canonical public defaults — override per environment as needed.
## Build & test
```bash
pnpm --filter @settlekit/arc-chains build # tsc -b
pnpm --filter @settlekit/arc-chains test # vitest run
```

View File

@ -0,0 +1,23 @@
{
"name": "@settlekit/arc-chains",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "tsc -b",
"test": "vitest run"
},
"devDependencies": {
"@types/node": "^20.14.0",
"typescript": "^5.5.4",
"vitest": "^2.0.5"
}
}

View File

@ -0,0 +1,155 @@
/**
* Arc / Circle chain descriptors — the single source of truth for chain
* metadata (id, RPC, explorer) shared across SettleKit packages and apps.
*
* Pure data + pure functions only. No I/O.
*
* The {@link SupportedChain} union is re-declared here (rather than imported)
* so this package stays dependency-free and a leaf in the build graph. It MUST
* stay member-for-member identical to packages/app-kit/src/types.ts
* (the canonical union for App Kit flows).
*
* Verified Arc Testnet endpoints are mirrored from
* packages/erc8004/src/addresses.ts (the canonical source for Arc endpoints).
* Non-Arc public chain ids and explorer hostnames are well-known public facts.
* Public RPC URLs are environment-dependent; the defaults below are canonical
* public endpoints — override per environment as needed.
*/
/**
* Blockchains App Kit supports for SettleKit flows (Arc-centric).
* Mirrors {@link SupportedChain} in packages/app-kit/src/types.ts.
*/
export type SupportedChain =
| "Arc_Testnet"
| "Arc_Mainnet"
| "Ethereum_Sepolia"
| "Ethereum"
| "Base_Sepolia"
| "Base"
| "Arbitrum_Sepolia"
| "Arbitrum";
/** Static metadata describing one chain. */
export interface ChainDescriptor {
/** Stable key, matching the {@link SupportedChain} union. */
key: SupportedChain;
/** Human-readable name for UI surfaces. */
displayName: string;
/** EVM chain id (e.g. 1 for Ethereum mainnet). */
chainId: number;
/** JSON-RPC endpoint. Empty string when not yet published (see TODO). */
rpcUrl: string;
/** Block-explorer base URL. Empty string when not yet published (see TODO). */
explorerUrl: string;
/** True for testnets. */
testnet: boolean;
}
/**
* Arc Testnet endpoints — mirrored verbatim from
* packages/erc8004/src/addresses.ts (canonical source).
*/
const ARC_TESTNET_RPC_URL = "https://rpc.testnet.arc.network/";
const ARC_TESTNET_EXPLORER = "https://testnet.arcscan.app";
/** Total record of every supported chain. */
export const CHAINS: Record<SupportedChain, ChainDescriptor> = {
Arc_Testnet: {
key: "Arc_Testnet",
displayName: "Arc Testnet",
// TODO: Arc Testnet EVM chainId not published in the Arc docs available in
// this repo — do not invent. Left as the 0 sentinel until verified; the
// verified rpcUrl/explorerUrl below are the source of truth for Arc Testnet.
chainId: 0,
rpcUrl: ARC_TESTNET_RPC_URL,
explorerUrl: ARC_TESTNET_EXPLORER,
testnet: true,
},
Arc_Mainnet: {
key: "Arc_Mainnet",
displayName: "Arc Mainnet",
// TODO: Arc Mainnet chainId not yet in Arc docs.
chainId: 0,
// TODO: Arc mainnet RPC not yet in Arc docs — do not invent.
rpcUrl: "",
// TODO: Arc mainnet explorer not yet in Arc docs — do not invent.
explorerUrl: "",
testnet: false,
},
Ethereum: {
key: "Ethereum",
displayName: "Ethereum",
chainId: 1,
rpcUrl: "https://eth.llamarpc.com",
explorerUrl: "https://etherscan.io",
testnet: false,
},
Ethereum_Sepolia: {
key: "Ethereum_Sepolia",
displayName: "Ethereum Sepolia",
chainId: 11155111,
rpcUrl: "https://ethereum-sepolia-rpc.publicnode.com",
explorerUrl: "https://sepolia.etherscan.io",
testnet: true,
},
Base: {
key: "Base",
displayName: "Base",
chainId: 8453,
rpcUrl: "https://mainnet.base.org",
explorerUrl: "https://basescan.org",
testnet: false,
},
Base_Sepolia: {
key: "Base_Sepolia",
displayName: "Base Sepolia",
chainId: 84532,
rpcUrl: "https://sepolia.base.org",
explorerUrl: "https://sepolia.basescan.org",
testnet: true,
},
Arbitrum: {
key: "Arbitrum",
displayName: "Arbitrum One",
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
explorerUrl: "https://arbiscan.io",
testnet: false,
},
Arbitrum_Sepolia: {
key: "Arbitrum_Sepolia",
displayName: "Arbitrum Sepolia",
chainId: 421614,
rpcUrl: "https://sepolia-rollup.arbitrum.io/rpc",
explorerUrl: "https://sepolia.arbiscan.io",
testnet: true,
},
};
/** Runtime allow-list derived from {@link CHAINS}. */
export const SUPPORTED_CHAINS: readonly SupportedChain[] = Object.keys(
CHAINS,
) as SupportedChain[];
/**
* Look up a chain descriptor by key. {@link CHAINS} is a total
* `Record<SupportedChain, ...>`, so a literal-union key never widens to
* `undefined` under `noUncheckedIndexedAccess`.
*/
export function getChain(key: SupportedChain): ChainDescriptor {
return CHAINS[key];
}
/** Build an explorer URL for a transaction hash on the given chain. */
export function explorerTxUrl(chain: ChainDescriptor, hash: string): string {
return `${chain.explorerUrl}/tx/${hash}`;
}
/** Build an explorer URL for an address on the given chain. */
export function explorerAddressUrl(
chain: ChainDescriptor,
addr: string,
): string {
return `${chain.explorerUrl}/address/${addr}`;
}

View File

@ -0,0 +1,40 @@
/**
* Known Arc Testnet contract addresses — ERC-8004 registries.
*
* These three addresses are MIRRORED VERBATIM from
* packages/erc8004/src/addresses.ts, which is the canonical source. They are
* re-declared here (rather than imported) so @settlekit/arc-chains stays
* dependency-free and a leaf in the build graph. A test asserts the exact
* values to catch drift; if erc8004 changes, update both and re-verify.
*
* Pure data only. No I/O. Addresses are never invented.
*/
import type { SupportedChain } from "./chains.js";
/** A set of ERC-8004 registry addresses for one network. */
export interface Erc8004Registries {
identityRegistry: string;
reputationRegistry: string;
validationRegistry: string;
}
/**
* Arc Testnet ERC-8004 registries.
* Mirrored from packages/erc8004/src/addresses.ts (canonical source).
*/
export const ARC_TESTNET_REGISTRIES: Erc8004Registries = {
identityRegistry: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
reputationRegistry: "0x8004B663056A597Dffe9eCcC1965A193B7388713",
validationRegistry: "0x8004Cb1BF31DAf7788923b405b754f57acEB4272",
};
/**
* Per-chain ERC-8004 registries, keyed by chain. Forward-compatible map; only
* Arc Testnet is populated. Arc Mainnet is intentionally omitted — its
* registry addresses are not yet in the Arc docs (do not invent).
*/
export const CONTRACTS: Partial<Record<SupportedChain, Erc8004Registries>> = {
Arc_Testnet: ARC_TESTNET_REGISTRIES,
// TODO: Arc_Mainnet ERC-8004 registries not yet in Arc docs — do not invent.
};

View File

@ -0,0 +1,11 @@
/**
* @settlekit/arc-chains — dependency-light source of truth for Arc / Circle
* chain, token, and contract constants. Pure data + pure functions only.
*
* No symbol collisions: SupportedChain lives in chains.ts, SupportedToken in
* tokens.ts; Erc8004Registries in contracts.ts.
*/
export * from "./chains.js";
export * from "./tokens.js";
export * from "./contracts.js";

View File

@ -0,0 +1,103 @@
/**
* Token metadata for Arc / Circle flows — symbol-level decimals plus optional
* per-chain placement. The single source of truth for token constants shared
* across SettleKit packages and apps.
*
* Pure data only. No I/O.
*
* HARD RULE: on-chain token addresses are NEVER invented. Every `address` is
* left `undefined` with a `// TODO` until a value appears in the Arc docs.
*
* The {@link SupportedToken} union is re-declared here (rather than imported)
* so this package stays dependency-free. It MUST stay member-for-member
* identical to packages/app-kit/src/types.ts (the canonical union).
*/
import type { SupportedChain } from "./chains.js";
/**
* Tokens App Kit can transfer or swap.
* Mirrors {@link SupportedToken} in packages/app-kit/src/types.ts.
*/
export type SupportedToken =
| "USDC"
| "EURC"
| "USDT"
| "USDe"
| "DAI"
| "PYUSD"
| "cirBTC";
/** Runtime allow-list mirroring {@link SupportedToken}. */
export const SUPPORTED_TOKENS: readonly SupportedToken[] = [
"USDC",
"EURC",
"USDT",
"USDe",
"DAI",
"PYUSD",
"cirBTC",
];
/** Metadata for one token. */
export interface TokenMetadata {
/** Token symbol. */
symbol: SupportedToken;
/** ERC-20 decimals. */
decimals: number;
/**
* On-chain contract address. Optional and left `undefined` until published
* in the Arc docs — addresses are never invented.
*/
address?: string;
}
/**
* Symbol-level token metadata. Decimals use well-established standards:
* USDC/EURC/USDT/PYUSD = 6, DAI/USDe = 18, cirBTC = 8 (BTC-pegged).
* Addresses are intentionally omitted (per-chain; see {@link CHAIN_TOKENS}).
*/
export const TOKENS: Record<SupportedToken, TokenMetadata> = {
// Decimals = 6 per the Arc/Circle stablecoin spec.
USDC: { symbol: "USDC", decimals: 6 },
EURC: { symbol: "EURC", decimals: 6 },
// USDT uses 6 decimals on EVM chains (standard).
USDT: { symbol: "USDT", decimals: 6 },
// USDe (Ethena) uses 18 decimals (standard).
USDe: { symbol: "USDe", decimals: 18 },
// DAI uses 18 decimals (standard).
DAI: { symbol: "DAI", decimals: 18 },
// PYUSD uses 6 decimals (standard).
PYUSD: { symbol: "PYUSD", decimals: 6 },
// cirBTC is BTC-pegged; 8 decimals (BTC convention).
// TODO: confirm cirBTC decimals against Arc docs.
cirBTC: { symbol: "cirBTC", decimals: 8 },
};
/**
* Per-chain token placement. Populated only where token presence is known;
* decimals carry over from {@link TOKENS} and addresses stay `undefined` until
* the Arc docs publish them (never invented).
*
* USDC and EURC are Circle's native stablecoins on Arc, hence listed on
* Arc Testnet. Addresses are TODO.
*/
export const CHAIN_TOKENS: Partial<
Record<SupportedChain, Partial<Record<SupportedToken, TokenMetadata>>>
> = {
Arc_Testnet: {
// TODO: USDC address on Arc Testnet not in Arc docs — do not invent.
USDC: { symbol: "USDC", decimals: 6 },
// TODO: EURC address on Arc Testnet not in Arc docs — do not invent.
EURC: { symbol: "EURC", decimals: 6 },
},
};
/**
* Look up symbol-level token metadata. {@link TOKENS} is a total
* `Record<SupportedToken, ...>`, so a literal-union key never widens to
* `undefined` under `noUncheckedIndexedAccess`.
*/
export function getToken(symbol: SupportedToken): TokenMetadata {
return TOKENS[symbol];
}

View File

@ -0,0 +1,125 @@
import { describe, expect, it } from "vitest";
import {
ARC_TESTNET_REGISTRIES,
CHAINS,
SUPPORTED_CHAINS,
SUPPORTED_TOKENS,
TOKENS,
explorerAddressUrl,
explorerTxUrl,
getChain,
getToken,
} from "../src/index.js";
import type { ChainDescriptor, SupportedChain } from "../src/index.js";
/** Chains whose endpoints are intentionally TODO (excluded from invariants). */
const TODO_CHAINS: readonly SupportedChain[] = ["Arc_Mainnet"];
describe("chains", () => {
it("getChain returns the verified Arc Testnet descriptor", () => {
const arc = getChain("Arc_Testnet");
expect(arc.rpcUrl).toBe("https://rpc.testnet.arc.network/");
expect(arc.explorerUrl).toBe("https://testnet.arcscan.app");
expect(arc.testnet).toBe(true);
expect(arc.key).toBe("Arc_Testnet");
});
it("getChain returns a mainnet (non-testnet) descriptor for Ethereum", () => {
const eth = getChain("Ethereum");
expect(eth.testnet).toBe(false);
expect(eth.chainId).toBe(1);
});
it("explorerTxUrl builds the exact tx path", () => {
const arc = getChain("Arc_Testnet");
expect(explorerTxUrl(arc, "0xabc")).toBe(
"https://testnet.arcscan.app/tx/0xabc",
);
});
it("explorerAddressUrl builds the exact address path", () => {
const arc = getChain("Arc_Testnet");
expect(explorerAddressUrl(arc, "0xdef")).toBe(
"https://testnet.arcscan.app/address/0xdef",
);
});
it("CHAINS has exactly the 8 SupportedChain keys", () => {
const keys = Object.keys(CHAINS);
expect(keys).toHaveLength(8);
expect([...keys].sort()).toEqual([...SUPPORTED_CHAINS].sort());
expect(keys).toEqual(
expect.arrayContaining([
"Arc_Testnet",
"Arc_Mainnet",
"Ethereum_Sepolia",
"Ethereum",
"Base_Sepolia",
"Base",
"Arbitrum_Sepolia",
"Arbitrum",
]),
);
});
it("every non-TODO chain has non-empty rpcUrl and explorerUrl", () => {
for (const chain of Object.values(CHAINS) as ChainDescriptor[]) {
if (TODO_CHAINS.includes(chain.key)) continue;
expect(chain.rpcUrl.length).toBeGreaterThan(0);
expect(chain.explorerUrl.length).toBeGreaterThan(0);
}
});
it("every chain descriptor's key matches its CHAINS record key", () => {
for (const key of SUPPORTED_CHAINS) {
expect(getChain(key).key).toBe(key);
}
});
it("chainId is a positive unique integer for chains with a published id", () => {
const ids = (Object.values(CHAINS) as ChainDescriptor[])
// chainId 0 is the documented "not in docs" sentinel (Arc).
.filter((c) => c.chainId !== 0)
.map((c) => c.chainId);
for (const id of ids) {
expect(Number.isInteger(id)).toBe(true);
expect(id).toBeGreaterThan(0);
}
expect(new Set(ids).size).toBe(ids.length);
});
});
describe("contracts", () => {
it("ARC_TESTNET_REGISTRIES matches the documented ERC-8004 addresses", () => {
expect(ARC_TESTNET_REGISTRIES.identityRegistry).toBe(
"0x8004A818BFB912233c491871b3d84c89A494BD9e",
);
expect(ARC_TESTNET_REGISTRIES.reputationRegistry).toBe(
"0x8004B663056A597Dffe9eCcC1965A193B7388713",
);
expect(ARC_TESTNET_REGISTRIES.validationRegistry).toBe(
"0x8004Cb1BF31DAf7788923b405b754f57acEB4272",
);
});
});
describe("tokens", () => {
it("USDC and EURC have 6 decimals", () => {
expect(getToken("USDC").decimals).toBe(6);
expect(getToken("EURC").decimals).toBe(6);
});
it("TOKENS key-set equals the 7-member SupportedToken union", () => {
const keys = Object.keys(TOKENS);
expect(keys).toHaveLength(7);
expect([...keys].sort()).toEqual([...SUPPORTED_TOKENS].sort());
});
it("no token address is invented (all undefined or 0x-prefixed)", () => {
for (const meta of Object.values(TOKENS)) {
if (meta.address !== undefined) {
expect(meta.address.startsWith("0x")).toBe(true);
}
}
});
});

View File

@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"composite": true
},
"references": [],
"include": ["src/**/*"],
"exclude": ["dist", "node_modules", "**/*.test.ts"]
}

View File

@ -12,6 +12,7 @@
* - GET /v1/w3s/wallets list wallets
* - GET /v1/w3s/wallets/{id}/balances get wallet token balances
* - POST /v1/w3s/developer/transactions/transfer create a transfer transaction
* - POST /v1/w3s/developer/transactions/contractExecution execute a contract call
* - GET /v1/w3s/transactions/{id} get transaction status
*
* ENTITY SECRET (read this): every mutating call requires an
@ -28,6 +29,8 @@ import { SettleKitError } from "@settlekit/common";
import { createFetchWalletsHttp } from "./http.js";
import type { WalletsHttp, WalletsRequest } from "./http.js";
import { assertOk, requireString, unwrapData } from "./envelope.js";
import { buildContractExecutionRequest } from "./contract-execution.js";
import type { CreateContractExecutionInput } from "./contract-execution.js";
import type {
CircleAccountType,
CircleBlockchain,
@ -128,6 +131,9 @@ export interface WalletsClient {
listWallets(input?: ListWalletsInput): Promise<CircleWalletResource[]>;
getWalletBalance(walletId: string): Promise<CircleTokenBalance[]>;
createTransfer(input: CreateTransferInput): Promise<CircleTransactionResource>;
createContractExecution(
input: CreateContractExecutionInput,
): Promise<CircleTransactionResource>;
getTransaction(id: string): Promise<CircleTransactionResource>;
}
@ -252,6 +258,25 @@ export function createWalletsClient(config: WalletsClientConfig): WalletsClient
});
},
async createContractExecution(
input: CreateContractExecutionInput,
): Promise<CircleTransactionResource> {
requireString(input.walletAddress, "createContractExecution.walletAddress");
requireString(input.blockchain, "createContractExecution.blockchain");
requireString(input.contractAddress, "createContractExecution.contractAddress");
requireString(input.abiFunctionSignature, "createContractExecution.abiFunctionSignature");
if (!Array.isArray(input.abiParameters)) {
throw new SettleKitError({
code: "validation_error",
message: "createContractExecution requires abiParameters to be an array",
});
}
const entitySecretCiphertext = await resolveEntitySecret(input, "createContractExecution");
return send<CircleTransactionResource>(
buildContractExecutionRequest(input, entitySecretCiphertext),
);
},
async getTransaction(id: string): Promise<CircleTransactionResource> {
requireString(id, "getTransaction.id");
const data = await send<{ transaction: CircleTransactionResource }>({

View File

@ -0,0 +1,170 @@
/**
* Developer-controlled wallet **contract execution** + transaction polling for
* Circle Web3 Services (W3S) — the mechanism Arc's ERC-8004/8183 tutorials use
* (`createContractExecutionTransaction` + `getTransaction` polling to a terminal
* `COMPLETE` / `FAILED` state).
*
* Two pieces live here:
* - `buildContractExecutionRequest` — a pure request builder that mirrors
* `createTransfer`'s body shape exactly (idempotencyKey, domain fields,
* `feeLevel` defaulting to MEDIUM, refId, entitySecretCiphertext). The
* `createContractExecution` method on `WalletsClient` composes this with the
* same private `send` / `resolveEntitySecret` helpers used by every mutation.
* - `pollTransaction` — a standalone helper that polls a transaction via the
* public `getTransaction` until it reaches a terminal state. A `sleep` is
* injectable so tests run deterministically with no real timers.
*
* This package flattens the gas fee to a top-level `feeLevel` (its own REST
* convention, matching `createTransfer`) rather than the Arc SDK's nested
* `fee: { type: "level", config: { feeLevel } }`.
*
* Source: https://developers.circle.com/w3s (Developer-Controlled Wallets).
*/
import { SettleKitError } from "@settlekit/common";
import { requireString } from "./envelope.js";
import type { WalletsRequest } from "./http.js";
import type { WalletsClient } from "./client.js";
import type { EntitySecretInput } from "./client.js";
import type {
CircleBlockchain,
CircleFeeLevel,
CircleTransactionResource,
CircleTransactionState,
} from "./types.js";
/** Endpoint for developer-controlled contract execution transactions. */
const CONTRACT_EXECUTION_PATH = "/v1/w3s/developer/transactions/contractExecution";
/** Terminal failure states: a transaction in any of these will never complete. */
const TERMINAL_FAILURE_STATES: ReadonlySet<CircleTransactionState> = new Set([
"FAILED",
"CANCELLED",
"DENIED",
]);
/** Default number of poll attempts before `pollTransaction` times out. */
export const DEFAULT_POLL_ATTEMPTS = 30;
/** Default delay (ms) between poll attempts. */
export const DEFAULT_POLL_DELAY_MS = 2000;
/**
* Input for a developer-controlled contract execution transaction. Keys on
* `walletAddress` + `blockchain` (the contractExecution endpoint accepts these
* as an alternative to `walletId`). Mirrors `CreateTransferInput`'s entity
* secret / idempotency / refId conventions.
*/
export interface CreateContractExecutionInput extends EntitySecretInput {
/** Source developer-controlled wallet address. */
walletAddress: string;
/** Blockchain the wallet (and target contract) live on. */
blockchain: CircleBlockchain;
/** Target smart-contract address to call. */
contractAddress: string;
/** ABI function signature, e.g. "mint(address,uint256)". */
abiFunctionSignature: string;
/** Positional ABI arguments aligned with the function signature. */
abiParameters: readonly (string | number | boolean)[];
/** Gas fee level. Defaults to MEDIUM. */
feeLevel?: CircleFeeLevel;
/** Caller reference echoed back on the transaction. */
refId?: string;
idempotencyKey?: string;
}
/**
* Build the contract-execution request. Pure: it never mutates `input`, and the
* readonly `abiParameters` are spread into a fresh array so the body is plain
* JSON-serializable. The body mirrors `createTransfer` exactly.
*/
export function buildContractExecutionRequest(
input: CreateContractExecutionInput,
entitySecretCiphertext: string,
): WalletsRequest {
return {
method: "POST",
path: CONTRACT_EXECUTION_PATH,
body: {
idempotencyKey: input.idempotencyKey,
walletAddress: input.walletAddress,
blockchain: input.blockchain,
contractAddress: input.contractAddress,
abiFunctionSignature: input.abiFunctionSignature,
abiParameters: [...input.abiParameters],
feeLevel: input.feeLevel ?? "MEDIUM",
refId: input.refId,
entitySecretCiphertext,
},
};
}
/** Options for {@link pollTransaction}. */
export interface PollTransactionOptions {
/** Transaction id to poll. */
id: string;
/** Maximum number of `getTransaction` calls. Defaults to {@link DEFAULT_POLL_ATTEMPTS}. */
attempts?: number;
/** Delay between attempts in ms. Defaults to {@link DEFAULT_POLL_DELAY_MS}. */
delayMs?: number;
/** Injectable sleep for deterministic tests; defaults to a real timer-based sleep. */
sleep?: (ms: number) => Promise<void>;
}
/** Real timer-based sleep used as the production default. */
function defaultSleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
/**
* Poll a transaction until it reaches a terminal state.
*
* - On `COMPLETE` resolves with the transaction (its `txHash` is populated once
* broadcast).
* - On `FAILED` / `CANCELLED` / `DENIED` throws a `SettleKitError`
* (`integration_error`) carrying the failure state and Circle error fields.
* - After exhausting `attempts` without a terminal state throws a retryable
* `SettleKitError` (`integration_error`) carrying the last-seen state.
*
* No `sleep` is awaited after the final attempt (off-by-one safe).
*/
export async function pollTransaction(
client: Pick<WalletsClient, "getTransaction">,
opts: PollTransactionOptions,
): Promise<CircleTransactionResource> {
requireString(opts.id, "pollTransaction.id");
const attempts = opts.attempts ?? DEFAULT_POLL_ATTEMPTS;
const delayMs = opts.delayMs ?? DEFAULT_POLL_DELAY_MS;
const sleep = opts.sleep ?? defaultSleep;
let lastState: CircleTransactionState | undefined;
for (let attempt = 0; attempt < attempts; attempt += 1) {
const tx = await client.getTransaction(opts.id);
lastState = tx.state;
if (tx.state === "COMPLETE") return tx;
if (TERMINAL_FAILURE_STATES.has(tx.state)) {
throw new SettleKitError({
code: "integration_error",
message: `Transaction ${opts.id} reached terminal failure state ${tx.state}`,
details: {
id: opts.id,
state: tx.state,
errorReason: tx.errorReason,
errorDetails: tx.errorDetails,
},
});
}
const isLastAttempt = attempt === attempts - 1;
if (!isLastAttempt) await sleep(delayMs);
}
throw new SettleKitError({
code: "integration_error",
message: `Transaction ${opts.id} did not reach a terminal state within ${attempts} attempts`,
retryable: true,
details: { id: opts.id, state: lastState, attempts },
});
}

View File

@ -14,6 +14,12 @@ export type {
CreateTransferInput,
} from "./client.js";
export { pollTransaction, buildContractExecutionRequest } from "./contract-execution.js";
export type {
CreateContractExecutionInput,
PollTransactionOptions,
} from "./contract-execution.js";
export { createUserWalletsClient } from "./user-wallets.js";
export type {
UserWalletsClient,

View File

@ -0,0 +1,284 @@
import { describe, expect, it, vi } from "vitest";
import { SettleKitError } from "@settlekit/common";
import { createWalletsClient, pollTransaction } from "../src/index.js";
import type {
CircleTransactionResource,
WalletsClient,
WalletsHttp,
WalletsRequest,
WalletsResponse,
} from "../src/index.js";
/** In-memory transport that records requests and returns scripted responses. */
function recordingHttp(responder: (req: WalletsRequest) => WalletsResponse): {
http: WalletsHttp;
requests: WalletsRequest[];
} {
const requests: WalletsRequest[] = [];
const http: WalletsHttp = {
async request(req: WalletsRequest): Promise<WalletsResponse> {
requests.push(req);
return responder(req);
},
};
return { http, requests };
}
const CIPHER = "ZmFrZS1jaXBoZXJ0ZXh0"; // base64-ish placeholder ciphertext
const CE_PATH = "/v1/w3s/developer/transactions/contractExecution";
/** A minimal transaction resource for poll stubs. */
function tx(
state: CircleTransactionResource["state"],
extra: Partial<CircleTransactionResource> = {},
): CircleTransactionResource {
return {
id: "tx_ce_1",
blockchain: "ETH-SEPOLIA",
state,
createDate: "2026-01-01T00:00:00Z",
updateDate: "2026-01-01T00:00:00Z",
...extra,
};
}
describe("createContractExecution", () => {
it("posts the contract execution request shape", async () => {
const { http, requests } = recordingHttp(() => ({
status: 201,
body: {
data: {
id: "tx_ce_1",
blockchain: "ETH-SEPOLIA",
state: "INITIATED",
createDate: "2026-01-01T00:00:00Z",
updateDate: "2026-01-01T00:00:00Z",
},
},
}));
const client = createWalletsClient({ apiKey: "k", http });
const result = await client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "mint(address,uint256)",
abiParameters: ["0xrecipient", 1],
feeLevel: "HIGH",
refId: "agent_42",
entitySecretCiphertext: CIPHER,
idempotencyKey: "idem-ce",
});
const req = requests[0]!;
expect(req.method).toBe("POST");
expect(req.path).toBe(CE_PATH);
expect(req.body).toMatchObject({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "mint(address,uint256)",
abiParameters: ["0xrecipient", 1],
feeLevel: "HIGH",
refId: "agent_42",
entitySecretCiphertext: CIPHER,
idempotencyKey: "idem-ce",
});
expect(result).toMatchObject({ id: "tx_ce_1", state: "INITIATED" });
});
it("defaults feeLevel to MEDIUM and does not mutate caller abiParameters", async () => {
const { http, requests } = recordingHttp(() => ({
status: 201,
body: {
data: {
id: "tx_ce_2",
blockchain: "ETH-SEPOLIA",
state: "INITIATED",
createDate: "2026-01-01T00:00:00Z",
updateDate: "2026-01-01T00:00:00Z",
},
},
}));
const client = createWalletsClient({ apiKey: "k", http });
const params: readonly (string | number | boolean)[] = ["0xrecipient", 5, true];
await client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "approve(address,uint256)",
abiParameters: params,
entitySecretCiphertext: CIPHER,
});
const body = requests[0]!.body as { feeLevel: string; abiParameters: unknown[] };
expect(body.feeLevel).toBe("MEDIUM");
// Fresh array, not the same reference.
expect(body.abiParameters).not.toBe(params);
expect(body.abiParameters).toEqual(["0xrecipient", 5, true]);
});
it("resolves the entity secret via the provider when no per-call ciphertext is given", async () => {
let calls = 0;
const { http, requests } = recordingHttp(() => ({
status: 201,
body: {
data: {
id: "tx_ce_3",
blockchain: "ETH-SEPOLIA",
state: "INITIATED",
createDate: "2026-01-01T00:00:00Z",
updateDate: "2026-01-01T00:00:00Z",
},
},
}));
const client = createWalletsClient({
apiKey: "k",
http,
entitySecretProvider: () => {
calls += 1;
return `cipher-${calls}`;
},
});
await client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "mint(address,uint256)",
abiParameters: ["0xrecipient", 1],
});
expect(calls).toBe(1);
expect((requests[0]!.body as { entitySecretCiphertext: string }).entitySecretCiphertext).toBe(
"cipher-1",
);
});
it("rejects when no entity secret source is available", async () => {
const { http } = recordingHttp(() => ({ status: 201, body: { data: tx("INITIATED") } }));
const client = createWalletsClient({ apiKey: "k", http });
await expect(
client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "mint(address,uint256)",
abiParameters: [],
}),
).rejects.toThrow(/entitySecretCiphertext/);
});
it("rejects a missing contractAddress with a validation error", async () => {
const { http } = recordingHttp(() => ({ status: 201, body: { data: tx("INITIATED") } }));
const client = createWalletsClient({ apiKey: "k", http });
await expect(
client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "",
abiFunctionSignature: "mint(address,uint256)",
abiParameters: [],
entitySecretCiphertext: CIPHER,
}),
).rejects.toMatchObject({ code: "validation_error" });
});
it("rejects an empty abiFunctionSignature with a validation error", async () => {
const { http } = recordingHttp(() => ({ status: 201, body: { data: tx("INITIATED") } }));
const client = createWalletsClient({ apiKey: "k", http });
await expect(
client.createContractExecution({
walletAddress: "0xwallet",
blockchain: "ETH-SEPOLIA",
contractAddress: "0xcontract",
abiFunctionSignature: "",
abiParameters: [],
entitySecretCiphertext: CIPHER,
}),
).rejects.toBeInstanceOf(SettleKitError);
});
});
/** Build a stub client exposing only getTransaction, scripted by a queue. */
function stubClient(states: CircleTransactionResource[]): {
client: Pick<WalletsClient, "getTransaction">;
getTransaction: ReturnType<typeof vi.fn>;
} {
let i = 0;
const getTransaction = vi.fn(async () => {
const next = states[Math.min(i, states.length - 1)]!;
i += 1;
return next;
});
return { client: { getTransaction }, getTransaction };
}
describe("pollTransaction", () => {
it("polls until COMPLETE and returns the transaction with txHash", async () => {
const { client, getTransaction } = stubClient([
tx("CONFIRMED"),
tx("CONFIRMED"),
tx("COMPLETE", { txHash: "0xhash" }),
]);
const sleep = vi.fn(async () => {});
const result = await pollTransaction(client, {
id: "tx_ce_1",
attempts: 5,
delayMs: 1000,
sleep,
});
expect(result.txHash).toBe("0xhash");
expect(getTransaction).toHaveBeenCalledTimes(3);
expect(sleep).toHaveBeenCalledTimes(2);
expect(sleep).toHaveBeenNthCalledWith(1, 1000);
expect(sleep).toHaveBeenNthCalledWith(2, 1000);
});
it("throws on a FAILED terminal state carrying error fields", async () => {
const { client } = stubClient([
tx("FAILED", { errorReason: "reverted", errorDetails: "OOG" }),
]);
const sleep = vi.fn(async () => {});
await expect(
pollTransaction(client, { id: "tx_ce_1", attempts: 5, delayMs: 1000, sleep }),
).rejects.toMatchObject({
code: "integration_error",
details: { state: "FAILED", errorReason: "reverted", errorDetails: "OOG" },
});
expect(sleep).not.toHaveBeenCalled();
});
it("throws on a CANCELLED terminal state", async () => {
const { client } = stubClient([tx("CANCELLED")]);
await expect(
pollTransaction(client, { id: "tx_ce_1", attempts: 5, sleep: async () => {} }),
).rejects.toMatchObject({ code: "integration_error", details: { state: "CANCELLED" } });
});
it("times out with a retryable error after exhausting attempts", async () => {
const { client, getTransaction } = stubClient([tx("SENT")]);
const sleep = vi.fn(async () => {});
await expect(
pollTransaction(client, { id: "tx_ce_1", attempts: 3, delayMs: 500, sleep }),
).rejects.toMatchObject({
code: "integration_error",
retryable: true,
details: { state: "SENT", attempts: 3 },
});
expect(getTransaction).toHaveBeenCalledTimes(3);
expect(sleep).toHaveBeenCalledTimes(2); // no sleep after the final attempt
});
it("rejects an empty id with a validation error", async () => {
const { client } = stubClient([tx("COMPLETE", { txHash: "0xhash" })]);
await expect(
pollTransaction(client, { id: "", sleep: async () => {} }),
).rejects.toMatchObject({ code: "validation_error" });
});
});

321
packages/erc8004/README.md Normal file
View File

@ -0,0 +1,321 @@
# @settlekit/erc8004
ERC-8004 agent identity, reputation, and validation on [Arc](https://docs.arc.io),
exposed through a SettleKit-idiomatic facade that returns `Result` values instead
of throwing.
ERC-8004 gives autonomous agents:
- **Identity** — an ERC-721 minted by the **IdentityRegistry** (`register(string)`).
- **Reputation** — feedback attestations recorded by external validators in the
**ReputationRegistry** (`giveFeedback(...)`).
- **Validation** — a request/response flow in the **ValidationRegistry**
(`validationRequest(...)` / `validationResponse(...)` / `getValidationStatus(bytes32)`).
Deployed Arc Testnet registry addresses are exported from
[`src/addresses.ts`](./src/addresses.ts) as `ARC_TESTNET_REGISTRIES`.
## Design: port / adapter (no chain dependency)
This package depends only on `@settlekit/common`. It **never imports a chain
library**. The on-chain operations are declared as an injectable interface — the
[`Erc8004Port`](./src/port.ts) — which the consumer implements with viem, ethers,
or Circle Developer-Controlled Wallets, capturing the signing adapter by closure.
This mirrors the proven pattern in `@settlekit/app-kit`. Benefits: the package
stays dependency-light and chain-agnostic, and tests/demos inject a deterministic
[`LocalErc8004Port`](./src/local-port.ts).
## Quickstart (deterministic, in-memory)
```ts
import { configureErc8004, LocalErc8004Port } from "@settlekit/erc8004";
import { isOk } from "@settlekit/common";
const port = new LocalErc8004Port({ owner: "0xowner" });
const registry = configureErc8004({ port });
const reg = await registry.registerAgent({ metadataUri: "ipfs://agent.json" });
if (isOk(reg)) console.log(reg.value.txHash); // 0xlocal00000001
const agent = await registry.resolveAgent({ owner: "0xowner" });
if (isOk(agent) && agent.value) console.log(agent.value.agentId); // "1"
```
## API reference: `AgentRegistryClient`
Every method returns `Promise<Result<T>>` from `@settlekit/common`
(`ok(value)` / `err(SettleKitError)`). Validation failures short-circuit with
`code: "validation_error"`; thrown port errors are mapped to
`code: "integration_error"` (`retryable: true`).
| Method | Validates | Returns |
| --- | --- | --- |
| `registerAgent({ metadataUri })` | non-empty `metadataUri` | `TxResult` |
| `resolveAgent({ owner })` | non-empty `owner` | `AgentIdentity \| null` |
| `giveFeedback(FeedbackInput)` | non-empty `agentId`/`tag`, integer `score` 0..100, `feedbackType` 0..255 (default 0) | `TxResult` |
| `requestValidation(ValidationRequestInput)` | non-empty `agentId`/`validator`/`requestUri`/`subject` | `ValidationRequestResult` (`TxResult` + `requestHash`) |
| `respondValidation(ValidationResponseInput)` | non-empty `requestHash`, integer `response` 0..100 | `TxResult` |
| `getValidationStatus({ requestHash })` | non-empty `requestHash` | `ValidationStatus` |
`resolveAgent` returns `ok(null)` when the owner has no registered agent.
### `requestHash` is port-owned
`requestValidation` does NOT take a hash — the **port** derives `requestHash`
from the stable `subject` string and returns it. The same subject reproduces the
same hash, so status can be looked up later.
`LocalErc8004Port` uses an FNV-1a hash (padded to a bytes32-shaped hex) for
stable in-memory lookup. **This is not chain-compatible.** A real on-chain port
must derive `requestHash` with the ValidationRegistry's actual scheme (typically
`keccak256`) so it matches what the contract stores.
## On-chain contract signatures
The consumer's port maps the domain inputs onto these ValidationRegistry /
ReputationRegistry / IdentityRegistry calls:
```solidity
// IdentityRegistry
register(string metadataUri)
// ReputationRegistry
giveFeedback(uint256 agentId, int128 score, uint8 feedbackType,
string tag, string metadataUri, string evidenceUri,
string comment, bytes32 ref)
// ValidationRegistry
validationRequest(address validator, uint256 agentId, string requestUri, bytes32 requestHash)
validationResponse(bytes32 requestHash, uint8 response, string responseUri, bytes32 tag, string note)
getValidationStatus(bytes32 requestHash)
```
Note: `score` is `int128` on-chain. This package validates `score` as an integer
in 0..100 (the documented convention); a consumer needing the wider `int128`
range can relax that in its own port.
## Wiring sketch 1 — viem
The port is consumer-owned (this package adds no viem dependency):
```ts
import {
createPublicClient, createWalletClient, http, keccak256, toHex, getAddress,
} from "viem";
import type { Erc8004Port } from "@settlekit/erc8004";
import { ARC_TESTNET_REGISTRIES, ARC_TESTNET_RPC_URL, explorerTxUrl } from "@settlekit/erc8004";
// Provide your own ABIs for the three registries.
import { identityAbi, reputationAbi, validationAbi } from "./abis.js";
export function createViemErc8004Port(opts: {
account: `0x${string}`;
transport?: ReturnType<typeof http>;
}): Erc8004Port {
const transport = opts.transport ?? http(ARC_TESTNET_RPC_URL);
const pub = createPublicClient({ transport });
const wallet = createWalletClient({ account: opts.account, transport });
const r = ARC_TESTNET_REGISTRIES;
return {
async register({ metadataUri }) {
const txHash = await wallet.writeContract({
address: r.identityRegistry as `0x${string}`,
abi: identityAbi,
functionName: "register",
args: [metadataUri],
});
return { txHash, explorerUrl: explorerTxUrl(txHash) };
},
async findAgentId({ owner }) {
const id = (await pub.readContract({
address: r.identityRegistry as `0x${string}`,
abi: identityAbi,
functionName: "agentIdOf",
args: [getAddress(owner)],
})) as bigint;
return id === 0n ? null : id.toString();
},
async ownerOf({ agentId }) {
return (await pub.readContract({
address: r.identityRegistry as `0x${string}`,
abi: identityAbi,
functionName: "ownerOf",
args: [BigInt(agentId)],
})) as string;
},
async tokenUri({ agentId }) {
return (await pub.readContract({
address: r.identityRegistry as `0x${string}`,
abi: identityAbi,
functionName: "tokenURI",
args: [BigInt(agentId)],
})) as string;
},
async giveFeedback(input) {
const txHash = await wallet.writeContract({
address: r.reputationRegistry as `0x${string}`,
abi: reputationAbi,
functionName: "giveFeedback",
args: [
BigInt(input.agentId), BigInt(input.score), input.feedbackType ?? 0,
input.tag, input.metadataUri ?? "", input.evidenceUri ?? "",
input.comment ?? "", "0x".padEnd(66, "0") as `0x${string}`,
],
});
return { txHash, explorerUrl: explorerTxUrl(txHash) };
},
async requestValidation(input) {
// The port owns hashing — keep this aligned with the contract's scheme.
const requestHash = keccak256(toHex(input.subject));
const txHash = await wallet.writeContract({
address: r.validationRegistry as `0x${string}`,
abi: validationAbi,
functionName: "validationRequest",
args: [getAddress(input.validator), BigInt(input.agentId), input.requestUri, requestHash],
});
return { txHash, explorerUrl: explorerTxUrl(txHash), requestHash };
},
async respondValidation(input) {
const txHash = await wallet.writeContract({
address: r.validationRegistry as `0x${string}`,
abi: validationAbi,
functionName: "validationResponse",
args: [
input.requestHash as `0x${string}`, input.response, input.responseUri ?? "",
("0x" + (input.tag ?? "").padEnd(64, "0")).slice(0, 66) as `0x${string}`, "",
],
});
return { txHash, explorerUrl: explorerTxUrl(txHash) };
},
async getValidationStatus({ requestHash }) {
const [validator, agentId, response, tag] = (await pub.readContract({
address: r.validationRegistry as `0x${string}`,
abi: validationAbi,
functionName: "getValidationStatus",
args: [requestHash as `0x${string}`],
})) as [string, bigint, number, string];
return { validator, agentId: agentId.toString(), response, tag, passed: response === 100 };
},
};
}
```
```ts
import { configureErc8004 } from "@settlekit/erc8004";
const registry = configureErc8004({ port: createViemErc8004Port({ account }) });
```
## Wiring sketch 2 — Circle Developer-Controlled Wallets
Submit the same contract calls through DCW contract-execution. Encode the
function call (e.g. with viem's `encodeFunctionData`) and submit via the DCW SDK:
```ts
import { initiateDeveloperControlledWalletsClient } from "@circle-fin/developer-controlled-wallets";
import { encodeFunctionData, keccak256, toHex } from "viem";
import type { Erc8004Port } from "@settlekit/erc8004";
import { ARC_TESTNET_REGISTRIES, explorerTxUrl } from "@settlekit/erc8004";
import { identityAbi, reputationAbi, validationAbi } from "./abis.js";
export function createCircleDcwErc8004Port(opts: {
walletId: string;
apiKey: string;
entitySecret: string;
}): Erc8004Port {
const dcw = initiateDeveloperControlledWalletsClient({
apiKey: opts.apiKey,
entitySecret: opts.entitySecret,
});
const r = ARC_TESTNET_REGISTRIES;
async function exec(address: string, callData: `0x${string}`) {
const res = await dcw.createContractExecutionTransaction({
walletId: opts.walletId,
contractAddress: address,
callData,
fee: { type: "level", config: { feeLevel: "MEDIUM" } },
});
const txHash = res.data?.txHash ?? res.data?.id ?? "";
return { txHash, explorerUrl: explorerTxUrl(txHash) };
}
return {
async register({ metadataUri }) {
return exec(
r.identityRegistry,
encodeFunctionData({ abi: identityAbi, functionName: "register", args: [metadataUri] }),
);
},
async requestValidation(input) {
const requestHash = keccak256(toHex(input.subject)); // align with contract scheme
const tx = await exec(
r.validationRegistry,
encodeFunctionData({
abi: validationAbi,
functionName: "validationRequest",
args: [input.validator, BigInt(input.agentId), input.requestUri, requestHash],
}),
);
return { ...tx, requestHash };
},
// findAgentId / ownerOf / tokenUri / getValidationStatus are read-only:
// use a viem/ethers public client (DCW is for signing writes), or the
// chain RPC directly. giveFeedback / respondValidation mirror register
// via encodeFunctionData + exec(...).
findAgentId: async () => null,
ownerOf: async () => "",
tokenUri: async () => "",
giveFeedback: async (input) =>
exec(
r.reputationRegistry,
encodeFunctionData({
abi: reputationAbi,
functionName: "giveFeedback",
args: [
BigInt(input.agentId), BigInt(input.score), input.feedbackType ?? 0,
input.tag, input.metadataUri ?? "", input.evidenceUri ?? "",
input.comment ?? "", ("0x".padEnd(66, "0")) as `0x${string}`,
],
}),
),
respondValidation: async (input) =>
exec(
r.validationRegistry,
encodeFunctionData({
abi: validationAbi,
functionName: "validationResponse",
args: [
input.requestHash as `0x${string}`, input.response, input.responseUri ?? "",
("0x".padEnd(66, "0")) as `0x${string}`, "",
],
}),
),
getValidationStatus: async () => {
throw new Error("read getValidationStatus via a public client");
},
};
}
```
> The two sketches are illustrative. ABIs, the exact read function names
> (`agentIdOf`, etc.), and the contract's `requestHash` scheme must match the
> deployed Arc registries — confirm against the Arc docs before mainnet use.
## Testing
```bash
pnpm --filter @settlekit/erc8004 build
pnpm --filter @settlekit/erc8004 test
```
`LocalErc8004Port` is fully deterministic (no `Date.now()` / `Math.random()`):
sequential agent ids, counter-based tx hashes, FNV-1a request hashes.

View File

@ -0,0 +1,26 @@
{
"name": "@settlekit/erc8004",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "tsc -b",
"test": "vitest run"
},
"dependencies": {
"@settlekit/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.14.0",
"typescript": "^5.5.4",
"vitest": "^2.0.5"
}
}

View File

@ -0,0 +1,39 @@
/**
* ERC-8004 on-chain registry addresses on Arc.
*
* ERC-8004 gives autonomous agents an on-chain identity (an ERC-721 minted by
* the IdentityRegistry), reputation (attestations recorded by external
* validators in the ReputationRegistry), and a request/response validation flow
* (the ValidationRegistry). These are the deployed Arc Testnet addresses from
* the Arc docs — verify against https://docs.arc.io before mainnet use.
*/
/** A set of ERC-8004 registry addresses for one network. */
export interface Erc8004Registries {
identityRegistry: string;
reputationRegistry: string;
validationRegistry: string;
}
/** Arc Testnet ERC-8004 registries. */
export const ARC_TESTNET_REGISTRIES: Erc8004Registries = {
identityRegistry: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
reputationRegistry: "0x8004B663056A597Dffe9eCcC1965A193B7388713",
validationRegistry: "0x8004Cb1BF31DAf7788923b405b754f57acEB4272",
};
/** Arc Testnet JSON-RPC endpoint. */
export const ARC_TESTNET_RPC_URL = "https://rpc.testnet.arc.network/";
/** Arc Testnet block explorer base. */
export const ARC_TESTNET_EXPLORER = "https://testnet.arcscan.app";
/** Build an explorer URL for a transaction hash. */
export function explorerTxUrl(txHash: string, base = ARC_TESTNET_EXPLORER): string {
return `${base}/tx/${txHash}`;
}
/** Build an explorer URL for an address. */
export function explorerAddressUrl(address: string, base = ARC_TESTNET_EXPLORER): string {
return `${base}/address/${address}`;
}

View File

@ -0,0 +1,150 @@
/**
* {@link AgentRegistryClient} — the SettleKit-idiomatic facade over an injected
* {@link Erc8004Port}. Every method validates its request, calls the port, and
* returns a `Result` instead of throwing, so callers handle success/failure
* uniformly. Mirrors app-kit's `ArcPaymentClient`.
*/
import { type Result, SettleKitError, err, ok } from "@settlekit/common";
import type { Erc8004Port } from "./port.js";
import type {
AgentIdentity,
FeedbackInput,
TxResult,
ValidationRequestInput,
ValidationRequestResult,
ValidationResponseInput,
ValidationStatus,
} from "./types.js";
import {
firstError,
validateAddress,
validateIntInRange,
validateNonEmpty,
validateScore,
} from "./validate.js";
/** Default feedback category when a request omits one. */
const DEFAULT_FEEDBACK_TYPE = 0;
/** Inclusive bounds for the uint8 `feedbackType` field. */
const FEEDBACK_TYPE_MIN = 0;
const FEEDBACK_TYPE_MAX = 255;
/** Inclusive bounds for the uint8 validation `response` field (0..100). */
const RESPONSE_MIN = 0;
const RESPONSE_MAX = 100;
/** Configuration for an {@link AgentRegistryClient}. */
export interface AgentRegistryClientConfig {
/** The injected ERC-8004 port (viem/Circle DCW impl, or {@link LocalErc8004Port}). */
port: Erc8004Port;
}
export class AgentRegistryClient {
private readonly port: Erc8004Port;
constructor(config: AgentRegistryClientConfig) {
this.port = config.port;
}
/** Wrap a port call, mapping thrown errors to a typed integration error. */
private async run<T>(op: string, call: () => Promise<T>): Promise<Result<T>> {
try {
const value = await call();
return ok(value);
} catch (cause) {
return err(
new SettleKitError({
code: "integration_error",
message: `erc8004 ${op} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
retryable: true,
cause,
details: { op },
}),
);
}
}
/** Mint a new agent identity with the given metadata URI. */
async registerAgent(input: { metadataUri: string }): Promise<Result<TxResult>> {
const invalid = firstError(validateNonEmpty(input.metadataUri, "metadataUri"));
if (invalid !== null) return err(invalid);
return this.run("register", () => this.port.register({ metadataUri: input.metadataUri }));
}
/**
* Resolve an owner's agent identity. Returns `ok(null)` when the owner has no
* registered agent.
*/
async resolveAgent(input: { owner: string }): Promise<Result<AgentIdentity | null>> {
const invalid = firstError(validateAddress(input.owner, "owner"));
if (invalid !== null) return err(invalid);
return this.run("resolveAgent", async () => {
const agentId = await this.port.findAgentId({ owner: input.owner });
if (agentId === null) return null;
const [owner, metadataUri] = await Promise.all([
this.port.ownerOf({ agentId }),
this.port.tokenUri({ agentId }),
]);
const identity: AgentIdentity = { agentId, owner, metadataUri };
return identity;
});
}
/** Record reputation feedback about an agent. */
async giveFeedback(input: FeedbackInput): Promise<Result<TxResult>> {
const feedbackType = input.feedbackType ?? DEFAULT_FEEDBACK_TYPE;
const invalid = firstError(
validateNonEmpty(input.agentId, "agentId"),
validateScore(input.score),
validateIntInRange(feedbackType, FEEDBACK_TYPE_MIN, FEEDBACK_TYPE_MAX, "feedbackType"),
validateNonEmpty(input.tag, "tag"),
);
if (invalid !== null) return err(invalid);
return this.run("giveFeedback", () =>
this.port.giveFeedback({ ...input, feedbackType }),
);
}
/** Submit a validation request; the port derives the request hash. */
async requestValidation(
input: ValidationRequestInput,
): Promise<Result<ValidationRequestResult>> {
const invalid = firstError(
validateNonEmpty(input.agentId, "agentId"),
validateAddress(input.validator, "validator"),
validateNonEmpty(input.requestUri, "requestUri"),
validateNonEmpty(input.subject, "subject"),
);
if (invalid !== null) return err(invalid);
return this.run("requestValidation", () => this.port.requestValidation(input));
}
/** Submit a validator's response to a prior request. */
async respondValidation(input: ValidationResponseInput): Promise<Result<TxResult>> {
const invalid = firstError(
validateNonEmpty(input.requestHash, "requestHash"),
validateIntInRange(input.response, RESPONSE_MIN, RESPONSE_MAX, "response"),
);
if (invalid !== null) return err(invalid);
return this.run("respondValidation", () => this.port.respondValidation(input));
}
/** Read the current status of a validation request by its hash. */
async getValidationStatus(input: {
requestHash: string;
}): Promise<Result<ValidationStatus>> {
const invalid = firstError(validateNonEmpty(input.requestHash, "requestHash"));
if (invalid !== null) return err(invalid);
return this.run("getValidationStatus", () =>
this.port.getValidationStatus({ requestHash: input.requestHash }),
);
}
}

View File

@ -0,0 +1,32 @@
/**
* One factory to build an {@link AgentRegistryClient}. The consumer injects a
* configured {@link Erc8004Port}; this package never depends on a chain library.
*
* Live wiring (in the consumer, which owns the chain dependency) — the port can
* be backed by viem or Circle Developer-Controlled Wallets:
*
* ```ts
* import { configureErc8004 } from "@settlekit/erc8004";
* import { createViemErc8004Port } from "./my-viem-port.js"; // consumer-owned
*
* const registry = configureErc8004({ port: createViemErc8004Port({ walletClient, publicClient }) });
* const res = await registry.registerAgent({ metadataUri: "ipfs://agent.json" });
* ```
*
* Tests and demos inject {@link LocalErc8004Port} instead of a real port.
* See the README for full viem and Circle DCW port sketches.
*/
import { AgentRegistryClient } from "./client.js";
import type { Erc8004Port } from "./port.js";
/** Options for {@link configureErc8004}. */
export interface ConfigureErc8004Options {
/** The injected ERC-8004 port implementation. */
port: Erc8004Port;
}
/** Build a configured {@link AgentRegistryClient}. */
export function configureErc8004(options: ConfigureErc8004Options): AgentRegistryClient {
return new AgentRegistryClient({ port: options.port });
}

View File

@ -0,0 +1,7 @@
export * from "./addresses.js";
export * from "./types.js";
export * from "./port.js";
export * from "./validate.js";
export * from "./client.js";
export * from "./local-port.js";
export * from "./configure.js";

View File

@ -0,0 +1,160 @@
/**
* {@link LocalErc8004Port} — a deterministic, in-memory {@link Erc8004Port} for
* tests, demos, and local development. It never touches a chain: it records
* every call and returns synthetic, monotonically-numbered transaction hashes
* so assertions are stable across runs. Mirrors app-kit's `LocalAppKitSdk`.
*
* Determinism: no `Date.now()` / `Math.random()`. Agent ids are sequential
* decimal strings; tx hashes are counter-based; `requestHash` is an FNV-1a hash
* of the subject padded to a bytes32-shaped hex.
*
* IMPORTANT: the FNV-1a `requestHash` is for stable in-memory lookup ONLY and
* is NOT chain-compatible. A real on-chain port derives bytes32 via the
* ValidationRegistry's actual hashing scheme (typically keccak256).
*/
import type { Erc8004Port } from "./port.js";
import type {
FeedbackInput,
TxResult,
ValidationRequestInput,
ValidationRequestResult,
ValidationResponseInput,
ValidationStatus,
} from "./types.js";
import { ARC_TESTNET_EXPLORER, explorerTxUrl } from "./addresses.js";
/**
* Response value that marks a validation as passed. Per {@link ./types.js}
* (`ValidationResponseInput`: "0–100; 100 = passed") we use a strict pass: a
* response equal to {@link PASS_THRESHOLD}.
*/
const PASS_THRESHOLD = 100;
/** FNV-1a 32-bit offset basis. */
const FNV_OFFSET_BASIS = 0x811c9dc5;
/** FNV-1a 32-bit prime. */
const FNV_PRIME = 0x01000193;
/**
* Stable FNV-1a (32-bit) hash of `subject`, rendered as a 0x-prefixed,
* 64-hex-char (bytes32-shaped) string. Deterministic and dependency-free.
*/
export function fnv1aHex(subject: string): string {
let hash = FNV_OFFSET_BASIS;
for (let i = 0; i < subject.length; i += 1) {
hash ^= subject.charCodeAt(i);
hash = Math.imul(hash, FNV_PRIME) >>> 0;
}
const word = hash.toString(16).padStart(8, "0");
return `0x${word.padStart(64, "0")}`;
}
/** Options controlling the local port's simulated behavior. */
export interface LocalErc8004Options {
/** The registering wallet that owns every agent minted by `register`. */
owner: string;
}
export class LocalErc8004Port implements Erc8004Port {
private readonly owner: string;
private agentSeq = 0;
private txCounter = 0;
private readonly metadataByAgent = new Map<string, string>();
private readonly ownerByAgent = new Map<string, string>();
private readonly feedbackRecords: FeedbackInput[] = [];
private readonly validations = new Map<string, ValidationStatus>();
constructor(options: LocalErc8004Options) {
this.owner = options.owner;
}
/** All recorded feedback, oldest first (for test assertions). */
feedback(): readonly FeedbackInput[] {
return [...this.feedbackRecords];
}
/** All registered agent ids, oldest first (for test assertions). */
agents(): readonly string[] {
return [...this.metadataByAgent.keys()];
}
/** Build a deterministic, counter-based transaction result. */
private tx(): TxResult {
this.txCounter += 1;
const txHash = `0xlocal${this.txCounter.toString(16).padStart(8, "0")}`;
return { txHash, explorerUrl: explorerTxUrl(txHash, ARC_TESTNET_EXPLORER) };
}
async register(input: { metadataUri: string }): Promise<TxResult> {
this.agentSeq += 1;
const agentId = String(this.agentSeq);
this.metadataByAgent.set(agentId, input.metadataUri);
this.ownerByAgent.set(agentId, this.owner);
return this.tx();
}
async findAgentId(input: { owner: string }): Promise<string | null> {
for (const [agentId, owner] of this.ownerByAgent) {
if (owner === input.owner) return agentId;
}
return null;
}
async ownerOf(input: { agentId: string }): Promise<string> {
const owner = this.ownerByAgent.get(input.agentId);
if (owner === undefined) {
throw new Error(`unknown agentId: ${input.agentId}`);
}
return owner;
}
async tokenUri(input: { agentId: string }): Promise<string> {
const uri = this.metadataByAgent.get(input.agentId);
if (uri === undefined) {
throw new Error(`unknown agentId: ${input.agentId}`);
}
return uri;
}
async giveFeedback(input: FeedbackInput): Promise<TxResult> {
this.feedbackRecords.push({ ...input });
return this.tx();
}
async requestValidation(input: ValidationRequestInput): Promise<ValidationRequestResult> {
const requestHash = fnv1aHex(input.subject);
const status: ValidationStatus = {
validator: input.validator,
agentId: input.agentId,
response: 0,
tag: "",
passed: false,
};
this.validations.set(requestHash, status);
return { ...this.tx(), requestHash };
}
async respondValidation(input: ValidationResponseInput): Promise<TxResult> {
const existing = this.validations.get(input.requestHash);
if (existing === undefined) {
throw new Error(`unknown requestHash: ${input.requestHash}`);
}
const updated: ValidationStatus = {
...existing,
response: input.response,
tag: input.tag ?? existing.tag,
passed: input.response === PASS_THRESHOLD,
};
this.validations.set(input.requestHash, updated);
return this.tx();
}
async getValidationStatus(input: { requestHash: string }): Promise<ValidationStatus> {
const status = this.validations.get(input.requestHash);
if (status === undefined) {
throw new Error(`unknown requestHash: ${input.requestHash}`);
}
return { ...status };
}
}

View File

@ -0,0 +1,56 @@
/**
* The minimal ERC-8004 on-chain surface this package depends on — a *port* the
* consumer injects (dependency inversion, mirroring app-kit's `AppKitSdk`).
*
* This package NEVER imports a chain library. A consumer-owned implementation
* (backed by viem, ethers, or Circle Developer-Controlled Wallets) satisfies
* this shape and captures its signing adapter by closure; tests and demos use
* {@link LocalErc8004Port}. Keeping the contract here means `@settlekit/erc8004`
* adds no external chain dependency.
*
* The port is intentionally NON-generic: {@link ./types.js} models all I/O with
* concrete domain types, so there is no signing-adapter type parameter.
*
* Note: the port owns `requestHash` derivation. `requestValidation` hashes the
* stable `subject` string into a bytes32-shaped handle; a real on-chain port
* must align that hashing with the ValidationRegistry contract's scheme.
*/
import type {
FeedbackInput,
TxResult,
ValidationRequestInput,
ValidationRequestResult,
ValidationResponseInput,
ValidationStatus,
} from "./types.js";
/** The injected ERC-8004 registry operations. */
export interface Erc8004Port {
/** Mint a new agent identity (ERC-721) with the given metadata URI. */
register(input: { metadataUri: string }): Promise<TxResult>;
/** Find the agent id owned by `owner`, or null if none is registered. */
findAgentId(input: { owner: string }): Promise<string | null>;
/** Resolve the owner wallet of an agent id. */
ownerOf(input: { agentId: string }): Promise<string>;
/** Resolve the metadata token URI of an agent id. */
tokenUri(input: { agentId: string }): Promise<string>;
/** Record reputation feedback about an agent. */
giveFeedback(input: FeedbackInput): Promise<TxResult>;
/**
* Submit a validation request. The port computes `requestHash` from
* `input.subject` and returns it on the result for later status lookups.
*/
requestValidation(input: ValidationRequestInput): Promise<ValidationRequestResult>;
/** Submit a validator's response to a prior request. */
respondValidation(input: ValidationResponseInput): Promise<TxResult>;
/** Read the current status of a validation request by its hash. */
getValidationStatus(input: { requestHash: string }): Promise<ValidationStatus>;
}

View File

@ -0,0 +1,76 @@
/**
* ERC-8004 domain types: agent identity, reputation feedback, and the
* request/response validation flow. Kept free of any chain library so the
* package depends only on `@settlekit/common`; the chain details live behind
* the injected {@link Erc8004Port}.
*/
/** An agent's on-chain identity. */
export interface AgentIdentity {
/** ERC-721 token id minted by the IdentityRegistry. */
agentId: string;
/** Wallet that owns the identity. */
owner: string;
/** Metadata URI (e.g. an IPFS document describing the agent). */
metadataUri: string;
}
/** Outcome of a state-changing call. */
export interface TxResult {
txHash: string;
explorerUrl?: string;
}
/** Reputation feedback recorded by a validator (never the agent's owner). */
export interface FeedbackInput {
agentId: string;
/** Score (contract type int128); convention is 0–100. */
score: number;
/** Feedback category (contract type uint8). Default 0. */
feedbackType?: number;
/** Short machine tag, e.g. "successful_trade". */
tag: string;
metadataUri?: string;
evidenceUri?: string;
comment?: string;
}
/** A request for a validator to attest something about an agent. */
export interface ValidationRequestInput {
agentId: string;
/** Validator wallet address that will respond. */
validator: string;
/** URI describing what is being validated. */
requestUri: string;
/**
* Stable subject string the port hashes into the on-chain request handle.
* The same subject reproduces the same handle, so status can be looked up.
*/
subject: string;
}
/** Handle to a submitted validation request. */
export interface ValidationRequestResult extends TxResult {
/** The on-chain request hash, used to read status later. */
requestHash: string;
}
/** A validator's response to a request. */
export interface ValidationResponseInput {
requestHash: string;
/** 0–100; 100 = passed. */
response: number;
responseUri?: string;
tag?: string;
}
/** Current status of a validation request. */
export interface ValidationStatus {
validator: string;
agentId: string;
/** 0–100 response; 0 when not yet answered. */
response: number;
tag: string;
/** Convenience: true when {@link ValidationStatus.response} indicates a pass. */
passed: boolean;
}

View File

@ -0,0 +1,69 @@
/**
* Boundary validation for ERC-8004 requests, mirroring app-kit's `validate.ts`.
* Each validator returns a `SettleKitError` describing the first problem, or
* `null` when the input is well-formed. Client methods short-circuit to
* `err(...)` so no malformed request ever reaches the port / chain.
*/
import { type SettleKitError, validationError } from "@settlekit/common";
/** Validate a non-empty, non-blank string field. */
export function validateNonEmpty(value: string, field: string): SettleKitError | null {
if (typeof value !== "string" || value.trim().length === 0) {
return validationError(`${field} is required`, { field });
}
return null;
}
/**
* Validate an integer within an inclusive range. Relies on
* {@link Number.isInteger} so `NaN`/`Infinity`/fractions are rejected (range
* comparisons alone would let `NaN` slip through).
*/
export function validateIntInRange(
value: number,
min: number,
max: number,
field: string,
): SettleKitError | null {
if (typeof value !== "number" || !Number.isInteger(value)) {
return validationError(`${field} must be an integer`, { field, value });
}
if (value < min || value > max) {
return validationError(`${field} must be between ${min} and ${max}`, {
field,
value,
min,
max,
});
}
return null;
}
/**
* Maximum reputation score this package enforces. The on-chain `score` type is
* `int128`, but the documented convention (see {@link ./types.js}) is 0–100.
* We require an integer in 0..100 here; consumers needing the wider int128
* range can validate it in their own port implementation.
*/
const MAX_SCORE = 100;
/** Validate a reputation score: an integer in the inclusive range 0..100. */
export function validateScore(score: number, field = "score"): SettleKitError | null {
return validateIntInRange(score, 0, MAX_SCORE, field);
}
/** Validate a non-empty wallet address (shape checking is the port's job). */
export function validateAddress(address: string, field = "address"): SettleKitError | null {
return validateNonEmpty(address, field);
}
/** Return the first non-null error from a list of checks, or null. */
export function firstError(
...checks: readonly (SettleKitError | null)[]
): SettleKitError | null {
for (const check of checks) {
if (check !== null) return check;
}
return null;
}

View File

@ -0,0 +1,298 @@
import { describe, expect, it } from "vitest";
import { isErr, isOk } from "@settlekit/common";
import {
AgentRegistryClient,
type Erc8004Port,
LocalErc8004Port,
configureErc8004,
fnv1aHex,
} from "../src/index.js";
const OWNER = "0xowner";
function setup(): { client: AgentRegistryClient; port: LocalErc8004Port } {
const port = new LocalErc8004Port({ owner: OWNER });
const client = configureErc8004({ port });
return { client, port };
}
describe("registerAgent + resolveAgent", () => {
it("registers and resolves an agent identity", async () => {
const { client, port } = setup();
const reg = await client.registerAgent({ metadataUri: "ipfs://a" });
expect(isOk(reg)).toBe(true);
if (!isOk(reg)) return;
expect(reg.value.txHash).toMatch(/^0xlocal/);
expect(reg.value.explorerUrl).toContain("arcscan");
const res = await client.resolveAgent({ owner: OWNER });
expect(isOk(res)).toBe(true);
if (!isOk(res)) return;
expect(res.value).not.toBeNull();
expect(res.value?.agentId).toBe("1");
expect(res.value?.owner).toBe(OWNER);
expect(res.value?.metadataUri).toBe("ipfs://a");
expect(port.agents()).toEqual(["1"]);
});
it("increments the agent id on the second register", async () => {
const { client } = setup();
await client.registerAgent({ metadataUri: "ipfs://a" });
const second = await client.registerAgent({ metadataUri: "ipfs://b" });
expect(isOk(second)).toBe(true);
// The second agent is owned by the same wallet; resolve returns the first,
// but the local port records both ids.
});
it("returns ok(null) for an unknown owner", async () => {
const { client } = setup();
const res = await client.resolveAgent({ owner: "0xnobody" });
expect(isOk(res)).toBe(true);
if (!isOk(res)) return;
expect(res.value).toBeNull();
});
it("rejects an empty metadataUri", async () => {
const { client } = setup();
const res = await client.registerAgent({ metadataUri: " " });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects an empty owner on resolve", async () => {
const { client } = setup();
const res = await client.resolveAgent({ owner: "" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
});
describe("giveFeedback validation", () => {
it("records valid feedback", async () => {
const { client, port } = setup();
const res = await client.giveFeedback({
agentId: "1",
score: 90,
tag: "successful_trade",
});
expect(isOk(res)).toBe(true);
if (!isOk(res)) return;
expect(res.value.txHash).toMatch(/^0xlocal/);
expect(port.feedback()).toHaveLength(1);
expect(port.feedback()[0]?.feedbackType).toBe(0);
});
it("rejects a non-integer score", async () => {
const { client } = setup();
const res = await client.giveFeedback({ agentId: "1", score: 90.5, tag: "t" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects a negative score", async () => {
const { client } = setup();
const res = await client.giveFeedback({ agentId: "1", score: -1, tag: "t" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects a feedbackType above 255", async () => {
const { client } = setup();
const res = await client.giveFeedback({
agentId: "1",
score: 50,
feedbackType: 256,
tag: "t",
});
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("accepts feedbackType 0 as the default", async () => {
const { client } = setup();
const res = await client.giveFeedback({
agentId: "1",
score: 50,
feedbackType: 0,
tag: "t",
});
expect(isOk(res)).toBe(true);
});
it("rejects an empty tag", async () => {
const { client } = setup();
const res = await client.giveFeedback({ agentId: "1", score: 50, tag: "" });
expect(isErr(res)).toBe(true);
});
it("rejects an empty agentId", async () => {
const { client } = setup();
const res = await client.giveFeedback({ agentId: "", score: 50, tag: "t" });
expect(isErr(res)).toBe(true);
});
});
describe("validation request/respond/status round-trip", () => {
it("requests, responds, and reads status", async () => {
const { client } = setup();
await client.registerAgent({ metadataUri: "ipfs://a" });
const req = await client.requestValidation({
agentId: "1",
validator: "0xval",
requestUri: "ipfs://r",
subject: "job-42",
});
expect(isOk(req)).toBe(true);
if (!isOk(req)) return;
expect(req.value.requestHash.startsWith("0x")).toBe(true);
expect(req.value.requestHash).toHaveLength(66);
const requestHash = req.value.requestHash;
const respond = await client.respondValidation({ requestHash, response: 100, tag: "ok" });
expect(isOk(respond)).toBe(true);
const status = await client.getValidationStatus({ requestHash });
expect(isOk(status)).toBe(true);
if (!isOk(status)) return;
expect(status.value.response).toBe(100);
expect(status.value.passed).toBe(true);
expect(status.value.validator).toBe("0xval");
expect(status.value.agentId).toBe("1");
expect(status.value.tag).toBe("ok");
});
it("derives a stable requestHash for the same subject", async () => {
const { client } = setup();
const a = await client.requestValidation({
agentId: "1",
validator: "0xval",
requestUri: "ipfs://r",
subject: "job-42",
});
const b = await client.requestValidation({
agentId: "1",
validator: "0xval",
requestUri: "ipfs://r",
subject: "job-42",
});
const c = await client.requestValidation({
agentId: "1",
validator: "0xval",
requestUri: "ipfs://r",
subject: "different",
});
expect(isOk(a) && isOk(b) && isOk(c)).toBe(true);
if (!isOk(a) || !isOk(b) || !isOk(c)) return;
expect(a.value.requestHash).toBe(b.value.requestHash);
expect(a.value.requestHash).not.toBe(c.value.requestHash);
expect(a.value.requestHash).toBe(fnv1aHex("job-42"));
});
it("marks passed=false for a response below 100", async () => {
const { client } = setup();
const req = await client.requestValidation({
agentId: "1",
validator: "0xval",
requestUri: "ipfs://r",
subject: "partial",
});
if (!isOk(req)) return;
await client.respondValidation({ requestHash: req.value.requestHash, response: 50 });
const status = await client.getValidationStatus({ requestHash: req.value.requestHash });
if (!isOk(status)) return;
expect(status.value.passed).toBe(false);
expect(status.value.response).toBe(50);
});
it("rejects a response above 100", async () => {
const { client } = setup();
const res = await client.respondValidation({ requestHash: "0xdead", response: 101 });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects a non-integer response", async () => {
const { client } = setup();
const res = await client.respondValidation({ requestHash: "0xdead", response: 50.5 });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects an empty requestHash on respond", async () => {
const { client } = setup();
const res = await client.respondValidation({ requestHash: "", response: 100 });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects an empty requestHash on getValidationStatus", async () => {
const { client } = setup();
const res = await client.getValidationStatus({ requestHash: "" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
it("rejects an empty validator on request", async () => {
const { client } = setup();
const res = await client.requestValidation({
agentId: "1",
validator: "",
requestUri: "ipfs://r",
subject: "s",
});
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
});
describe("error mapping", () => {
it("maps a missing-agent ownerOf throw to a retryable integration_error", async () => {
// A port that has no registered agents: resolve finds an id but ownerOf
// throws. Use an inline port to force the findAgentId/ownerOf mismatch.
const throwingPort: Erc8004Port = {
register: async () => ({ txHash: "0x" }),
findAgentId: async () => "99",
ownerOf: async () => {
throw new Error("boom: unknown agentId");
},
tokenUri: async () => "ipfs://x",
giveFeedback: async () => ({ txHash: "0x" }),
requestValidation: async () => ({ txHash: "0x", requestHash: "0x0" }),
respondValidation: async () => ({ txHash: "0x" }),
getValidationStatus: async () => {
throw new Error("missing");
},
};
const client = new AgentRegistryClient({ port: throwingPort });
const res = await client.resolveAgent({ owner: OWNER });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("integration_error");
expect(res.error.retryable).toBe(true);
expect(res.error.message).toContain("resolveAgent");
});
it("maps a getValidationStatus throw to a retryable integration_error", async () => {
const { client } = setup();
const res = await client.getValidationStatus({ requestHash: "0xnotfound" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("integration_error");
expect(res.error.retryable).toBe(true);
expect(res.error.message).toContain("getValidationStatus");
});
});

View File

@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"composite": true
},
"references": [{ "path": "../common" }],
"include": ["src/**/*"],
"exclude": ["dist", "node_modules", "**/*.test.ts"]
}

181
packages/erc8183/README.md Normal file
View File

@ -0,0 +1,181 @@
# @settlekit/erc8183
ERC-8183 autonomous-agent **job lifecycle** on Arc — create a job, fund a USDC escrow, submit a deliverable, evaluate it, then settle to the worker or refund the requester — wrapped in SettleKit idioms.
ERC-8183 models a unit of agent work as an on-chain job with an escrowed USDC payout. This package wraps that lifecycle with decimal-USDC amounts ([`Money`](../common/src/money.ts)), boundary validation, an explicit state machine, and `Result`-typed outcomes that never throw across the boundary.
## Job state machine
```
cancel cancel
created ───────► cancelled funded ───────► cancelled
│ │
fund │ submit │ refund
▼ ▼ ───────► refunded
funded ──────────────────► submitted
│ │
refund│ evaluate_ │ evaluate_
▼ pass/fail ▼
refunded evaluated ──────► refunded (refund)
│
settle │ (only when evaluation.passed)
▼
settled
```
Happy path: `created → funded → submitted → evaluated → settled`. Terminal states (`settled`, `refunded`, `cancelled`) have no outgoing transitions.
`evaluate` maps **both** a pass and a fail to the single `evaluated` status. The "cannot settle a failed evaluation" rule is therefore enforced by the port (and a fast-fail client pre-check), not by the transition table alone.
## Design: inject the port, take no dependency
Following the `app-kit` / `settlement-core` provider pattern, this package defines the on-chain surface it needs (`Erc8183Port`) and the **consumer injects** an implementation. So `@settlekit/erc8183` depends only on `@settlekit/common` — it never imports a chain SDK, builds offline, and bundles anywhere. The consumer owns viem + Circle Developer-Controlled Wallets (DCW).
### The port the consumer implements
```ts
interface Erc8183Port {
createJob(p: { requester; worker; amountUsdc; specUri }): Promise<{ jobId; txHash }>;
fundEscrow(p: { jobId; amountUsdc }): Promise<TxResult>;
submitDeliverable(p: { jobId; deliverableUri }): Promise<TxResult>;
evaluate(p: { jobId; passed; scoreOrUri? }): Promise<TxResult>;
settle(p: { jobId }): Promise<TxResult>;
refund(p: { jobId }): Promise<TxResult>;
getJob(p: { jobId }): Promise<Job>;
}
```
## Usage
```ts
import { configureErc8183, type Erc8183Port } from "@settlekit/erc8183";
const port: Erc8183Port = /* viem + Circle DCW implementation, see below */;
const jobs = configureErc8183({ port });
const created = await jobs.createJob({
requester: "0xreq",
worker: "0xworker",
amountUsdc: "100.00",
specUri: "ipfs://spec",
});
if (!created.ok) throw created.error;
const { jobId } = created.value;
await jobs.fundEscrow({ jobId, amountUsdc: "100.00" });
await jobs.submitDeliverable({ jobId, deliverableUri: "ipfs://deliverable" });
await jobs.evaluate({ jobId, passed: true, scoreOrUri: "0.95" });
const settled = await jobs.settle({ jobId });
if (settled.ok) console.log(settled.value.txHash);
```
Every method returns `Result<T>`. Validation failures surface as `validation_error`, illegal state transitions as `conflict`, missing jobs as `not_found`, and any other thrown port error as a **retryable** `integration_error`. A `SettleKitError` thrown by the port (conflict/not_found) passes through with its code preserved rather than being masked.
## Testing & demos
Inject `LocalErc8183Port` — a deterministic, in-memory port that enforces the state machine, mints sequential `job_N` ids, and returns synthetic monotonically-numbered tx hashes (`0xlocal…`). No chain, no network, no `Date.now`/`Math.random`:
```ts
import { configureErc8183, LocalErc8183Port } from "@settlekit/erc8183";
const port = new LocalErc8183Port(); // or { throwOn: ["createJob"] } to exercise error mapping
const jobs = configureErc8183({ port });
```
## Wiring sketch: viem + Circle Developer-Controlled Wallets
This package does **not** depend on viem — the consumer implements `Erc8183Port` against the ERC-8183 job contract. A typical implementation backs a viem `walletClient` with a Circle DCW signer:
```ts
import { createPublicClient, createWalletClient, http, parseUnits } from "viem";
import { configureErc8183, type Erc8183Port, type Job, type TxResult } from "@settlekit/erc8183";
import { money } from "@settlekit/common";
// import a Circle DCW -> viem account adapter from your own wiring layer
const ERC8183_ABI = [/* createJob / fundEscrow / submitDeliverable / evaluate / settle / refund / jobs(...) */] as const;
const CONTRACT = "0xJobContract" as const;
const USDC_DECIMALS = 6;
const account = /* viem Account backed by a Circle Developer-Controlled Wallet */;
const walletClient = createWalletClient({ account, chain: arc, transport: http(RPC_URL) });
const publicClient = createPublicClient({ chain: arc, transport: http(RPC_URL) });
async function wait(hash: `0x${string}`): Promise<TxResult> {
const receipt = await publicClient.waitForTransactionReceipt({ hash });
return { txHash: hash, status: receipt.status === "success" ? "success" : "failed" };
}
const port: Erc8183Port = {
async createJob({ requester, worker, amountUsdc, specUri }) {
const hash = await walletClient.writeContract({
address: CONTRACT,
abi: ERC8183_ABI,
functionName: "createJob",
args: [requester, worker, parseUnits(amountUsdc, USDC_DECIMALS), specUri],
});
const receipt = await publicClient.waitForTransactionReceipt({ hash });
const jobId = decodeJobIdFromLogs(receipt.logs); // contract emits the on-chain job id
return { jobId, txHash: hash };
},
async fundEscrow({ jobId, amountUsdc }) {
// USDC approve(CONTRACT, amount) first, then:
const hash = await walletClient.writeContract({
address: CONTRACT,
abi: ERC8183_ABI,
functionName: "fundEscrow",
args: [BigInt(jobId), parseUnits(amountUsdc, USDC_DECIMALS)],
});
return wait(hash);
},
async submitDeliverable({ jobId, deliverableUri }) {
const hash = await walletClient.writeContract({
address: CONTRACT, abi: ERC8183_ABI, functionName: "submitDeliverable",
args: [BigInt(jobId), deliverableUri],
});
return wait(hash);
},
async evaluate({ jobId, passed, scoreOrUri }) {
const hash = await walletClient.writeContract({
address: CONTRACT, abi: ERC8183_ABI, functionName: "evaluate",
args: [BigInt(jobId), passed, scoreOrUri ?? ""],
});
return wait(hash);
},
async settle({ jobId }) {
const hash = await walletClient.writeContract({
address: CONTRACT, abi: ERC8183_ABI, functionName: "settle", args: [BigInt(jobId)],
});
return wait(hash);
},
async refund({ jobId }) {
const hash = await walletClient.writeContract({
address: CONTRACT, abi: ERC8183_ABI, functionName: "refund", args: [BigInt(jobId)],
});
return wait(hash);
},
async getJob({ jobId }): Promise<Job> {
const raw = await publicClient.readContract({
address: CONTRACT, abi: ERC8183_ABI, functionName: "jobs", args: [BigInt(jobId)],
});
return {
id: jobId,
requester: raw.requester,
worker: raw.worker,
amount: money(formatUnits(raw.amount, USDC_DECIMALS)),
status: mapOnchainStatus(raw.status),
...(raw.deliverableUri ? { deliverableUri: raw.deliverableUri } : {}),
...(raw.hasEvaluation ? { evaluation: { passed: raw.passed, scoreOrUri: raw.scoreOrUri } } : {}),
};
},
};
const jobs = configureErc8183({ port });
```
The on-chain contract remains the authority on legal transitions; the SettleKit layer adds validation, a fast-fail pre-check, and uniform `Result` error handling.

View File

@ -0,0 +1,26 @@
{
"name": "@settlekit/erc8183",
"version": "0.0.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"],
"scripts": {
"build": "tsc -b",
"test": "vitest run"
},
"dependencies": {
"@settlekit/common": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.14.0",
"typescript": "^5.5.4",
"vitest": "^2.0.5"
}
}

View File

@ -0,0 +1,180 @@
/**
* {@link JobClient} — the SettleKit-idiomatic facade over an injected
* {@link Erc8183Port}. Every method validates its request, calls the port, and
* returns a `Result` instead of throwing, so callers handle success/failure
* uniformly. Thrown port errors are mapped to a retryable `integration_error`;
* when the thrown cause is already a {@link SettleKitError} (e.g. a `conflict`
* from an illegal on-chain transition or a `not_found`), its code is preserved
* rather than masked.
*/
import { type Result, SettleKitError, conflict, err, money, ok } from "@settlekit/common";
import type { Erc8183Port } from "./port.js";
import type {
CreateJobRequest,
CreateJobResult,
EvaluateRequest,
FundEscrowRequest,
Job,
JobIdRequest,
SubmitDeliverableRequest,
TxResult,
} from "./types.js";
import { firstError, validateAddress, validateAmount, validateNonEmpty } from "./validate.js";
/** Configuration for a {@link JobClient}. */
export interface JobClientConfig {
/** The injected ERC-8183 port (viem + DCW implementation, or a local mock). */
port: Erc8183Port;
}
export class JobClient {
private readonly port: Erc8183Port;
constructor(config: JobClientConfig) {
this.port = config.port;
}
/**
* Wrap a port call, mapping thrown errors to a typed error. A thrown
* {@link SettleKitError} (conflict/not_found/...) passes through with its code
* intact; any other throw becomes a retryable `integration_error`.
*/
private async run<T>(label: string, call: () => Promise<T>): Promise<Result<T>> {
try {
return ok(await call());
} catch (cause) {
if (SettleKitError.is(cause)) {
return err(cause);
}
return err(
new SettleKitError({
code: "integration_error",
message: `erc8183 ${label} failed: ${cause instanceof Error ? cause.message : String(cause)}`,
retryable: true,
cause,
details: { op: label },
}),
);
}
}
/** Create a job and post its spec, escrowing `amountUsdc` of USDC. */
async createJob(req: CreateJobRequest): Promise<Result<CreateJobResult>> {
const invalid = firstError(
validateAddress(req.requester, "requester"),
validateAddress(req.worker, "worker"),
validateNonEmpty(req.specUri, "specUri"),
validateAmount(req.amountUsdc),
);
if (invalid !== null) return err(invalid);
// Assert the amount is a canonical USDC value before touching the chain.
const amount = money(req.amountUsdc);
return this.run("createJob", () =>
this.port.createJob({
requester: req.requester,
worker: req.worker,
amountUsdc: amount.amount,
specUri: req.specUri,
}),
);
}
/** Fund the USDC escrow for an existing job. */
async fundEscrow(req: FundEscrowRequest): Promise<Result<TxResult>> {
const invalid = firstError(
validateNonEmpty(req.jobId, "jobId"),
validateAmount(req.amountUsdc),
);
if (invalid !== null) return err(invalid);
const amount = money(req.amountUsdc);
return this.run("fundEscrow", () =>
this.port.fundEscrow({ jobId: req.jobId, amountUsdc: amount.amount }),
);
}
/** Submit a deliverable for a funded job. */
async submitDeliverable(req: SubmitDeliverableRequest): Promise<Result<TxResult>> {
const invalid = firstError(
validateNonEmpty(req.jobId, "jobId"),
validateNonEmpty(req.deliverableUri, "deliverableUri"),
);
if (invalid !== null) return err(invalid);
return this.run("submitDeliverable", () =>
this.port.submitDeliverable({
jobId: req.jobId,
deliverableUri: req.deliverableUri,
}),
);
}
/** Record an evaluation verdict for a submitted job. */
async evaluate(req: EvaluateRequest): Promise<Result<TxResult>> {
const invalid = firstError(
validateNonEmpty(req.jobId, "jobId"),
req.scoreOrUri !== undefined ? validateNonEmpty(req.scoreOrUri, "scoreOrUri") : null,
);
if (invalid !== null) return err(invalid);
return this.run("evaluate", () =>
this.port.evaluate({
jobId: req.jobId,
passed: req.passed,
...(req.scoreOrUri !== undefined ? { scoreOrUri: req.scoreOrUri } : {}),
}),
);
}
/**
* Settle the escrow to the worker. Performs an optional fast-fail pre-check via
* {@link Erc8183Port.getJob} — rejecting with `conflict` when the job is not in
* `evaluated` status or did not pass — but the on-chain guard (port) remains
* authoritative.
*/
async settle(req: JobIdRequest): Promise<Result<TxResult>> {
const invalid = validateNonEmpty(req.jobId, "jobId");
if (invalid !== null) return err(invalid);
const precheck = await this.run("getJob", () => this.port.getJob({ jobId: req.jobId }));
if (!precheck.ok) return precheck;
const job = precheck.value;
if (job.status !== "evaluated") {
return err(
conflict(`cannot settle a job in status "${job.status}"`, {
jobId: req.jobId,
status: job.status,
}),
);
}
if (job.evaluation?.passed !== true) {
return err(
conflict("cannot settle a failed evaluation", {
jobId: req.jobId,
}),
);
}
return this.run("settle", () => this.port.settle({ jobId: req.jobId }));
}
/** Refund the escrow to the requester. */
async refund(req: JobIdRequest): Promise<Result<TxResult>> {
const invalid = validateNonEmpty(req.jobId, "jobId");
if (invalid !== null) return err(invalid);
return this.run("refund", () => this.port.refund({ jobId: req.jobId }));
}
/** Read the current state of a job. */
async getJob(req: JobIdRequest): Promise<Result<Job>> {
const invalid = validateNonEmpty(req.jobId, "jobId");
if (invalid !== null) return err(invalid);
return this.run("getJob", () => this.port.getJob({ jobId: req.jobId }));
}
}

View File

@ -0,0 +1,39 @@
/**
* One factory to build a {@link JobClient}. The consumer injects a configured
* {@link Erc8183Port} — there is no kit key or secret to read here, but the
* factory shape mirrors {@link import("@settlekit/app-kit").configureAppKit} for
* parity across SettleKit packages.
*
* Live wiring (in the consumer, which owns the viem + Circle DCW dependencies):
*
* ```ts
* import { createWalletClient, http } from "viem";
* import { configureErc8183, type Erc8183Port } from "@settlekit/erc8183";
*
* // Build a viem walletClient backed by a Circle Developer-Controlled Wallets
* // signer, then implement the port against the ERC-8183 job contract:
* const port: Erc8183Port = {
* async createJob({ requester, worker, amountUsdc, specUri }) { ... },
* async fundEscrow({ jobId, amountUsdc }) { ... },
* // submitDeliverable / evaluate / settle / refund / getJob
* };
*
* const jobs = configureErc8183({ port });
* const created = await jobs.createJob({ requester, worker, amountUsdc: "100.00", specUri });
* ```
*
* Tests/demos inject {@link import("./local-port.js").LocalErc8183Port} instead.
*/
import { JobClient, type JobClientConfig } from "./client.js";
/** Options for {@link configureErc8183}. */
export interface ConfigureErc8183Options {
/** The injected ERC-8183 port. */
port: JobClientConfig["port"];
}
/** Build a configured {@link JobClient}. */
export function configureErc8183(options: ConfigureErc8183Options): JobClient {
return new JobClient({ port: options.port });
}

View File

@ -0,0 +1,6 @@
export * from "./types.js";
export * from "./port.js";
export * from "./validate.js";
export * from "./client.js";
export * from "./local-port.js";
export * from "./configure.js";

View File

@ -0,0 +1,145 @@
/**
* {@link LocalErc8183Port} — a deterministic, in-memory {@link Erc8183Port} for
* tests, demos, and local development. It never touches a chain: it holds jobs
* in a `Map`, enforces the job state machine ({@link assertTransition}), mints
* sequential job ids (`job_1`, `job_2`, ...), and returns synthetic,
* monotonically-numbered transaction hashes so assertions are stable across
* runs. No `Math.random` / `Date.now` is used.
*
* Every state change creates a NEW {@link Job} object (immutability); stored
* jobs are never mutated in place.
*/
import { conflict, money, notFound } from "@settlekit/common";
import type { Erc8183Port } from "./port.js";
import { type Job, type JobEvaluation, type TxResult, assertTransition } from "./types.js";
/** Operations that may be forced to throw, to exercise client error mapping. */
export type LocalErc8183Op =
| "createJob"
| "fundEscrow"
| "submitDeliverable"
| "evaluate"
| "settle"
| "refund"
| "getJob";
/** Options controlling the local port's simulated behavior. */
export interface LocalErc8183Options {
/** Operations named here throw a generic Error, to exercise error mapping. */
throwOn?: readonly LocalErc8183Op[];
}
const SUCCESS: TxResult["status"] = "success";
export class LocalErc8183Port implements Erc8183Port {
private readonly jobsById = new Map<string, Job>();
private readonly throwOn: ReadonlySet<LocalErc8183Op>;
private jobCounter = 0;
private txCounter = 0;
constructor(options: LocalErc8183Options = {}) {
this.throwOn = new Set(options.throwOn ?? []);
}
/** A snapshot array of every stored job, for test assertions. */
jobs(): readonly Job[] {
return [...this.jobsById.values()];
}
/** Mint the next synthetic transaction hash. */
private nextTx(): string {
this.txCounter += 1;
return `0xlocal${this.txCounter.toString(16).padStart(8, "0")}`;
}
/** Throw the simulated failure for `op` when configured. */
private guard(op: LocalErc8183Op): void {
if (this.throwOn.has(op)) {
throw new Error(`simulated ${op} failure`);
}
}
/** Load a job or throw `not_found`. */
private require(jobId: string): Job {
const job = this.jobsById.get(jobId);
if (job === undefined) {
throw notFound(`job "${jobId}" was not found`, { jobId });
}
return job;
}
async createJob(p: {
requester: string;
worker: string;
amountUsdc: string;
specUri: string;
}): Promise<{ jobId: string; txHash: string }> {
this.guard("createJob");
this.jobCounter += 1;
const jobId = `job_${this.jobCounter}`;
const job: Job = {
id: jobId,
requester: p.requester,
worker: p.worker,
amount: money(p.amountUsdc),
status: "created",
};
this.jobsById.set(jobId, job);
return { jobId, txHash: this.nextTx() };
}
async fundEscrow(p: { jobId: string; amountUsdc: string }): Promise<TxResult> {
this.guard("fundEscrow");
const job = this.require(p.jobId);
const status = assertTransition(job.status, "fund");
this.jobsById.set(job.id, { ...job, status });
return { txHash: this.nextTx(), status: SUCCESS };
}
async submitDeliverable(p: { jobId: string; deliverableUri: string }): Promise<TxResult> {
this.guard("submitDeliverable");
const job = this.require(p.jobId);
const status = assertTransition(job.status, "submit");
this.jobsById.set(job.id, { ...job, status, deliverableUri: p.deliverableUri });
return { txHash: this.nextTx(), status: SUCCESS };
}
async evaluate(p: { jobId: string; passed: boolean; scoreOrUri?: string }): Promise<TxResult> {
this.guard("evaluate");
const job = this.require(p.jobId);
const status = assertTransition(job.status, p.passed ? "evaluate_pass" : "evaluate_fail");
const evaluation: JobEvaluation = {
passed: p.passed,
...(p.scoreOrUri !== undefined ? { scoreOrUri: p.scoreOrUri } : {}),
};
this.jobsById.set(job.id, { ...job, status, evaluation });
return { txHash: this.nextTx(), status: SUCCESS };
}
async settle(p: { jobId: string }): Promise<TxResult> {
this.guard("settle");
const job = this.require(p.jobId);
const status = assertTransition(job.status, "settle");
// The transition table allows settle from `evaluated` regardless of verdict;
// the lifecycle additionally forbids settling a failed evaluation.
if (job.evaluation?.passed !== true) {
throw conflict("cannot settle a failed evaluation", { jobId: p.jobId });
}
this.jobsById.set(job.id, { ...job, status });
return { txHash: this.nextTx(), status: SUCCESS };
}
async refund(p: { jobId: string }): Promise<TxResult> {
this.guard("refund");
const job = this.require(p.jobId);
const status = assertTransition(job.status, "refund");
this.jobsById.set(job.id, { ...job, status });
return { txHash: this.nextTx(), status: SUCCESS };
}
async getJob(p: { jobId: string }): Promise<Job> {
this.guard("getJob");
return this.require(p.jobId);
}
}

View File

@ -0,0 +1,42 @@
/**
* {@link Erc8183Port} — the minimal on-chain surface this package depends on, a
* *port* the consumer injects (dependency inversion, like settlement-core's
* providers). A real viem + Circle Developer-Controlled Wallets implementation
* against the ERC-8183 job contract satisfies this shape; tests and demos use
* {@link LocalErc8183Port}.
*
* Keeping the contract here means this package never imports a chain SDK and so
* adds no external dependency — the consumer owns viem/DCW and supplies the
* implementation.
*/
import type { Job, TxResult } from "./types.js";
/** The injected ERC-8183 on-chain job contract. */
export interface Erc8183Port {
/** Create a new job on-chain and post its spec. */
createJob(p: {
requester: string;
worker: string;
amountUsdc: string;
specUri: string;
}): Promise<{ jobId: string; txHash: string }>;
/** Fund the USDC escrow for an existing job. */
fundEscrow(p: { jobId: string; amountUsdc: string }): Promise<TxResult>;
/** Submit a deliverable for a funded job. */
submitDeliverable(p: { jobId: string; deliverableUri: string }): Promise<TxResult>;
/** Record an evaluation verdict for a submitted job. */
evaluate(p: { jobId: string; passed: boolean; scoreOrUri?: string }): Promise<TxResult>;
/** Settle the escrow to the worker (legal only after a passing evaluation). */
settle(p: { jobId: string }): Promise<TxResult>;
/** Refund the escrow to the requester. */
refund(p: { jobId: string }): Promise<TxResult>;
/** Read the current on-chain state of a job. */
getJob(p: { jobId: string }): Promise<Job>;
}

View File

@ -0,0 +1,204 @@
/**
* SettleKit-facing types for the ERC-8183 autonomous-agent job lifecycle on Arc.
*
* ERC-8183 models a unit of agent work as an on-chain *job*: a requester posts a
* spec and funds a USDC escrow, a worker submits a deliverable, an evaluator
* scores it, and the escrow either settles to the worker or refunds the
* requester. This package wraps that lifecycle in SettleKit idioms —
* decimal-USDC amounts ({@link Money}), schema-validated requests, a `Result`
* surface that never throws across the boundary, and an explicit state machine.
*
* The on-chain operations are injected through an {@link Erc8183Port} (dependency
* inversion) so this package never imports a chain SDK and adds no external
* dependency — the consumer supplies a viem + Circle DCW backed implementation,
* and tests/demos use the deterministic local port.
*/
import { type Money, conflict } from "@settlekit/common";
/** Lifecycle state of a job. */
export type JobStatus =
| "created"
| "funded"
| "submitted"
| "evaluated"
| "settled"
| "refunded"
| "cancelled";
/** A move between job statuses. */
export type JobTransition =
| "fund"
| "submit"
| "evaluate_pass"
| "evaluate_fail"
| "settle"
| "refund"
| "cancel";
/** The evaluator's verdict on a submitted deliverable. */
export interface JobEvaluation {
/** Whether the deliverable passed evaluation. */
passed: boolean;
/** An optional numeric score string or a URI to a detailed rubric. */
scoreOrUri?: string;
}
/** A job in the ERC-8183 lifecycle. */
export interface Job {
/** On-chain job identifier (port-minted). */
id: string;
/** Address of the party requesting and funding the work. */
requester: string;
/** Address of the agent performing the work. */
worker: string;
/** Escrowed USDC amount. */
amount: Money;
/** Current lifecycle status. */
status: JobStatus;
/** URI of the submitted deliverable, once present. */
deliverableUri?: string;
/** Evaluation verdict, once present. */
evaluation?: JobEvaluation;
}
/**
* The legal transition table for the job lifecycle.
*
* Read as: from `source` status, applying `transition` yields the target
* status. Any (source, transition) pair not present here is illegal and is
* rejected by {@link assertTransition} with a `conflict` (HTTP 409) error.
*
* Lifecycle (happy path):
* created -> funded -> submitted -> evaluated -> settled
*
* Branches:
* - a created or funded job may be cancelled before work begins.
* - a refund is permitted from funded/submitted/evaluated (escrow returns to
* the requester).
* - evaluate maps BOTH a pass and a fail to the single `evaluated` status; the
* "cannot settle a failed evaluation" rule is therefore enforced by the port
* (see LocalErc8183Port.settle), not expressible by this table alone.
*
* Terminal states (settled, refunded, cancelled) have no outgoing transitions.
*/
export const JOB_TRANSITIONS: Readonly<
Record<JobStatus, Readonly<Partial<Record<JobTransition, JobStatus>>>>
> = {
created: {
fund: "funded",
cancel: "cancelled",
},
funded: {
submit: "submitted",
refund: "refunded",
cancel: "cancelled",
},
submitted: {
evaluate_pass: "evaluated",
evaluate_fail: "evaluated",
refund: "refunded",
},
evaluated: {
settle: "settled",
refund: "refunded",
},
settled: {},
refunded: {},
cancelled: {},
};
/** Return the target status for a transition, or `undefined` if illegal. */
export function peekTransition(
status: JobStatus,
transition: JobTransition,
): JobStatus | undefined {
return JOB_TRANSITIONS[status][transition];
}
/** Whether `transition` is legal from the given `status`. */
export function canTransition(status: JobStatus, transition: JobTransition): boolean {
return peekTransition(status, transition) !== undefined;
}
/**
* Guard the job state machine: resolve the target status for a transition or
* throw a `conflict` {@link import("@settlekit/common").SettleKitError} (HTTP
* 409) describing the illegal move. This is the single enforcement point every
* transition funnels through.
*/
export function assertTransition(status: JobStatus, transition: JobTransition): JobStatus {
const next = peekTransition(status, transition);
if (next === undefined) {
throw conflict(`Illegal job transition "${transition}" from status "${status}".`, {
from: status,
transition,
});
}
return next;
}
/** Whether a status is terminal (no further transitions are possible). */
export function isTerminalJobStatus(status: JobStatus): boolean {
return Object.keys(JOB_TRANSITIONS[status]).length === 0;
}
/* -------------------------------------------------------------------------- */
/* Request / result shapes */
/* -------------------------------------------------------------------------- */
/** Create a new job and post its spec. */
export interface CreateJobRequest {
/** Address of the requester funding the work. */
requester: string;
/** Address of the worker that will perform the job. */
worker: string;
/** Decimal USDC amount to escrow, e.g. "100.00". */
amountUsdc: string;
/** URI of the job specification (e.g. ipfs://...). */
specUri: string;
}
/** Fund the USDC escrow for an existing job. */
export interface FundEscrowRequest {
jobId: string;
/** Decimal USDC amount to fund. */
amountUsdc: string;
}
/** Submit a deliverable for a funded job. */
export interface SubmitDeliverableRequest {
jobId: string;
/** URI of the submitted deliverable. */
deliverableUri: string;
}
/** Record an evaluation verdict for a submitted job. */
export interface EvaluateRequest {
jobId: string;
/** Whether the deliverable passed. */
passed: boolean;
/** Optional numeric score string or a URI to a detailed rubric. */
scoreOrUri?: string;
}
/** Address a single job by its id (settle/refund/getJob). */
export interface JobIdRequest {
jobId: string;
}
/** Result of creating a job. */
export interface CreateJobResult {
/** On-chain job identifier. */
jobId: string;
/** On-chain transaction hash. */
txHash: string;
}
/** Normalized result of an on-chain job operation. */
export interface TxResult {
/** On-chain transaction hash. */
txHash: string;
/** Status of the transaction. */
status: "success" | "pending" | "failed";
}

View File

@ -0,0 +1,48 @@
/**
* Boundary validation for ERC-8183 job requests. Each validator returns a
* `SettleKitError` describing the first problem, or `null` when the input is
* well-formed. Client methods short-circuit to `err(...)` so no malformed
* request ever reaches the port / chain.
*/
import { type SettleKitError, validationError } from "@settlekit/common";
/** Decimal amount with up to 6 fractional digits (USDC precision). */
const AMOUNT_RE = /^\d+(\.\d{1,6})?$/;
/** Validate a positive decimal amount string. */
export function validateAmount(amount: string, field = "amountUsdc"): SettleKitError | null {
if (typeof amount !== "string" || amount.length === 0) {
return validationError(`${field} is required`, { field });
}
if (!AMOUNT_RE.test(amount)) {
return validationError(`${field} must be a decimal with up to 6 places`, { field, amount });
}
if (Number(amount) <= 0) {
return validationError(`${field} must be greater than zero`, { field, amount });
}
return null;
}
/** Validate a non-empty trimmed string (addresses, URIs, ids). */
export function validateNonEmpty(value: string, field: string): SettleKitError | null {
if (typeof value !== "string" || value.trim().length === 0) {
return validationError(`${field} is required`, { field });
}
return null;
}
/** Validate a non-empty wallet address (alias of {@link validateNonEmpty}). */
export function validateAddress(address: string, field = "address"): SettleKitError | null {
return validateNonEmpty(address, field);
}
/** Return the first non-null error from a list of checks, or null. */
export function firstError(
...checks: readonly (SettleKitError | null)[]
): SettleKitError | null {
for (const check of checks) {
if (check !== null) return check;
}
return null;
}

View File

@ -0,0 +1,240 @@
import { describe, expect, it } from "vitest";
import { isErr, isOk } from "@settlekit/common";
import {
JobClient,
LocalErc8183Port,
type LocalErc8183Op,
configureErc8183,
} from "../src/index.js";
function setup(opts: { throwOn?: readonly LocalErc8183Op[] } = {}): {
client: JobClient;
port: LocalErc8183Port;
} {
const port = new LocalErc8183Port(opts.throwOn !== undefined ? { throwOn: opts.throwOn } : {});
const client = configureErc8183({ port });
return { client, port };
}
const VALID = {
requester: "0xreq",
worker: "0xwork",
amountUsdc: "100.00",
specUri: "ipfs://spec",
};
async function createOk(client: JobClient): Promise<string> {
const res = await client.createJob(VALID);
if (!isOk(res)) throw new Error("expected createJob ok");
return res.value.jobId;
}
describe("happy path", () => {
it("create -> fund -> submit -> evaluate(pass) -> settle", async () => {
const { client } = setup();
const created = await client.createJob(VALID);
expect(isOk(created)).toBe(true);
if (!isOk(created)) return;
expect(created.value.jobId).toBe("job_1");
expect(created.value.txHash).toMatch(/^0xlocal/);
const afterCreate = await client.getJob({ jobId: "job_1" });
expect(isOk(afterCreate)).toBe(true);
if (!isOk(afterCreate)) return;
expect(afterCreate.value.status).toBe("created");
expect(afterCreate.value.amount.amount).toBe("100");
expect(afterCreate.value.amount.currency).toBe("USDC");
const funded = await client.fundEscrow({ jobId: "job_1", amountUsdc: "100.00" });
expect(isOk(funded)).toBe(true);
expect(isOk(await client.getJob({ jobId: "job_1" }))).toBe(true);
const fundedJob = await client.getJob({ jobId: "job_1" });
if (!isOk(fundedJob)) return;
expect(fundedJob.value.status).toBe("funded");
const submitted = await client.submitDeliverable({
jobId: "job_1",
deliverableUri: "ipfs://deliverable",
});
expect(isOk(submitted)).toBe(true);
const submittedJob = await client.getJob({ jobId: "job_1" });
if (!isOk(submittedJob)) return;
expect(submittedJob.value.status).toBe("submitted");
expect(submittedJob.value.deliverableUri).toBe("ipfs://deliverable");
const evaluated = await client.evaluate({ jobId: "job_1", passed: true, scoreOrUri: "0.95" });
expect(isOk(evaluated)).toBe(true);
const evaluatedJob = await client.getJob({ jobId: "job_1" });
if (!isOk(evaluatedJob)) return;
expect(evaluatedJob.value.status).toBe("evaluated");
expect(evaluatedJob.value.evaluation?.passed).toBe(true);
expect(evaluatedJob.value.evaluation?.scoreOrUri).toBe("0.95");
const settled = await client.settle({ jobId: "job_1" });
expect(isOk(settled)).toBe(true);
const settledJob = await client.getJob({ jobId: "job_1" });
if (!isOk(settledJob)) return;
expect(settledJob.value.status).toBe("settled");
});
it("mints sequential job ids", async () => {
const { client } = setup();
expect(await createOk(client)).toBe("job_1");
expect(await createOk(client)).toBe("job_2");
});
});
describe("refund path", () => {
it("create -> fund -> refund", async () => {
const { client } = setup();
const jobId = await createOk(client);
expect(isOk(await client.fundEscrow({ jobId, amountUsdc: "100.00" }))).toBe(true);
const refunded = await client.refund({ jobId });
expect(isOk(refunded)).toBe(true);
const job = await client.getJob({ jobId });
if (!isOk(job)) return;
expect(job.value.status).toBe("refunded");
});
});
describe("evaluate-fail path", () => {
it("evaluated(fail) cannot settle but can refund", async () => {
const { client } = setup();
const jobId = await createOk(client);
await client.fundEscrow({ jobId, amountUsdc: "100.00" });
await client.submitDeliverable({ jobId, deliverableUri: "ipfs://d" });
const evaluated = await client.evaluate({ jobId, passed: false });
expect(isOk(evaluated)).toBe(true);
const job = await client.getJob({ jobId });
if (!isOk(job)) return;
expect(job.value.status).toBe("evaluated");
expect(job.value.evaluation?.passed).toBe(false);
const settled = await client.settle({ jobId });
expect(isErr(settled)).toBe(true);
if (!isErr(settled)) return;
expect(settled.error.code).toBe("conflict");
const refunded = await client.refund({ jobId });
expect(isOk(refunded)).toBe(true);
const after = await client.getJob({ jobId });
if (!isOk(after)) return;
expect(after.value.status).toBe("refunded");
});
});
describe("illegal-transition rejections", () => {
it("submit before funded -> conflict", async () => {
const { client } = setup();
const jobId = await createOk(client);
const res = await client.submitDeliverable({ jobId, deliverableUri: "ipfs://d" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("conflict");
});
it("settle before evaluated -> conflict", async () => {
const { client } = setup();
const jobId = await createOk(client);
await client.fundEscrow({ jobId, amountUsdc: "100.00" });
const res = await client.settle({ jobId });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("conflict");
});
it("evaluate before submitted -> conflict", async () => {
const { client } = setup();
const jobId = await createOk(client);
await client.fundEscrow({ jobId, amountUsdc: "100.00" });
const res = await client.evaluate({ jobId, passed: true });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("conflict");
});
it("double-fund -> conflict", async () => {
const { client } = setup();
const jobId = await createOk(client);
await client.fundEscrow({ jobId, amountUsdc: "100.00" });
const res = await client.fundEscrow({ jobId, amountUsdc: "100.00" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("conflict");
});
});
describe("validation rejections", () => {
it("rejects malformed/non-positive amounts on createJob", async () => {
const { client } = setup();
for (const amountUsdc of ["0", "-1", "1.2345678", "abc", ""]) {
const res = await client.createJob({ ...VALID, amountUsdc });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
}
});
it("rejects empty requester/worker/specUri", async () => {
const { client } = setup();
expect(isErr(await client.createJob({ ...VALID, requester: " " }))).toBe(true);
expect(isErr(await client.createJob({ ...VALID, worker: " " }))).toBe(true);
expect(isErr(await client.createJob({ ...VALID, specUri: " " }))).toBe(true);
});
it("rejects empty jobId on every job-addressed method", async () => {
const { client } = setup();
expect(isErr(await client.fundEscrow({ jobId: " ", amountUsdc: "1" }))).toBe(true);
expect(isErr(await client.submitDeliverable({ jobId: " ", deliverableUri: "x" }))).toBe(true);
expect(isErr(await client.evaluate({ jobId: " ", passed: true }))).toBe(true);
expect(isErr(await client.settle({ jobId: " " }))).toBe(true);
expect(isErr(await client.refund({ jobId: " " }))).toBe(true);
expect(isErr(await client.getJob({ jobId: " " }))).toBe(true);
});
it("rejects an empty scoreOrUri when provided", async () => {
const { client } = setup();
const jobId = await createOk(client);
const res = await client.evaluate({ jobId, passed: true, scoreOrUri: " " });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("validation_error");
});
});
describe("error mapping", () => {
it("maps a thrown createJob error to a retryable integration_error", async () => {
const { client } = setup({ throwOn: ["createJob"] });
const res = await client.createJob(VALID);
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("integration_error");
expect(res.error.retryable).toBe(true);
});
it("maps a thrown fundEscrow error to integration_error", async () => {
const { client } = setup({ throwOn: ["fundEscrow"] });
const jobId = await createOk(client);
const res = await client.fundEscrow({ jobId, amountUsdc: "1" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("integration_error");
});
it("maps a thrown getJob error to integration_error", async () => {
const { client } = setup({ throwOn: ["getJob"] });
const res = await client.getJob({ jobId: "job_1" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("integration_error");
});
it("preserves not_found for an unknown jobId rather than masking it", async () => {
const { client } = setup();
const res = await client.getJob({ jobId: "job_999" });
expect(isErr(res)).toBe(true);
if (!isErr(res)) return;
expect(res.error.code).toBe("not_found");
});
});

View File

@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { SettleKitError } from "@settlekit/common";
import {
assertTransition,
canTransition,
isTerminalJobStatus,
peekTransition,
} from "../src/index.js";
describe("job transition table", () => {
it("allows fund from created and forbids settle from created", () => {
expect(canTransition("created", "fund")).toBe(true);
expect(canTransition("created", "settle")).toBe(false);
});
it("peeks the target status for legal transitions", () => {
expect(peekTransition("created", "fund")).toBe("funded");
expect(peekTransition("funded", "submit")).toBe("submitted");
expect(peekTransition("submitted", "evaluate_pass")).toBe("evaluated");
expect(peekTransition("submitted", "evaluate_fail")).toBe("evaluated");
expect(peekTransition("evaluated", "settle")).toBe("settled");
expect(peekTransition("evaluated", "refund")).toBe("refunded");
});
it("returns undefined for illegal transitions", () => {
expect(peekTransition("created", "settle")).toBeUndefined();
expect(peekTransition("settled", "fund")).toBeUndefined();
});
it("assertTransition throws a conflict on an illegal move", () => {
try {
assertTransition("settled", "fund");
expect.unreachable("should have thrown");
} catch (error) {
expect(SettleKitError.is(error)).toBe(true);
if (!SettleKitError.is(error)) return;
expect(error.code).toBe("conflict");
}
});
it("assertTransition returns the next status on a legal move", () => {
expect(assertTransition("created", "fund")).toBe("funded");
});
it("identifies terminal statuses", () => {
expect(isTerminalJobStatus("settled")).toBe(true);
expect(isTerminalJobStatus("refunded")).toBe(true);
expect(isTerminalJobStatus("cancelled")).toBe(true);
expect(isTerminalJobStatus("created")).toBe(false);
expect(isTerminalJobStatus("evaluated")).toBe(false);
});
});

View File

@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"composite": true
},
"references": [{ "path": "../common" }],
"include": ["src/**/*"],
"exclude": ["dist", "node_modules", "**/*.test.ts"]
}

44
pnpm-lock.yaml generated
View File

@ -935,6 +935,18 @@ importers:
specifier: ^2.0.5
version: 2.1.9(@types/node@20.19.43)
packages/arc-chains:
devDependencies:
'@types/node':
specifier: ^20.14.0
version: 20.19.43
typescript:
specifier: ^5.5.4
version: 5.9.3
vitest:
specifier: ^2.0.5
version: 2.1.9(@types/node@20.19.43)
packages/attribution:
dependencies:
'@settlekit/common':
@ -1379,6 +1391,38 @@ importers:
specifier: ^2.0.5
version: 2.1.9(@types/node@20.19.43)
packages/erc8004:
dependencies:
'@settlekit/common':
specifier: workspace:*
version: link:../common
devDependencies:
'@types/node':
specifier: ^20.14.0
version: 20.19.43
typescript:
specifier: ^5.5.4
version: 5.9.3
vitest:
specifier: ^2.0.5
version: 2.1.9(@types/node@20.19.43)
packages/erc8183:
dependencies:
'@settlekit/common':
specifier: workspace:*
version: link:../common
devDependencies:
'@types/node':
specifier: ^20.14.0
version: 20.19.43
typescript:
specifier: ^5.5.4
version: 5.9.3
vitest:
specifier: ^2.0.5
version: 2.1.9(@types/node@20.19.43)
packages/escrow:
dependencies:
'@settlekit/common':