@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/dist/router.js ADDED
@@ -0,0 +1,72 @@
1
+ import { ARC_TESTNET, BASE_SEPOLIA, } from "./chains.js";
2
+ import { buildGatewayRequirements } from "./schemes/gateway.js";
3
+ import { buildExactRequirements } from "./schemes/exact.js";
4
+ import { ARC_SELF_SETTLE_SCHEME, buildArcSelfSettleRequirements, } from "./schemes/arc-self-settle.js";
5
+ export function buildAccepts(amount, config) {
6
+ const accepts = [];
7
+ const gatewayOn = config.gateway !== false;
8
+ const exactOn = config.exact !== false;
9
+ const arcOn = config.arc !== false;
10
+ if (gatewayOn) {
11
+ const chains = config.gatewayChains ?? [BASE_SEPOLIA, ARC_TESTNET];
12
+ for (const chain of chains) {
13
+ if (chain === ARC_TESTNET && !arcOn)
14
+ continue;
15
+ accepts.push(buildGatewayRequirements(chain, amount, config.sellerAddress));
16
+ }
17
+ }
18
+ if (exactOn) {
19
+ const chains = config.exactChains ?? [BASE_SEPOLIA];
20
+ for (const chain of chains) {
21
+ accepts.push(buildExactRequirements(chain, amount, config.sellerAddress));
22
+ }
23
+ }
24
+ if (arcOn) {
25
+ accepts.push(buildArcSelfSettleRequirements(config.arcChain ?? ARC_TESTNET, amount, config.sellerAddress));
26
+ }
27
+ return accepts;
28
+ }
29
+ function classify(req) {
30
+ if (req.scheme === ARC_SELF_SETTLE_SCHEME)
31
+ return "arcSelfSettle";
32
+ if (req.scheme === "exact") {
33
+ return req.extra?.name === "GatewayWalletBatched" ? "gateway" : "exact";
34
+ }
35
+ return undefined;
36
+ }
37
+ function acceptedOf(payload) {
38
+ const p = payload;
39
+ return p?.accepted && typeof p.accepted === "object"
40
+ ? p.accepted
41
+ : undefined;
42
+ }
43
+ export function createPaymentRouter(config) {
44
+ function railFor(payload, requirements) {
45
+ const accepted = acceptedOf(payload) ?? requirements;
46
+ const rail = classify(accepted);
47
+ if (!rail)
48
+ return undefined;
49
+ return rail;
50
+ }
51
+ return {
52
+ acceptsFor(amount) {
53
+ return buildAccepts(amount, config);
54
+ },
55
+ async verify(payload, requirements) {
56
+ const rail = railFor(payload, requirements);
57
+ const handle = rail ? config.handles[rail] : undefined;
58
+ if (!handle) {
59
+ return { isValid: false, invalidReason: "unsupported_scheme" };
60
+ }
61
+ return handle.verify(payload, requirements);
62
+ },
63
+ async settle(payload, requirements) {
64
+ const rail = railFor(payload, requirements);
65
+ const handle = rail ? config.handles[rail] : undefined;
66
+ if (!handle) {
67
+ return { success: false, errorReason: "unsupported_scheme" };
68
+ }
69
+ return handle.settle(payload, requirements);
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,29 @@
1
+ import type { x402ResourceServer } from "@x402/core/server";
2
+ import { type PaymentRequirements, type SettleResult, type SupportedChain, type VerifyResult } from "../chains.js";
3
+ export declare const ARC_SELF_SETTLE_SCHEME = "eip3009-client-broadcast";
4
+ export declare class ArcSelfSettleError extends Error {
5
+ readonly phase: "verify" | "settle";
6
+ readonly cause?: unknown | undefined;
7
+ constructor(message: string, phase: "verify" | "settle", cause?: unknown | undefined);
8
+ }
9
+ export interface ReceiptClient {
10
+ getTransactionReceipt(args: {
11
+ hash: `0x${string}`;
12
+ }): Promise<unknown>;
13
+ }
14
+ export interface ArcSelfSettleConfig {
15
+ sellerAddress: string;
16
+ chain?: SupportedChain;
17
+ rpcUrl?: string;
18
+ publicClient?: ReceiptClient;
19
+ seenTxHashes?: Set<string>;
20
+ }
21
+ export interface ArcSelfSettleHandle {
22
+ readonly publicClient: ReceiptClient;
23
+ readonly seenTxHashes: Set<string>;
24
+ readonly network: string;
25
+ verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
26
+ settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
27
+ }
28
+ export declare function buildArcSelfSettleRequirements(chain: SupportedChain, amount: string, payTo: string): PaymentRequirements;
29
+ export declare function registerArcSelfSettleScheme(server: x402ResourceServer, config: ArcSelfSettleConfig): ArcSelfSettleHandle;
@@ -0,0 +1,114 @@
1
+ import { createPublicClient, http } from "viem";
2
+ import { ARC_TESTNET, } from "../chains.js";
3
+ export const ARC_SELF_SETTLE_SCHEME = "eip3009-client-broadcast";
4
+ const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
5
+ export class ArcSelfSettleError extends Error {
6
+ phase;
7
+ cause;
8
+ constructor(message, phase, cause) {
9
+ super(message);
10
+ this.phase = phase;
11
+ this.cause = cause;
12
+ this.name = "ArcSelfSettleError";
13
+ }
14
+ }
15
+ export function buildArcSelfSettleRequirements(chain, amount, payTo) {
16
+ return {
17
+ scheme: ARC_SELF_SETTLE_SCHEME,
18
+ network: chain.caip2,
19
+ asset: chain.usdc,
20
+ amount,
21
+ payTo,
22
+ maxTimeoutSeconds: 345600,
23
+ extra: { assetTransferMethod: ARC_SELF_SETTLE_SCHEME },
24
+ };
25
+ }
26
+ function extractTxHash(payload) {
27
+ const p = payload;
28
+ const h = p?.payload?.txHash ?? p?.txHash;
29
+ return typeof h === "string" && h.startsWith("0x")
30
+ ? h
31
+ : undefined;
32
+ }
33
+ function addrFromTopic(topic) {
34
+ if (!topic || topic.length < 42)
35
+ return undefined;
36
+ return `0x${topic.slice(-40)}`.toLowerCase();
37
+ }
38
+ function findPaymentTransfer(receipt, usdc, payTo, amount) {
39
+ for (const log of receipt.logs) {
40
+ if (log.address.toLowerCase() !== usdc.toLowerCase())
41
+ continue;
42
+ if (log.topics[0]?.toLowerCase() !== TRANSFER_TOPIC)
43
+ continue;
44
+ const to = addrFromTopic(log.topics[2]);
45
+ if (to !== payTo.toLowerCase())
46
+ continue;
47
+ let value;
48
+ try {
49
+ value = BigInt(log.data);
50
+ }
51
+ catch {
52
+ continue;
53
+ }
54
+ if (value < amount)
55
+ continue;
56
+ return { payer: addrFromTopic(log.topics[1]) };
57
+ }
58
+ return undefined;
59
+ }
60
+ export function registerArcSelfSettleScheme(server, config) {
61
+ const chain = config.chain ?? ARC_TESTNET;
62
+ const publicClient = config.publicClient ??
63
+ createPublicClient({
64
+ transport: http(config.rpcUrl ?? chain.rpcUrl),
65
+ });
66
+ const seenTxHashes = config.seenTxHashes ?? new Set();
67
+ server.register(chain.caip2, {
68
+ scheme: ARC_SELF_SETTLE_SCHEME,
69
+ });
70
+ async function inspectReceipt(payload, requirements, phase) {
71
+ const txHash = extractTxHash(payload);
72
+ if (!txHash)
73
+ return { ok: false, reason: "missing_tx_hash" };
74
+ let receipt;
75
+ try {
76
+ receipt = (await publicClient.getTransactionReceipt({
77
+ hash: txHash,
78
+ }));
79
+ }
80
+ catch (err) {
81
+ throw new ArcSelfSettleError(`Receipt fetch failed: ${err.message}`, phase, err);
82
+ }
83
+ if (!receipt)
84
+ return { ok: false, reason: "tx_not_found" };
85
+ if (receipt.status !== "success")
86
+ return { ok: false, reason: "tx_reverted" };
87
+ const match = findPaymentTransfer(receipt, requirements.asset, requirements.payTo, BigInt(requirements.amount));
88
+ if (!match)
89
+ return { ok: false, reason: "missing_transfer" };
90
+ return { ok: true, receipt, txHash, payer: match.payer };
91
+ }
92
+ return {
93
+ publicClient,
94
+ seenTxHashes,
95
+ network: chain.caip2,
96
+ async verify(payload, requirements) {
97
+ const txHash = extractTxHash(payload);
98
+ if (txHash && seenTxHashes.has(txHash.toLowerCase())) {
99
+ return { isValid: false, invalidReason: "tx_replayed" };
100
+ }
101
+ const r = await inspectReceipt(payload, requirements, "verify");
102
+ if (!r.ok)
103
+ return { isValid: false, invalidReason: r.reason };
104
+ seenTxHashes.add(r.txHash.toLowerCase());
105
+ return { isValid: true, payer: r.payer };
106
+ },
107
+ async settle(payload, requirements) {
108
+ const r = await inspectReceipt(payload, requirements, "settle");
109
+ if (!r.ok)
110
+ return { success: false, errorReason: r.reason };
111
+ return { success: true, transaction: r.txHash, payer: r.payer };
112
+ },
113
+ };
114
+ }
@@ -0,0 +1,22 @@
1
+ import { HTTPFacilitatorClient } from "@x402/core/server";
2
+ import type { x402ResourceServer } from "@x402/core/server";
3
+ import { type PaymentRequirements, type SettleResult, type SupportedChain, type VerifyResult } from "../chains.js";
4
+ export declare class ExactPaymentError extends Error {
5
+ readonly phase: "verify" | "settle";
6
+ readonly cause?: unknown | undefined;
7
+ constructor(message: string, phase: "verify" | "settle", cause?: unknown | undefined);
8
+ }
9
+ export interface ExactSchemeConfig {
10
+ facilitatorUrl?: string;
11
+ sellerAddress: string;
12
+ chains?: SupportedChain[];
13
+ timeoutMs?: number;
14
+ }
15
+ export interface ExactSchemeHandle {
16
+ readonly facilitator: HTTPFacilitatorClient;
17
+ verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
18
+ settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
19
+ }
20
+ export declare function createExactFacilitator(config: Pick<ExactSchemeConfig, "facilitatorUrl" | "timeoutMs">): HTTPFacilitatorClient;
21
+ export declare function buildExactRequirements(chain: SupportedChain, amount: string, payTo: string): PaymentRequirements;
22
+ export declare function registerExactScheme(server: x402ResourceServer, config: ExactSchemeConfig): ExactSchemeHandle;
@@ -0,0 +1,71 @@
1
+ import { HTTPFacilitatorClient } from "@x402/core/server";
2
+ import { registerExactEvmScheme, } from "@x402/evm/exact/server";
3
+ import { BASE_SEPOLIA, } from "../chains.js";
4
+ export class ExactPaymentError extends Error {
5
+ phase;
6
+ cause;
7
+ constructor(message, phase, cause) {
8
+ super(message);
9
+ this.phase = phase;
10
+ this.cause = cause;
11
+ this.name = "ExactPaymentError";
12
+ }
13
+ }
14
+ const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
15
+ export function createExactFacilitator(config) {
16
+ return new HTTPFacilitatorClient({
17
+ url: config.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,
18
+ ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}),
19
+ });
20
+ }
21
+ export function buildExactRequirements(chain, amount, payTo) {
22
+ return {
23
+ scheme: "exact",
24
+ network: chain.caip2,
25
+ asset: chain.usdc,
26
+ amount,
27
+ maxAmountRequired: amount,
28
+ payTo,
29
+ maxTimeoutSeconds: 345600,
30
+ extra: { name: "USDC", version: "2" },
31
+ };
32
+ }
33
+ export function registerExactScheme(server, config) {
34
+ const facilitator = createExactFacilitator(config);
35
+ const chains = config.chains ?? [BASE_SEPOLIA];
36
+ registerExactEvmScheme(server, {
37
+ networks: chains.map((c) => c.caip2),
38
+ });
39
+ return {
40
+ facilitator,
41
+ async verify(payload, requirements) {
42
+ try {
43
+ const res = await facilitator.verify(payload, requirements);
44
+ const r = res;
45
+ return {
46
+ isValid: r.isValid,
47
+ invalidReason: r.invalidReason,
48
+ payer: r.payer,
49
+ };
50
+ }
51
+ catch (err) {
52
+ throw new ExactPaymentError(`Exact verify failed: ${err.message}`, "verify", err);
53
+ }
54
+ },
55
+ async settle(payload, requirements) {
56
+ try {
57
+ const res = await facilitator.settle(payload, requirements);
58
+ const r = res;
59
+ return {
60
+ success: r.success,
61
+ errorReason: r.errorReason,
62
+ transaction: r.transaction,
63
+ payer: r.payer,
64
+ };
65
+ }
66
+ catch (err) {
67
+ throw new ExactPaymentError(`Exact settle failed: ${err.message}`, "settle", err);
68
+ }
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,22 @@
1
+ import { BatchFacilitatorClient } from "@circle-fin/x402-batching/server";
2
+ import type { x402ResourceServer } from "@x402/core/server";
3
+ import { type PaymentRequirements, type SettleResult, type SupportedChain, type VerifyResult } from "../chains.js";
4
+ export declare class GatewayPaymentError extends Error {
5
+ readonly phase: "verify" | "settle" | "supported";
6
+ readonly cause?: unknown | undefined;
7
+ constructor(message: string, phase: "verify" | "settle" | "supported", cause?: unknown | undefined);
8
+ }
9
+ export interface GatewaySchemeConfig {
10
+ facilitatorUrl?: string;
11
+ sellerAddress: string;
12
+ chains?: SupportedChain[];
13
+ headers?: Record<string, string>;
14
+ }
15
+ export interface GatewaySchemeHandle {
16
+ readonly facilitator: BatchFacilitatorClient;
17
+ verify(payload: unknown, requirements: PaymentRequirements): Promise<VerifyResult>;
18
+ settle(payload: unknown, requirements: PaymentRequirements): Promise<SettleResult>;
19
+ }
20
+ export declare function createGatewayFacilitator(config: Pick<GatewaySchemeConfig, "facilitatorUrl" | "headers">): BatchFacilitatorClient;
21
+ export declare function buildGatewayRequirements(chain: SupportedChain, amount: string, payTo: string): PaymentRequirements;
22
+ export declare function registerGatewayScheme(server: x402ResourceServer, config: GatewaySchemeConfig): GatewaySchemeHandle;
@@ -0,0 +1,76 @@
1
+ import { BatchFacilitatorClient, GatewayEvmScheme, } from "@circle-fin/x402-batching/server";
2
+ import { ARC_TESTNET, BASE_SEPOLIA, } from "../chains.js";
3
+ export class GatewayPaymentError extends Error {
4
+ phase;
5
+ cause;
6
+ constructor(message, phase, cause) {
7
+ super(message);
8
+ this.phase = phase;
9
+ this.cause = cause;
10
+ this.name = "GatewayPaymentError";
11
+ }
12
+ }
13
+ const DEFAULT_FACILITATOR_URL = "https://gateway-api-testnet.circle.com";
14
+ export function createGatewayFacilitator(config) {
15
+ return new BatchFacilitatorClient({
16
+ url: config.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,
17
+ ...(config.headers ? { headers: config.headers } : {}),
18
+ });
19
+ }
20
+ export function buildGatewayRequirements(chain, amount, payTo) {
21
+ if (!chain.gatewayWallet) {
22
+ throw new GatewayPaymentError(`Chain ${chain.name} has no GatewayWallet`, "verify");
23
+ }
24
+ return {
25
+ scheme: "exact",
26
+ network: chain.caip2,
27
+ asset: chain.usdc,
28
+ amount,
29
+ payTo,
30
+ maxTimeoutSeconds: 1209600,
31
+ extra: {
32
+ name: "GatewayWalletBatched",
33
+ version: "1",
34
+ verifyingContract: chain.gatewayWallet,
35
+ },
36
+ };
37
+ }
38
+ export function registerGatewayScheme(server, config) {
39
+ const facilitator = createGatewayFacilitator(config);
40
+ const chains = config.chains ?? [BASE_SEPOLIA, ARC_TESTNET];
41
+ for (const chain of chains) {
42
+ server.register(chain.caip2, new GatewayEvmScheme());
43
+ }
44
+ return {
45
+ facilitator,
46
+ async verify(payload, requirements) {
47
+ try {
48
+ const res = await facilitator.verify(payload, requirements);
49
+ const r = res;
50
+ return {
51
+ isValid: r.isValid,
52
+ invalidReason: r.invalidReason,
53
+ payer: r.payer,
54
+ };
55
+ }
56
+ catch (err) {
57
+ throw new GatewayPaymentError(`Gateway verify failed: ${err.message}`, "verify", err);
58
+ }
59
+ },
60
+ async settle(payload, requirements) {
61
+ try {
62
+ const res = await facilitator.settle(payload, requirements);
63
+ const r = res;
64
+ return {
65
+ success: r.success,
66
+ errorReason: r.errorReason,
67
+ transaction: r.transaction,
68
+ payer: r.payer,
69
+ };
70
+ }
71
+ catch (err) {
72
+ throw new GatewayPaymentError(`Gateway settle failed: ${err.message}`, "settle", err);
73
+ }
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,32 @@
1
+ import type { FailureStore } from "./ledger";
2
+ import type { ArcSelfSettleHandle } from "./schemes/arc-self-settle";
3
+ export interface GatewayTransferQuery {
4
+ getTransferById(id: string): Promise<TransferLike>;
5
+ }
6
+ export type PaymentStatusValue = "pending" | "confirmed" | "completed" | "failed" | "not_found";
7
+ export type PaymentRefType = "gateway-transfer" | "tx-hash" | "internal";
8
+ export interface PaymentStatus {
9
+ status: PaymentStatusValue;
10
+ ref: string;
11
+ refType: PaymentRefType;
12
+ scheme?: string;
13
+ network?: string;
14
+ amount?: string;
15
+ confirmedAt?: string;
16
+ raw?: unknown;
17
+ }
18
+ export interface StatusLookupDeps {
19
+ gatewayTransfers?: GatewayTransferQuery;
20
+ arcSelfSettle?: ArcSelfSettleHandle;
21
+ failureStore?: FailureStore;
22
+ }
23
+ export type PaymentStatusLookup = (ref: string) => Promise<PaymentStatus>;
24
+ interface TransferLike {
25
+ id: string;
26
+ status: string;
27
+ sendingNetwork?: string;
28
+ amount?: string;
29
+ updatedAt?: string;
30
+ }
31
+ export declare function createPaymentStatusLookup(deps: StatusLookupDeps): PaymentStatusLookup;
32
+ export {};
package/dist/status.js ADDED
@@ -0,0 +1,86 @@
1
+ const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
2
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
3
+ const GATEWAY_STATUS_MAP = {
4
+ received: "pending",
5
+ batched: "pending",
6
+ confirmed: "confirmed",
7
+ completed: "completed",
8
+ failed: "failed",
9
+ };
10
+ export function createPaymentStatusLookup(deps) {
11
+ return async (ref) => {
12
+ if (TX_HASH_RE.test(ref)) {
13
+ const client = deps.arcSelfSettle?.publicClient;
14
+ if (!client) {
15
+ return { status: "not_found", ref, refType: "tx-hash" };
16
+ }
17
+ try {
18
+ const receipt = (await client.getTransactionReceipt({
19
+ hash: ref,
20
+ }));
21
+ if (!receipt) {
22
+ return {
23
+ status: "pending",
24
+ ref,
25
+ refType: "tx-hash",
26
+ scheme: "eip3009-client-broadcast",
27
+ };
28
+ }
29
+ return {
30
+ status: receipt.status === "success" ? "confirmed" : "failed",
31
+ ref,
32
+ refType: "tx-hash",
33
+ scheme: "eip3009-client-broadcast",
34
+ network: deps.arcSelfSettle?.network,
35
+ raw: receipt,
36
+ };
37
+ }
38
+ catch {
39
+ return { status: "not_found", ref, refType: "tx-hash" };
40
+ }
41
+ }
42
+ if (UUID_RE.test(ref)) {
43
+ const query = deps.gatewayTransfers;
44
+ if (!query) {
45
+ return { status: "not_found", ref, refType: "gateway-transfer" };
46
+ }
47
+ try {
48
+ const t = await query.getTransferById(ref);
49
+ return {
50
+ status: GATEWAY_STATUS_MAP[t.status] ?? "pending",
51
+ ref,
52
+ refType: "gateway-transfer",
53
+ scheme: "gateway",
54
+ network: t.sendingNetwork,
55
+ amount: t.amount,
56
+ confirmedAt: t.updatedAt,
57
+ raw: t,
58
+ };
59
+ }
60
+ catch {
61
+ return { status: "not_found", ref, refType: "gateway-transfer" };
62
+ }
63
+ }
64
+ if (deps.failureStore) {
65
+ try {
66
+ const entries = await deps.failureStore.list();
67
+ const hit = entries.find((e) => e.paymentId === ref || e.txRef === ref);
68
+ if (hit) {
69
+ return {
70
+ status: "failed",
71
+ ref,
72
+ refType: "internal",
73
+ scheme: hit.scheme,
74
+ network: hit.network,
75
+ amount: hit.amount,
76
+ confirmedAt: hit.at,
77
+ raw: hit,
78
+ };
79
+ }
80
+ }
81
+ catch {
82
+ }
83
+ }
84
+ return { status: "not_found", ref, refType: "internal" };
85
+ };
86
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@agentbadge/circle-payments",
3
+ "version": "0.1.0",
4
+ "description": "Circle Gateway nanopayments + x402 payment rails (Base Sepolia, Arc) for AgentBadge \u2014 trusted agent payments",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "author": "AgentBadge",
12
+ "license": "MIT",
13
+ "keywords": [
14
+ "x402",
15
+ "circle",
16
+ "gateway",
17
+ "nanopayments",
18
+ "usdc",
19
+ "arc",
20
+ "agent",
21
+ "payments"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "engines": {
27
+ "node": ">=18"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc",
31
+ "prepublishOnly": "npm run build",
32
+ "test": "vitest run --run"
33
+ },
34
+ "dependencies": {
35
+ "@circle-fin/x402-batching": "^3.5.0",
36
+ "@x402/core": "^2.3.0",
37
+ "@x402/evm": "^2.3.0",
38
+ "viem": "^2.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@vitest/coverage-v8": "^2.0.0",
42
+ "bun-types": "^1.3.14",
43
+ "hono": "^4.13.8",
44
+ "tsx": "^4.19.0",
45
+ "typescript": "^5.9.0",
46
+ "vitest": "^2.0.0"
47
+ },
48
+ "peerDependencies": {
49
+ "hono": "^4.7.0"
50
+ }
51
+ }