@agentbadge/circle-payments 0.1.14 → 0.1.17

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 CHANGED
@@ -219,6 +219,16 @@ const verdict = await evaluator.evaluate(jobId); // → complete / reject / expi
219
219
  - ERC-8183 AgenticCommerce: `0x0747EEf0706327138c69792bF28Cd525089e4583`
220
220
  - Memo contract: `0x5294E9927c3306DcBaDb03fe70b92e01cCede505`
221
221
 
222
+ ## Cross-chain payments (EPIC-156)
223
+
224
+ Buyer holds USDC on any Gateway-covered chain; seller settles on Arc.
225
+ Buyer helpers: `gatewayDepositInfo(chains)`, `depositToGateway(...)`,
226
+ `gatewayBalance({depositor, chain})` — plus server routes
227
+ `GET /api/pay/gateway/deposit-info`, `deposit-qr.svg`,
228
+ `transfers/:id` (terminal status, 156-5).
229
+ Reference client: `hackathon/server/examples/crosschain-pay.ts`;
230
+ docs: `docs/PAYMENTS/CROSSCHAIN.md`.
231
+
222
232
  ## License
223
233
 
224
234
  MIT
@@ -13,6 +13,7 @@ export interface DepositWalletClient {
13
13
  }
14
14
  export interface DepositResult {
15
15
  txHash: `0x${string}`;
16
+ approvalTxHash?: `0x${string}`;
16
17
  expectedCreditAt: string;
17
18
  network: Caip2;
18
19
  }
@@ -1,7 +1,7 @@
1
1
  import { erc20Abi, parseUnits } from "viem";
2
2
  const CREDIT_ESTIMATE_SEC = {
3
- 6: 40,
4
- 26: 10,
3
+ 6: 1800,
4
+ 26: 15,
5
5
  };
6
6
  function estimateFor(chain) {
7
7
  if (chain.domain !== undefined && CREDIT_ESTIMATE_SEC[chain.domain]) {
@@ -24,10 +24,23 @@ export function gatewayDepositInfo(chains, minDepositUsd) {
24
24
  transferUri: `ethereum:${c.gatewayWallet}@${c.chainId}?value=0`,
25
25
  ...(c.explorerUrl ? { explorerUrl: c.explorerUrl } : {}),
26
26
  })),
27
- howto: "transfer USDC to gatewayWallet on your chain → spendable unified " +
28
- "balance after source finality; then pay via signed burn intents",
27
+ howto: "approve USDC then call gatewayWallet.deposit(usdc, amount) on your " +
28
+ "chain → spendable unified balance after source finality (a raw " +
29
+ "transfer does NOT credit); then pay via signed burn intents",
29
30
  };
30
31
  }
32
+ const GATEWAY_WALLET_ABI = [
33
+ {
34
+ name: "deposit",
35
+ type: "function",
36
+ stateMutability: "nonpayable",
37
+ inputs: [
38
+ { name: "token", type: "address" },
39
+ { name: "value", type: "uint256" },
40
+ ],
41
+ outputs: [],
42
+ },
43
+ ];
31
44
  export async function depositToGateway(args) {
32
45
  const { wallet, chain } = args;
33
46
  if (!chain.gatewayWallet) {
@@ -37,15 +50,22 @@ export async function depositToGateway(args) {
37
50
  if (amount <= 0n) {
38
51
  throw new Error(`deposit amount must be > 0 (got ${args.amountUsd})`);
39
52
  }
40
- const txHash = await wallet.writeContract({
53
+ const approvalTxHash = await wallet.writeContract({
41
54
  address: chain.usdc,
42
55
  abi: erc20Abi,
43
- functionName: "transfer",
56
+ functionName: "approve",
44
57
  args: [chain.gatewayWallet, amount],
45
58
  });
59
+ const txHash = await wallet.writeContract({
60
+ address: chain.gatewayWallet,
61
+ abi: GATEWAY_WALLET_ABI,
62
+ functionName: "deposit",
63
+ args: [chain.usdc, amount],
64
+ });
46
65
  const eta = new Date(Date.now() + estimateFor(chain) * 1000);
47
66
  return {
48
67
  txHash,
68
+ approvalTxHash,
49
69
  expectedCreditAt: eta.toISOString(),
50
70
  network: chain.caip2,
51
71
  };
package/dist/index.d.ts CHANGED
@@ -20,3 +20,4 @@ export * from "./identity/erc8004.js";
20
20
  export * from "./identity/verify-passport.js";
21
21
  export * from "./memo/memo.js";
22
22
  export * from "./agent-wallet/index.js";
23
+ export * from "./payer-bind.js";
package/dist/index.js CHANGED
@@ -20,3 +20,4 @@ export * from "./identity/erc8004.js";
20
20
  export * from "./identity/verify-passport.js";
21
21
  export * from "./memo/memo.js";
22
22
  export * from "./agent-wallet/index.js";
23
+ export * from "./payer-bind.js";
package/dist/ledger.d.ts CHANGED
@@ -7,6 +7,8 @@ export interface PaymentFailure {
7
7
  reason: string;
8
8
  txRef?: string;
9
9
  at?: string;
10
+ rail?: string;
11
+ requestId?: string;
10
12
  }
11
13
  export interface FailureStore {
12
14
  append(failure: PaymentFailure): void | Promise<void>;
@@ -25,6 +25,8 @@ export interface RequirePaymentOptions extends PaymentRouterConfig {
25
25
  payment?: PaymentInfo;
26
26
  error?: string;
27
27
  }) => Promise<void> | void;
28
+ legacyHeader?: boolean;
29
+ extraRequirements?: Record<string, unknown>;
28
30
  }
29
31
  export interface PaymentInfo {
30
32
  payer?: string;
@@ -1,5 +1,5 @@
1
1
  import { recordFailure, } from "./ledger.js";
2
- import { createPaymentRouter, } from "./router.js";
2
+ import { classifyRail, createPaymentRouter, } from "./router.js";
3
3
  const b64encode = (o) => Buffer.from(JSON.stringify(o)).toString("base64");
4
4
  function b64decode(s) {
5
5
  try {
@@ -72,8 +72,20 @@ export function requirePayment(price, opts) {
72
72
  return c.json({ error: "Invalid price" }, 402);
73
73
  }
74
74
  }
75
- const accepts = router.acceptsFor(amount);
76
- const signatureHeader = c.req.header("payment-signature");
75
+ const accepts = opts.extraRequirements
76
+ ? router.acceptsFor(amount).map((a) => ({
77
+ ...a,
78
+ extra: { ...a.extra, ...opts.extraRequirements },
79
+ }))
80
+ : router.acceptsFor(amount);
81
+ let signatureHeader = c.req.header("payment-signature");
82
+ if (!signatureHeader && opts.legacyHeader) {
83
+ const v1 = c.req.header("x-payment");
84
+ if (v1) {
85
+ console.warn(`[x402] deprecated X-PAYMENT header used on ${c.req.path} — migrate to payment-signature`);
86
+ signatureHeader = v1;
87
+ }
88
+ }
77
89
  if (!signatureHeader) {
78
90
  return paymentRequired(c, accepts, opts);
79
91
  }
@@ -139,6 +151,10 @@ export function requirePayment(price, opts) {
139
151
  amount: requirements.amount,
140
152
  reason: c.error instanceof Error ? c.error.message : String(c.error),
141
153
  txRef: settleResult.transaction,
154
+ rail: classifyRail(requirements),
155
+ requestId: typeof c.get("requestId") === "string"
156
+ ? c.get("requestId")
157
+ : undefined,
142
158
  }, opts.onFailure);
143
159
  }
144
160
  c.header("PAYMENT-RESPONSE", b64encode({
@@ -0,0 +1,15 @@
1
+ export declare const PAYER_BIND_CHALLENGE_VERSION = "agentbadge-pay:v1";
2
+ export interface PayerChallengeParams {
3
+ wallet: string;
4
+ method: string;
5
+ path: string;
6
+ payRef: string;
7
+ timestamp: number;
8
+ }
9
+ export declare function buildPayerChallenge(p: PayerChallengeParams): string;
10
+ export type PayerChallengeSigner = `0x${string}` | {
11
+ signMessage(args: {
12
+ message: string;
13
+ }): Promise<`0x${string}`>;
14
+ };
15
+ export declare function signPayerChallenge(signer: PayerChallengeSigner, params: PayerChallengeParams): Promise<`0x${string}`>;
@@ -0,0 +1,16 @@
1
+ import { privateKeyToAccount } from "viem/accounts";
2
+ export const PAYER_BIND_CHALLENGE_VERSION = "agentbadge-pay:v1";
3
+ export function buildPayerChallenge(p) {
4
+ return [
5
+ PAYER_BIND_CHALLENGE_VERSION,
6
+ `wallet:${p.wallet.toLowerCase()}`,
7
+ `method:${p.method.toUpperCase()}`,
8
+ `path:${p.path}`,
9
+ `payref:${p.payRef.toLowerCase()}`,
10
+ `timestamp:${p.timestamp}`,
11
+ ].join("\n");
12
+ }
13
+ export async function signPayerChallenge(signer, params) {
14
+ const account = typeof signer === "string" ? privateKeyToAccount(signer) : signer;
15
+ return account.signMessage({ message: buildPayerChallenge(params) });
16
+ }
package/dist/router.d.ts CHANGED
@@ -11,7 +11,9 @@ export interface RouterFlags {
11
11
  }
12
12
  export interface RouterConfig extends RouterFlags {
13
13
  sellerAddress: string;
14
+ railPayTo?: Partial<Record<"gateway" | "exact" | "arcSelfSettle", string>>;
14
15
  gatewayChains?: SupportedChain[];
16
+ gatewayCrosschainTakeUsd?: string;
15
17
  exactChains?: SupportedChain[];
16
18
  arcChain?: SupportedChain;
17
19
  }
@@ -21,6 +23,11 @@ export interface PaymentRouterConfig extends RouterConfig {
21
23
  exact?: SchemeHandle;
22
24
  arcSelfSettle?: SchemeHandle;
23
25
  };
26
+ metrics?: PaymentMetricsHooks;
27
+ }
28
+ export interface PaymentMetricsHooks {
29
+ onVerify?(rail: string, network: string, result: "ok" | "invalid" | "error", ms: number): void;
30
+ onSettle?(rail: string, network: string, result: "ok" | "fail" | "error", ms: number): void;
24
31
  }
25
32
  export interface PaymentRouter {
26
33
  acceptsFor(amount: string): PaymentRequirements[];
@@ -28,4 +35,6 @@ export interface PaymentRouter {
28
35
  settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
29
36
  }
30
37
  export declare function buildAccepts(amount: string, config: RouterConfig): PaymentRequirements[];
38
+ export type PaymentRail = "gateway" | "exact" | "arcSelfSettle";
39
+ export declare function classifyRail(req: PaymentRequirements): PaymentRail | undefined;
31
40
  export declare function createPaymentRouter(config: PaymentRouterConfig): PaymentRouter;
package/dist/router.js CHANGED
@@ -14,24 +14,40 @@ export function buildAccepts(amount, config) {
14
14
  const arcOn = flagOn(config.arc);
15
15
  if (gatewayOn) {
16
16
  const chains = config.gatewayChains ?? [BASE_SEPOLIA, ARC_TESTNET];
17
+ const takeUsd = config.gatewayCrosschainTakeUsd;
18
+ const takeN = Number(takeUsd ?? "0");
19
+ const takeAtomic = Number.isFinite(takeN) && takeN > 0
20
+ ? BigInt(Math.round(takeN * 1e6))
21
+ : 0n;
17
22
  for (const chain of chains) {
18
23
  if (chain === ARC_TESTNET && !arcOn)
19
24
  continue;
20
- accepts.push(buildGatewayRequirements(chain, amount, config.sellerAddress));
25
+ const req = buildGatewayRequirements(chain, (BigInt(amount) + takeAtomic).toString(), config.railPayTo?.gateway ?? config.sellerAddress);
26
+ accepts.push({
27
+ ...req,
28
+ extra: {
29
+ ...req.extra,
30
+ gatewayFeeHint: {
31
+ payerSide: true,
32
+ takeUsd: takeUsd ?? "0",
33
+ note: "gateway provider/gas/forwarder fees are charged to the payer on top",
34
+ },
35
+ },
36
+ });
21
37
  }
22
38
  }
23
39
  if (exactOn) {
24
40
  const chains = config.exactChains ?? [BASE_SEPOLIA];
25
41
  for (const chain of chains) {
26
- accepts.push(buildExactRequirements(chain, amount, config.sellerAddress));
42
+ accepts.push(buildExactRequirements(chain, amount, config.railPayTo?.exact ?? config.sellerAddress));
27
43
  }
28
44
  }
29
45
  if (arcOn) {
30
- accepts.push(buildArcSelfSettleRequirements(config.arcChain ?? ARC_TESTNET, amount, config.sellerAddress));
46
+ accepts.push(buildArcSelfSettleRequirements(config.arcChain ?? ARC_TESTNET, amount, config.railPayTo?.arcSelfSettle ?? config.sellerAddress));
31
47
  }
32
48
  return accepts;
33
49
  }
34
- function classify(req) {
50
+ export function classifyRail(req) {
35
51
  if (req.scheme === ARC_SELF_SETTLE_SCHEME)
36
52
  return "arcSelfSettle";
37
53
  if (req.scheme === "exact") {
@@ -48,7 +64,7 @@ function acceptedOf(payload) {
48
64
  export function createPaymentRouter(config) {
49
65
  function railFor(payload, requirements) {
50
66
  const accepted = acceptedOf(payload) ?? requirements;
51
- const rail = classify(accepted);
67
+ const rail = classifyRail(accepted);
52
68
  if (!rail)
53
69
  return undefined;
54
70
  return rail;
@@ -60,18 +76,42 @@ export function createPaymentRouter(config) {
60
76
  async verify(payload, requirements) {
61
77
  const rail = railFor(payload, requirements);
62
78
  const handle = rail ? config.handles[rail] : undefined;
79
+ const network = requirements.network;
80
+ const t0 = Date.now();
81
+ const metrics = config.metrics;
63
82
  if (!handle) {
83
+ metrics?.onVerify?.(rail ?? "unknown", network, "invalid", Date.now() - t0);
64
84
  return { isValid: false, invalidReason: "unsupported_scheme" };
65
85
  }
66
- return handle.verify(payload, requirements);
86
+ try {
87
+ const res = await handle.verify(payload, requirements);
88
+ metrics?.onVerify?.(rail, network, res.isValid ? "ok" : "invalid", Date.now() - t0);
89
+ return res;
90
+ }
91
+ catch (err) {
92
+ metrics?.onVerify?.(rail, network, "error", Date.now() - t0);
93
+ throw err;
94
+ }
67
95
  },
68
96
  async settle(payload, requirements) {
69
97
  const rail = railFor(payload, requirements);
70
98
  const handle = rail ? config.handles[rail] : undefined;
99
+ const network = requirements.network;
100
+ const t0 = Date.now();
101
+ const metrics = config.metrics;
71
102
  if (!handle) {
103
+ metrics?.onSettle?.(rail ?? "unknown", network, "fail", Date.now() - t0);
72
104
  return { success: false, errorReason: "unsupported_scheme" };
73
105
  }
74
- return handle.settle(payload, requirements);
106
+ try {
107
+ const res = await handle.settle(payload, requirements);
108
+ metrics?.onSettle?.(rail, network, res.success ? "ok" : "fail", Date.now() - t0);
109
+ return res;
110
+ }
111
+ catch (err) {
112
+ metrics?.onSettle?.(rail, network, "error", Date.now() - t0);
113
+ throw err;
114
+ }
75
115
  },
76
116
  };
77
117
  }
@@ -31,9 +31,18 @@ export interface ArcSelfSettleHandle {
31
31
  readonly publicClient: ReceiptClient;
32
32
  readonly seenTxHashes: Set<string>;
33
33
  readonly network: string;
34
+ inspect(payload: unknown, requirements: PaymentRequirements): Promise<ArcInspectResult>;
34
35
  verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
35
36
  settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
36
37
  }
38
+ export type ArcInspectResult = {
39
+ ok: true;
40
+ txHash: `0x${string}`;
41
+ payer?: string;
42
+ } | {
43
+ ok: false;
44
+ reason: string;
45
+ };
37
46
  export declare function buildArcSelfSettleRequirements(chain: SupportedChain, amount: string, payTo: string): PaymentRequirements;
38
47
  export declare function createArcSelfSettleHandle(config: ArcSelfSettleConfig): ArcSelfSettleHandle;
39
48
  export declare function registerArcSelfSettleScheme(server: x402ResourceServer, config: ArcSelfSettleConfig): ArcSelfSettleHandle;
@@ -78,18 +78,36 @@ export function createArcSelfSettleHandle(config) {
78
78
  });
79
79
  const seenTxHashes = config.seenTxHashes ?? new Set();
80
80
  const txHashStore = config.txHashStore ?? new InMemoryTxHashStore(seenTxHashes);
81
+ const RECEIPT_CACHE_TTL_MS = 30_000;
82
+ const RECEIPT_CACHE_MAX = 512;
83
+ const receiptCache = new Map();
81
84
  async function inspectReceipt(payload, requirements, phase) {
82
85
  const txHash = extractTxHash(payload);
83
86
  if (!txHash)
84
87
  return { ok: false, reason: "missing_tx_hash" };
85
- let receipt;
86
- try {
87
- receipt = (await publicClient.getTransactionReceipt({
88
- hash: txHash,
89
- }));
88
+ const cacheKey = txHash.toLowerCase();
89
+ const hit = receiptCache.get(cacheKey);
90
+ let receipt = null;
91
+ if (hit && hit.expiresAt > Date.now()) {
92
+ receipt = hit.receipt;
90
93
  }
91
- catch (err) {
92
- throw new ArcSelfSettleError(`Receipt fetch failed: ${err.message}`, phase, err);
94
+ else {
95
+ try {
96
+ receipt = (await publicClient.getTransactionReceipt({
97
+ hash: txHash,
98
+ }));
99
+ }
100
+ catch (err) {
101
+ throw new ArcSelfSettleError(`Receipt fetch failed: ${err.message}`, phase, err);
102
+ }
103
+ if (receipt) {
104
+ if (receiptCache.size >= RECEIPT_CACHE_MAX)
105
+ receiptCache.clear();
106
+ receiptCache.set(cacheKey, {
107
+ receipt,
108
+ expiresAt: Date.now() + RECEIPT_CACHE_TTL_MS,
109
+ });
110
+ }
93
111
  }
94
112
  if (!receipt)
95
113
  return { ok: false, reason: "tx_not_found" };
@@ -104,6 +122,12 @@ export function createArcSelfSettleHandle(config) {
104
122
  publicClient,
105
123
  seenTxHashes,
106
124
  network: chain.caip2,
125
+ async inspect(payload, requirements) {
126
+ const r = await inspectReceipt(payload, requirements, "verify");
127
+ if (!r.ok)
128
+ return { ok: false, reason: r.reason };
129
+ return { ok: true, txHash: r.txHash, payer: r.payer };
130
+ },
107
131
  async verify(payload, requirements) {
108
132
  const r = await inspectReceipt(payload, requirements, "verify");
109
133
  if (!r.ok)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@agentbadge/circle-payments",
3
- "version": "0.1.14",
4
- "description": "Circle Gateway nanopayments + x402 payment rails (Base Sepolia, Arc) for AgentBadge — trusted agent payments",
3
+ "version": "0.1.17",
4
+ "description": "Circle Gateway nanopayments + x402 payment rails (Base Sepolia, Arc) for AgentBadge \u2014 trusted agent payments",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",