@agentbadge/circle-payments 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,203 @@
1
+ # @agentbadge/circle-payments
2
+
3
+ Circle Gateway nanopayments + x402 payment rails for AgentBadge — trusted
4
+ agent payments on **Base Sepolia** and **Arc**.
5
+
6
+ This package is the single boundary for everything payment-related in the
7
+ AgentBadge server: x402 scheme registration, payment routing, Hono
8
+ middleware, identity extensions, failure ledger, pricing, payment status /
9
+ history, and the ERC-8183 agentic-commerce escrow stack on Arc.
10
+
11
+ ## Boundary rule
12
+
13
+ All Circle SDK (`@circle-fin/x402-batching`) and x402 (`@x402/core`,
14
+ `@x402/evm`) usage stays **inside** this package. Server code imports only
15
+ from `@agentbadge/circle-payments` — never from the underlying SDKs directly.
16
+
17
+ ## Features
18
+
19
+ - **Three payment rails** behind one router:
20
+ - **Gateway batch** — gasless sub-cent USDC via Circle Gateway
21
+ (`BatchFacilitatorClient` + `GatewayEvmScheme`)
22
+ - **Exact** — standard x402 EIP-3009 `exact` scheme via a facilitator
23
+ (Base Sepolia)
24
+ - **`eip3009-client-broadcast`** — Arc self-settle: the buyer broadcasts
25
+ `transferWithAuthorization` themselves (gas paid in USDC, Arc's native
26
+ token — zero ETH, no facilitator), the server verifies the on-chain
27
+ receipt
28
+ - **`requirePayment` Hono middleware** — 402 challenge → verify → settle →
29
+ receipt headers, with identity extension injection
30
+ - **Identity extension** — embeds the seller's AgentBadge passport
31
+ (`passportTokenId`, `readinessScore`, `verifyUrl`) into 402 responses
32
+ - **ERC-8183 escrow** — full job lifecycle on Arc (`createJob → setBudget →
33
+ fund → submit → evaluate → complete`), evaluator with verdict store, and
34
+ commission split to treasury
35
+ - **ERC-8004 mirror** — passport registration in the ERC-8004
36
+ IdentityRegistry on Arc
37
+ - **Memo audit** — attach order/job metadata to settlement transactions via
38
+ the Arc Memo contract
39
+ - **Ops surface** — pricing table, payment status lookup, payment history,
40
+ failure ledger, wallet balance helpers
41
+
42
+ ## Architecture
43
+
44
+ ```mermaid
45
+ flowchart LR
46
+ subgraph Server["Hono server"]
47
+ MW["requirePayment()<br/>middleware"]
48
+ RT["createPaymentRouter()<br/>router.ts"]
49
+ PR["PRICE_TABLE<br/>pricing.ts"]
50
+ ID["identityExtension()<br/>identity.ts"]
51
+ LG["FailureStore<br/>ledger.ts"]
52
+ end
53
+
54
+ subgraph Schemes["Scheme handles (schemes/)"]
55
+ GW["Gateway batch<br/>gateway.ts"]
56
+ EX["Exact EIP-3009<br/>exact.ts"]
57
+ AS["Arc self-settle<br/>arc-self-settle.ts"]
58
+ end
59
+
60
+ subgraph Escrow["Agentic commerce (escrow/)"]
61
+ E8["createErc8183()<br/>erc8183.ts"]
62
+ EV["createEvaluator()<br/>evaluator.ts"]
63
+ CM["createCommissionSplitter()<br/>commission.ts"]
64
+ end
65
+
66
+ subgraph Ext["External"]
67
+ FAC["x402.org facilitator"]
68
+ CGW["Circle Gateway"]
69
+ ARC["Arc testnet<br/>USDC 0x3600…0000"]
70
+ E8183["ERC-8183 AgenticCommerce<br/>0x0747…4583"]
71
+ end
72
+
73
+ MW --> RT
74
+ MW --> ID
75
+ MW --> LG
76
+ RT --> GW & EX & AS
77
+ GW --> CGW
78
+ EX --> FAC
79
+ AS --> ARC
80
+ E8 --> E8183
81
+ EV --> E8
82
+ CM --> E8183
83
+ ```
84
+
85
+ ## Payment flow (x402)
86
+
87
+ ```mermaid
88
+ sequenceDiagram
89
+ participant A as Buyer agent
90
+ participant S as Server (requirePayment)
91
+ participant R as PaymentRouter
92
+ participant F as Facilitator / Arc RPC
93
+
94
+ A->>S: GET /resource (no payment)
95
+ S->>R: buildAccepts(price, payTo)
96
+ R-->>S: accepts[] (gateway, exact, arc-broadcast)
97
+ S-->>A: 402 + PAYMENT-REQUIRED (+ agentbadge ext)
98
+ A->>A: pick rail, sign EIP-3009
99
+ alt Arc self-settle
100
+ A->>F: broadcast transferWithAuthorization (gas in USDC)
101
+ F-->>A: txHash
102
+ end
103
+ A->>S: GET /resource + payment-signature
104
+ S->>R: verify(payload, requirements)
105
+ alt exact / gateway
106
+ R->>F: facilitator verify+settle
107
+ else arc self-settle
108
+ R->>F: getTransactionReceipt(txHash)<br/>check Transfer log + replay
109
+ end
110
+ F-->>R: settled
111
+ R-->>S: SettleResult
112
+ S-->>A: 200 + PAYMENT-RESPONSE + body
113
+ ```
114
+
115
+ ## ERC-8183 escrow lifecycle (Arc)
116
+
117
+ ```mermaid
118
+ stateDiagram-v2
119
+ [*] --> Open: client createJob(provider,<br/>evaluator, expiredAt, description)
120
+ Open --> Funded: provider setBudget +<br/>client approve USDC + fund
121
+ Funded --> Submitted: provider submit(deliverable)
122
+ Funded --> Expired: claimRefund (past expiredAt)
123
+ Submitted --> Completed: evaluator complete<br/>(escrow → provider, fee → treasury)
124
+ Submitted --> Rejected: evaluator reject<br/>(escrow → client)
125
+ Submitted --> Expired: claimRefund (past expiredAt)
126
+ Completed --> [*]
127
+ Rejected --> [*]
128
+ Expired --> [*]
129
+ ```
130
+
131
+ ## Install
132
+
133
+ ```bash
134
+ npm install @agentbadge/circle-payments
135
+ # peer: hono ^4.7.0
136
+ ```
137
+
138
+ ## Usage
139
+
140
+ ### Server: gate a route with a price
141
+
142
+ ```ts
143
+ import { createPaymentRouter, requirePayment } from "@agentbadge/circle-payments";
144
+
145
+ const router = createPaymentRouter({
146
+ gateway: true, // Circle Gateway batch rail
147
+ exact: true, // EIP-3009 exact via facilitator
148
+ arcSelfSettle: true, // eip3009-client-broadcast on Arc
149
+ facilitatorUrl: "https://x402.org/facilitator",
150
+ payTo: "0x…", // seller EOA
151
+ identityLookup, // optional: seller → passport
152
+ });
153
+
154
+ app.get("/api/paid", requirePayment(router, { price: "$0.001" }), (c) =>
155
+ c.json({ data: "premium" }),
156
+ );
157
+ ```
158
+
159
+ ### Escrow (ERC-8183 on Arc)
160
+
161
+ ```ts
162
+ import { createErc8183, createEvaluator, splitPayout } from "@agentbadge/circle-payments";
163
+
164
+ const escrow = createErc8183({ read: publicClient });
165
+ const { jobId } = await escrow.createJob(clientWallet, {
166
+ provider, evaluator, expiredAt, description,
167
+ });
168
+ // provider: setBudget → client: approve + fund → provider: submit
169
+ const evaluator = createEvaluator({ escrow, wallet: evaluatorWallet, verify });
170
+ const verdict = await evaluator.evaluate(jobId); // → complete / reject / expired
171
+ ```
172
+
173
+ ## API surface
174
+
175
+ | Export | Purpose |
176
+ |--------|---------|
177
+ | `createPaymentRouter`, `buildAccepts` | Rail registry + 402 accepts generation |
178
+ | `requirePayment` | Hono middleware: 402 → verify → settle → receipt |
179
+ | `registerGatewayScheme`, `registerExactScheme`, `registerArcSelfSettleScheme` | Scheme registration on `x402ResourceServer` |
180
+ | `BASE_SEPOLIA`, `ARC_TESTNET`, `ARC_CONTRACTS`, `getChain` | Chain configs (CAIP-2, USDC, RPC) |
181
+ | `identityExtension` | AgentBadge passport extension for 402 responses |
182
+ | `PRICE_TABLE`, `getPrice`, `validatePriceTable` | Route pricing config |
183
+ | `createPaymentStatusLookup` | Payment status by tx hash / gateway transfer |
184
+ | `createMemoryFailureStore` | Failure ledger (alerts on repeated failures) |
185
+ | `createErc8183`, `createJobRegistry`, `jobDescription` | ERC-8183 job lifecycle + registry |
186
+ | `createEvaluator`, `createEvaluationStore` | Evaluator verdicts + on-chain settle |
187
+ | `splitPayout`, `createCommissionSplitter` | Fee split to treasury (BPS) |
188
+ | `createErc8004Mirror` | Passport registration in ERC-8004 registry |
189
+ | `verifyPassport` | Buyer-side helper: 402 response → trust score |
190
+ | `createMemoClient` | Arc Memo contract metadata on settlement txs |
191
+
192
+ ## Verified on-chain facts (Arc testnet)
193
+
194
+ - CAIP-2: `eip155:5042002` · USDC: `0x3600000000000000000000000000000000000000`
195
+ - EIP-712 domain: `{name:"USDC", version:"2", chainId:5042002, verifyingContract: USDC}`
196
+ - Gas floor: `maxFeePerGas` ≥ 20 Gwei, `maxPriorityFeePerGas` 0–1 Gwei,
197
+ ~65k gas per `transferWithAuthorization` — paid in USDC (6 dec)
198
+ - ERC-8183 AgenticCommerce: `0x0747EEf0706327138c69792bF28Cd525089e4583`
199
+ - Memo contract: `0x5294E9927c3306DcBaDb03fe70b92e01cCede505`
200
+
201
+ ## License
202
+
203
+ MIT
@@ -0,0 +1,33 @@
1
+ import type { Caip2, SupportedChain } from "./chains";
2
+ export interface BalanceClient {
3
+ readContract(args: {
4
+ address: `0x${string}`;
5
+ abi: unknown;
6
+ functionName: string;
7
+ args: readonly unknown[];
8
+ }): Promise<unknown>;
9
+ }
10
+ export interface WalletBalance {
11
+ balance: string;
12
+ formatted: string;
13
+ }
14
+ export interface GatewayBalanceInfo {
15
+ available: string;
16
+ withdrawing: string;
17
+ withdrawable: string;
18
+ }
19
+ export interface ChainBalance {
20
+ network: Caip2;
21
+ chain: string;
22
+ wallet?: WalletBalance;
23
+ gateway?: GatewayBalanceInfo;
24
+ error?: string;
25
+ }
26
+ export interface BalanceLookupDeps {
27
+ chains: SupportedChain[];
28
+ sellerAddress: string;
29
+ gatewayApiUrl?: string;
30
+ publicClients?: Partial<Record<Caip2, BalanceClient>>;
31
+ }
32
+ export type BalanceLookup = (chain?: string) => Promise<ChainBalance[]>;
33
+ export declare function createBalanceLookup(deps: BalanceLookupDeps): BalanceLookup;
@@ -0,0 +1,72 @@
1
+ import { createPublicClient, erc20Abi, formatUnits, http } from "viem";
2
+ export function createBalanceLookup(deps) {
3
+ const clients = new Map();
4
+ for (const [net, c] of Object.entries(deps.publicClients ?? {})) {
5
+ if (c)
6
+ clients.set(net, c);
7
+ }
8
+ function clientFor(chain) {
9
+ const cached = clients.get(chain.caip2);
10
+ if (cached)
11
+ return cached;
12
+ const client = createPublicClient({
13
+ transport: http(chain.rpcUrl),
14
+ });
15
+ clients.set(chain.caip2, client);
16
+ return client;
17
+ }
18
+ async function walletBalance(chain) {
19
+ const raw = (await clientFor(chain).readContract({
20
+ address: chain.usdc,
21
+ abi: erc20Abi,
22
+ functionName: "balanceOf",
23
+ args: [deps.sellerAddress],
24
+ }));
25
+ return { balance: raw.toString(), formatted: formatUnits(raw, 6) };
26
+ }
27
+ async function gatewayBalance(chain) {
28
+ if (!deps.gatewayApiUrl || chain.domain === undefined)
29
+ return undefined;
30
+ try {
31
+ const resp = await fetch(`${deps.gatewayApiUrl}/balances`, {
32
+ method: "POST",
33
+ headers: { "Content-Type": "application/json" },
34
+ body: JSON.stringify({
35
+ token: "USDC",
36
+ sources: [{ depositor: deps.sellerAddress, domain: chain.domain }],
37
+ }),
38
+ });
39
+ if (!resp.ok)
40
+ return undefined;
41
+ const data = (await resp.json());
42
+ const row = data.balances?.[0];
43
+ if (!row)
44
+ return undefined;
45
+ return {
46
+ available: row.balance ?? "0",
47
+ withdrawing: row.withdrawing ?? "0",
48
+ withdrawable: row.withdrawable ?? "0",
49
+ };
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ return async (chainFilter) => {
56
+ const f = chainFilter?.trim().toLowerCase();
57
+ const targets = f
58
+ ? deps.chains.filter((c) => c.caip2 === f || c.name.toLowerCase() === f)
59
+ : deps.chains;
60
+ return Promise.all(targets.map(async (chain) => {
61
+ const out = { network: chain.caip2, chain: chain.name };
62
+ try {
63
+ out.wallet = await walletBalance(chain);
64
+ }
65
+ catch (e) {
66
+ out.error = e instanceof Error ? e.message : String(e);
67
+ }
68
+ out.gateway = await gatewayBalance(chain);
69
+ return out;
70
+ }));
71
+ };
72
+ }
@@ -0,0 +1,63 @@
1
+ export type Caip2 = `eip155:${number}`;
2
+ export interface SupportedChain {
3
+ caip2: Caip2;
4
+ chainId: number;
5
+ name: string;
6
+ usdc: `0x${string}`;
7
+ usdcDecimals: 6;
8
+ rpcUrl: string;
9
+ facilitatorUrl?: string;
10
+ gatewayWallet?: `0x${string}`;
11
+ domain?: number;
12
+ explorerUrl?: string;
13
+ faucetUrl?: string;
14
+ }
15
+ export declare const BASE_SEPOLIA: SupportedChain;
16
+ export declare const ARC_TESTNET: SupportedChain;
17
+ export declare const ARC_CONTRACTS: {
18
+ readonly memo: "0x5294E9927c3306DcBaDb03fe70b92e01cCede505";
19
+ readonly agenticCommerce: "0x0747EEf0706327138c69792bF28Cd525089e4583";
20
+ readonly identityRegistry: "0x8004A818BFB912233c491871b3d84c89A494BD9e";
21
+ readonly reputationRegistry: "0x8004B663056A597Dffe9eCcC1965A193B7388713";
22
+ readonly validationRegistry: "0x8004Cb1BF31DAf7788923b405b754f57acEB4272";
23
+ };
24
+ export declare const CHAINS: {
25
+ readonly [BASE_SEPOLIA.caip2]: SupportedChain;
26
+ readonly [ARC_TESTNET.caip2]: SupportedChain;
27
+ };
28
+ export declare function getChain(id: string | number): SupportedChain | undefined;
29
+ export type PaymentSchemeId = "gateway-batch" | "exact" | "eip3009-client-broadcast";
30
+ export interface PaymentRequirements {
31
+ scheme: string;
32
+ network: string;
33
+ asset: string;
34
+ amount: string;
35
+ maxAmountRequired?: string;
36
+ payTo: string;
37
+ maxTimeoutSeconds: number;
38
+ extra?: Record<string, unknown>;
39
+ }
40
+ export interface AcceptsEntry extends PaymentRequirements {
41
+ scheme: string;
42
+ }
43
+ export interface VerifyResult {
44
+ isValid: boolean;
45
+ invalidReason?: string;
46
+ payer?: string;
47
+ }
48
+ export interface SettleResult {
49
+ success: boolean;
50
+ errorReason?: string;
51
+ transaction?: string;
52
+ payer?: string;
53
+ }
54
+ export interface IdentityExtension {
55
+ passport?: {
56
+ tokenId?: string;
57
+ address?: string;
58
+ chain?: string;
59
+ verified?: boolean;
60
+ [k: string]: unknown;
61
+ };
62
+ [k: string]: unknown;
63
+ }
package/dist/chains.js ADDED
@@ -0,0 +1,41 @@
1
+ export const BASE_SEPOLIA = {
2
+ caip2: "eip155:84532",
3
+ chainId: 84532,
4
+ name: "Base Sepolia",
5
+ usdc: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
6
+ usdcDecimals: 6,
7
+ rpcUrl: "https://sepolia.base.org",
8
+ facilitatorUrl: "https://gateway-api-testnet.circle.com",
9
+ gatewayWallet: "0x0077777d7EBA4688BDeF3E311b846F25870A19B9",
10
+ domain: 6,
11
+ explorerUrl: "https://sepolia.basescan.org",
12
+ faucetUrl: "https://faucet.circle.com",
13
+ };
14
+ export const ARC_TESTNET = {
15
+ caip2: "eip155:5042002",
16
+ chainId: 5042002,
17
+ name: "Arc Testnet",
18
+ usdc: "0x3600000000000000000000000000000000000000",
19
+ usdcDecimals: 6,
20
+ rpcUrl: "https://rpc.testnet.arc.network",
21
+ facilitatorUrl: "https://gateway-api-testnet.circle.com",
22
+ gatewayWallet: "0x0077777d7EBA4688BDeF3E311b846F25870A19B9",
23
+ domain: 26,
24
+ explorerUrl: "https://explorer.testnet.arc.io",
25
+ faucetUrl: "https://faucet.circle.com",
26
+ };
27
+ export const ARC_CONTRACTS = {
28
+ memo: "0x5294E9927c3306DcBaDb03fe70b92e01cCede505",
29
+ agenticCommerce: "0x0747EEf0706327138c69792bF28Cd525089e4583",
30
+ identityRegistry: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
31
+ reputationRegistry: "0x8004B663056A597Dffe9eCcC1965A193B7388713",
32
+ validationRegistry: "0x8004Cb1BF31DAf7788923b405b754f57acEB4272",
33
+ };
34
+ export const CHAINS = {
35
+ [BASE_SEPOLIA.caip2]: BASE_SEPOLIA,
36
+ [ARC_TESTNET.caip2]: ARC_TESTNET,
37
+ };
38
+ export function getChain(id) {
39
+ const key = typeof id === "number" ? `eip155:${id}` : id;
40
+ return CHAINS[key];
41
+ }
@@ -0,0 +1,37 @@
1
+ import type { Hex } from "viem";
2
+ import type { WriteClient } from "./erc8183.js";
3
+ export declare const BPS_DENOMINATOR = 10000n;
4
+ export interface PayoutSplit {
5
+ providerAmount: bigint;
6
+ feeAmount: bigint;
7
+ feeBps: number;
8
+ }
9
+ export declare function splitPayout(budget: bigint, feeBps: number): PayoutSplit;
10
+ export interface CommissionRecord {
11
+ jobId: string;
12
+ budget: string;
13
+ feeBps: number;
14
+ feeAmount: string;
15
+ providerAmount: string;
16
+ treasury: `0x${string}`;
17
+ feeTx?: Hex;
18
+ recordedAt: string;
19
+ }
20
+ export declare class CommissionError extends Error {
21
+ readonly cause?: unknown | undefined;
22
+ constructor(message: string, cause?: unknown | undefined);
23
+ }
24
+ export interface CommissionDeps {
25
+ usdc: `0x${string}`;
26
+ treasury: `0x${string}`;
27
+ feeBps: number;
28
+ }
29
+ export declare function createCommissionSplitter(cfg: CommissionDeps): {
30
+ feeBps: number;
31
+ treasury: `0x${string}`;
32
+ collectFee(providerWallet: WriteClient, args: {
33
+ jobId: bigint;
34
+ budget: bigint;
35
+ }): Promise<CommissionRecord>;
36
+ };
37
+ export type CommissionSplitter = ReturnType<typeof createCommissionSplitter>;
@@ -0,0 +1,52 @@
1
+ import { parseAbi } from "viem";
2
+ const ERC20_TRANSFER_ABI = parseAbi([
3
+ "function transfer(address to, uint256 amount) returns (bool)",
4
+ ]);
5
+ export const BPS_DENOMINATOR = 10000n;
6
+ export function splitPayout(budget, feeBps) {
7
+ if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > 10_000) {
8
+ throw new CommissionError(`invalid feeBps ${feeBps}`);
9
+ }
10
+ const feeAmount = (budget * BigInt(feeBps)) / BPS_DENOMINATOR;
11
+ return { providerAmount: budget - feeAmount, feeAmount, feeBps };
12
+ }
13
+ export class CommissionError extends Error {
14
+ cause;
15
+ constructor(message, cause) {
16
+ super(message);
17
+ this.cause = cause;
18
+ this.name = "CommissionError";
19
+ }
20
+ }
21
+ export function createCommissionSplitter(cfg) {
22
+ return {
23
+ feeBps: cfg.feeBps,
24
+ treasury: cfg.treasury,
25
+ async collectFee(providerWallet, args) {
26
+ const split = splitPayout(args.budget, cfg.feeBps);
27
+ const record = {
28
+ jobId: args.jobId.toString(),
29
+ budget: args.budget.toString(),
30
+ feeBps: cfg.feeBps,
31
+ feeAmount: split.feeAmount.toString(),
32
+ providerAmount: split.providerAmount.toString(),
33
+ treasury: cfg.treasury,
34
+ recordedAt: new Date().toISOString(),
35
+ };
36
+ if (split.feeAmount === 0n)
37
+ return record;
38
+ try {
39
+ record.feeTx = await providerWallet.writeContract({
40
+ address: cfg.usdc,
41
+ abi: ERC20_TRANSFER_ABI,
42
+ functionName: "transfer",
43
+ args: [cfg.treasury, split.feeAmount],
44
+ });
45
+ return record;
46
+ }
47
+ catch (e) {
48
+ throw new CommissionError(`fee transfer failed for job ${args.jobId}`, e);
49
+ }
50
+ },
51
+ };
52
+ }