@agentbadge/circle-payments 0.1.18 → 0.1.20

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
@@ -229,6 +229,83 @@ Buyer helpers: `gatewayDepositInfo(chains)`, `depositToGateway(...)`,
229
229
  Reference client: `hackathon/server/examples/crosschain-pay.ts`;
230
230
  docs: `docs/PAYMENTS/CROSSCHAIN.md`.
231
231
 
232
+ ## Buyer client — caps-enforced (EPIC-182)
233
+
234
+ No uncapped clients: `createPayingClient` refuses construction without
235
+ mandatory `PaymentCaps` (`maxPaymentUsd`, `sessionBudgetUsd`, optional
236
+ `allowedNetworks`). Every 402 challenge passes strict `accepts[]`
237
+ validation — unknown scheme/network/asset or `extra.decimals !== 6` is
238
+ refused with a named `{field, value}`, never guessed. Session spend is
239
+ capped and recorded at sign/broadcast (self-settle) or acceptance
240
+ (facilitator rails); a second 402 after a paid retry throws
241
+ `PaymentNotAcceptedError` — no double-pay, no loops.
242
+
243
+ ```ts
244
+ import { createPayingClient, viemSigner, paginateAll }
245
+ from "@agentbadge/circle-payments";
246
+
247
+ const client = createPayingClient({
248
+ caps: { maxPaymentUsd: "0.25", sessionBudgetUsd: "5" },
249
+ signer: viemSigner(walletClient), // or any BuyerSigner
250
+ gateway: { autoDepositUsd: "1" }, // opt-in Gateway top-up
251
+ });
252
+ const res = await client.get("https://api.example.com/paid");
253
+ client.spent(); // atomic units spent
254
+
255
+ // Auto-pagination — each page pays within the same budget:
256
+ const items = await paginateAll(async (cursor) =>
257
+ client.get(`https://api.example.com/list${cursor ? `?cursor=${cursor}` : ""}`));
258
+ ```
259
+
260
+ Errors: `PaymentRefusedError{field,value}` (challenge refused),
261
+ `CapExceededError`, `BudgetExhaustedError`, `PaymentNotAcceptedError`.
262
+
263
+ ### Pre-payment risk guard (EPIC-204)
264
+
265
+ `beforePayment` vets every `payTo` advertised in the 402 BEFORE signing —
266
+ a `{block: reason}` becomes `PaymentRefusedError` and no money moves.
267
+ `createRiskGuard` wraps a payment-forensics risk API
268
+ (`GET /api/v1/risk/:address`); the endpoint is pluggable (ours on Arc or
269
+ any compatible service).
270
+
271
+ ```ts
272
+ import { createPayingClient, createRiskGuard, viemSigner }
273
+ from "@agentbadge/circle-payments";
274
+
275
+ const client = createPayingClient({
276
+ caps,
277
+ signer: viemSigner(walletClient),
278
+ beforePayment: createRiskGuard({
279
+ endpoint: "https://agentbadge.xyz/api/v1/risk", // or any compatible API
280
+ minOrganicShare: 0.3, // organic revenue floor
281
+ allowNoData: true, // new sellers have to start somewhere
282
+ onRiskError: "allow", // "block" = fail-closed
283
+ timeoutMs: 2000, // never hang the 402-loop
284
+ }),
285
+ checkAllOffers: true, // default: vet every accepts[] payTo
286
+ });
287
+ ```
288
+
289
+ Verdicts: `block` (or `caution` below the floor) refuses; `no_data`
290
+ follows `allowNoData`; endpoint errors/429s follow `onRiskError`.
291
+ CLI: `agentbadge pay <url> --risk-check`
292
+ (`AGENTBADGE_RISK_ENDPOINT` to override).
293
+
294
+ ### CLI: `agentbadge pay`
295
+
296
+ ```bash
297
+ export AGENTBADGE_PAYER_KEY=0x… # env only — never a flag
298
+ agentbadge pay https://api.example.com/paid \
299
+ --max-payment 0.25 --budget 5 # or AGENTBADGE_MAX_PAYMENT/_BUDGET
300
+ agentbadge pay <url> --print-only # show payment terms, never sign
301
+ agentbadge pay <url> --auto-deposit 1 # top up Gateway when short
302
+ ```
303
+
304
+ Exit codes: `0` ok · `2` refusal/cap/budget/usage · `3` transport.
305
+ Every refusal names the field (`field=scheme value=…`) on stderr.
306
+ A `gateway-batch` challenge with insufficient unified balance prints
307
+ the deposit command instead of a bare "insufficient".
308
+
232
309
  ## License
233
310
 
234
311
  MIT
@@ -0,0 +1,33 @@
1
+ import { type PaymentRequirements } from "../chains.js";
2
+ import type { PaymentPayload } from "../middleware.js";
3
+ import { type PaymentCaps } from "./caps.js";
4
+ export interface PaymentRequired402 {
5
+ x402Version: number;
6
+ resource?: {
7
+ url?: string;
8
+ description?: string;
9
+ mimeType?: string;
10
+ };
11
+ accepts: PaymentRequirements[];
12
+ extensions?: Record<string, unknown>;
13
+ }
14
+ export interface ValidateAcceptsOk {
15
+ ok: true;
16
+ requirements: PaymentRequirements;
17
+ priceUsd: string;
18
+ }
19
+ export interface ValidateAcceptsRefuse {
20
+ ok: false;
21
+ reason: string;
22
+ field: string;
23
+ value: unknown;
24
+ }
25
+ export type ValidateAcceptsResult = ValidateAcceptsOk | ValidateAcceptsRefuse;
26
+ export interface ValidateAcceptsOptions {
27
+ allowedSchemes?: string[];
28
+ }
29
+ export declare const ALLOWED_SCHEMES: readonly ["exact", "eip3009-client-broadcast", "gateway-batch"];
30
+ export declare function atomicToUsd(atomic: string): string;
31
+ export declare function matchAccepted(payload: Pick<PaymentPayload, "accepted">, accepts: PaymentRequirements[]): PaymentRequirements | undefined;
32
+ export declare function isGatewayBatch(requirements: PaymentRequirements): boolean;
33
+ export declare function validateAccepts(pr: PaymentRequired402 | string, caps: PaymentCaps, opts?: ValidateAcceptsOptions): ValidateAcceptsResult;
@@ -0,0 +1,150 @@
1
+ import { supportsBatching } from "@circle-fin/x402-batching";
2
+ import { ARC_MAINNET, ARC_TESTNET, getChain, } from "../chains.js";
3
+ import { decode402 } from "../identity/verify-passport.js";
4
+ import { assertCaps, usdToAtomic, } from "./caps.js";
5
+ export const ALLOWED_SCHEMES = [
6
+ "exact",
7
+ "eip3009-client-broadcast",
8
+ "gateway-batch",
9
+ ];
10
+ const SCHEME_PREFERENCE = {
11
+ exact: 0,
12
+ "gateway-batch": 1,
13
+ "eip3009-client-broadcast": 2,
14
+ };
15
+ const SUPPORTED_VERSION = 2;
16
+ const EXPECTED_DECIMALS = 6;
17
+ const refuse = (reason, field, value) => ({
18
+ ok: false,
19
+ reason,
20
+ field,
21
+ value,
22
+ });
23
+ export function atomicToUsd(atomic) {
24
+ const n = BigInt(atomic);
25
+ const int = n / 1000000n;
26
+ const frac = (n % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
27
+ return frac ? `${int}.${frac}` : int.toString();
28
+ }
29
+ export function matchAccepted(payload, accepts) {
30
+ const accepted = payload.accepted;
31
+ if (!accepted)
32
+ return undefined;
33
+ return accepts.find((a) => a.scheme === accepted.scheme &&
34
+ a.network === accepted.network &&
35
+ a.asset === accepted.asset &&
36
+ (a.extra?.name ?? undefined) === (accepted.extra?.name ?? undefined));
37
+ }
38
+ export function isGatewayBatch(requirements) {
39
+ return supportsBatching(requirements);
40
+ }
41
+ function defaultAllowedNetworks(caps) {
42
+ return caps.allowedNetworks ?? [ARC_MAINNET.caip2, ARC_TESTNET.caip2];
43
+ }
44
+ function checkEntry(e, caps, allowedNetworks, allowedSchemes, capAtomic) {
45
+ if (!allowedSchemes.includes(e.scheme)) {
46
+ return {
47
+ ok: false,
48
+ field: "scheme",
49
+ value: e.scheme,
50
+ reason: `unsupported scheme ${JSON.stringify(e.scheme)}`,
51
+ };
52
+ }
53
+ if (!allowedNetworks.includes(e.network)) {
54
+ return {
55
+ ok: false,
56
+ field: "network",
57
+ value: e.network,
58
+ reason: `network ${JSON.stringify(e.network)} not in allowedNetworks`,
59
+ };
60
+ }
61
+ const chain = getChain(e.network);
62
+ if (!chain) {
63
+ return {
64
+ ok: false,
65
+ field: "network",
66
+ value: e.network,
67
+ reason: `unknown network ${JSON.stringify(e.network)}`,
68
+ };
69
+ }
70
+ if (e.asset.toLowerCase() !== chain.usdc.toLowerCase()) {
71
+ return {
72
+ ok: false,
73
+ field: "asset",
74
+ value: e.asset,
75
+ reason: `asset ${e.asset} is not ${chain.name} USDC ${chain.usdc} — refusing non-USDC`,
76
+ };
77
+ }
78
+ const decimals = e.extra?.decimals;
79
+ if (decimals !== undefined && decimals !== EXPECTED_DECIMALS) {
80
+ return {
81
+ ok: false,
82
+ field: "extra.decimals",
83
+ value: decimals,
84
+ reason: `asset decimals ${JSON.stringify(decimals)} !== ${EXPECTED_DECIMALS} — refusing mis-scale`,
85
+ };
86
+ }
87
+ let amount;
88
+ try {
89
+ if (typeof e.amount !== "string" || !/^\d+$/.test(e.amount)) {
90
+ throw new Error("bad amount");
91
+ }
92
+ amount = BigInt(e.amount);
93
+ }
94
+ catch {
95
+ return {
96
+ ok: false,
97
+ field: "amount",
98
+ value: e.amount,
99
+ reason: `amount ${JSON.stringify(e.amount)} is not an atomic integer string`,
100
+ };
101
+ }
102
+ if (amount > capAtomic) {
103
+ return {
104
+ ok: false,
105
+ field: "amount",
106
+ value: e.amount,
107
+ reason: `amount ${e.amount} exceeds per-call cap ${capAtomic.toString()} (atomic units)`,
108
+ };
109
+ }
110
+ return { ok: true };
111
+ }
112
+ export function validateAccepts(pr, caps, opts = {}) {
113
+ assertCaps(caps);
114
+ const parsed = decode402(pr);
115
+ if (!parsed || typeof parsed !== "object") {
116
+ return refuse("malformed payment-required payload", "payload", undefined);
117
+ }
118
+ if (parsed.x402Version !== SUPPORTED_VERSION) {
119
+ return refuse(`unsupported x402Version ${JSON.stringify(parsed.x402Version)} — expected ${SUPPORTED_VERSION}`, "x402Version", parsed.x402Version);
120
+ }
121
+ const accepts = parsed.accepts;
122
+ if (!Array.isArray(accepts) || accepts.length === 0) {
123
+ return refuse("402 payload has no accepts[] entries", "accepts", accepts);
124
+ }
125
+ const allowedNetworks = defaultAllowedNetworks(caps);
126
+ const allowedSchemes = opts.allowedSchemes ?? [...ALLOWED_SCHEMES];
127
+ const capAtomic = BigInt(usdToAtomic(caps.maxPaymentUsd));
128
+ const valid = [];
129
+ let firstRefusal;
130
+ for (const e of accepts) {
131
+ const check = checkEntry(e, caps, allowedNetworks, allowedSchemes, capAtomic);
132
+ if (check.ok) {
133
+ valid.push(e);
134
+ }
135
+ else if (!firstRefusal) {
136
+ firstRefusal = check;
137
+ }
138
+ }
139
+ if (valid.length === 0) {
140
+ return refuse(firstRefusal?.reason ?? "no accepts entry passes validation", firstRefusal?.field ?? "accepts", firstRefusal?.value);
141
+ }
142
+ valid.sort((a, b) => (SCHEME_PREFERENCE[a.scheme] ?? 99) -
143
+ (SCHEME_PREFERENCE[b.scheme] ?? 99));
144
+ const requirements = valid[0];
145
+ return {
146
+ ok: true,
147
+ requirements,
148
+ priceUsd: atomicToUsd(requirements.amount),
149
+ };
150
+ }
@@ -0,0 +1,27 @@
1
+ import type { Caip2 } from "../chains.js";
2
+ export interface PaymentCaps {
3
+ maxPaymentUsd: string;
4
+ sessionBudgetUsd: string;
5
+ allowedNetworks?: Caip2[];
6
+ }
7
+ export declare function assertCaps(caps: PaymentCaps | undefined | null): asserts caps is PaymentCaps;
8
+ export declare function usdToAtomic(usd: string): string;
9
+ export declare class CapExceededError extends Error {
10
+ readonly name = "CapExceededError";
11
+ readonly cap: string;
12
+ readonly requested: string;
13
+ constructor(cap: string, requested: string);
14
+ }
15
+ export declare class BudgetExhaustedError extends Error {
16
+ readonly name = "BudgetExhaustedError";
17
+ readonly spent: string;
18
+ readonly budget: string;
19
+ readonly requested: string;
20
+ constructor(spent: string, budget: string, requested: string);
21
+ }
22
+ export declare class PaymentNotAcceptedError extends Error {
23
+ readonly name = "PaymentNotAcceptedError";
24
+ readonly field: string;
25
+ readonly value: unknown;
26
+ constructor(reason: string, field: string, value: unknown);
27
+ }
@@ -0,0 +1,67 @@
1
+ const USD_RE = /^\d+(\.\d{1,6})?$/;
2
+ function isValidUsdString(v) {
3
+ return typeof v === "string" && USD_RE.test(v);
4
+ }
5
+ export function assertCaps(caps) {
6
+ if (!caps || typeof caps !== "object") {
7
+ throw new TypeError("PaymentCaps required — refusing to create an uncapped paying client");
8
+ }
9
+ for (const field of ["maxPaymentUsd", "sessionBudgetUsd"]) {
10
+ const v = caps[field];
11
+ if (!isValidUsdString(v)) {
12
+ throw new TypeError(`PaymentCaps.${field} must be a USD decimal string ("0.25"), got ${JSON.stringify(v)} — refusing uncapped client`);
13
+ }
14
+ if (BigInt(usdToAtomic(v)) <= 0n) {
15
+ throw new TypeError(`PaymentCaps.${field} must be > 0 — refusing uncapped client`);
16
+ }
17
+ }
18
+ if (caps.allowedNetworks !== undefined) {
19
+ if (!Array.isArray(caps.allowedNetworks) ||
20
+ caps.allowedNetworks.some((n) => typeof n !== "string")) {
21
+ throw new TypeError("PaymentCaps.allowedNetworks must be an array of CAIP-2 strings");
22
+ }
23
+ }
24
+ }
25
+ export function usdToAtomic(usd) {
26
+ if (!isValidUsdString(usd)) {
27
+ throw new Error(`Invalid USD amount: ${JSON.stringify(usd)}`);
28
+ }
29
+ const dot = usd.indexOf(".");
30
+ const intPart = dot === -1 ? usd : usd.slice(0, dot);
31
+ const fracPart = dot === -1 ? "" : usd.slice(dot + 1);
32
+ const frac6 = (fracPart + "000000").slice(0, 6);
33
+ const atomic = BigInt(intPart) * 1000000n + BigInt(frac6);
34
+ return atomic.toString();
35
+ }
36
+ export class CapExceededError extends Error {
37
+ name = "CapExceededError";
38
+ cap;
39
+ requested;
40
+ constructor(cap, requested) {
41
+ super(`Payment amount ${requested} exceeds per-call cap ${cap} (atomic units)`);
42
+ this.cap = cap;
43
+ this.requested = requested;
44
+ }
45
+ }
46
+ export class BudgetExhaustedError extends Error {
47
+ name = "BudgetExhaustedError";
48
+ spent;
49
+ budget;
50
+ requested;
51
+ constructor(spent, budget, requested) {
52
+ super(`Session budget exhausted: spent ${spent} + requested ${requested} > budget ${budget} (atomic units)`);
53
+ this.spent = spent;
54
+ this.budget = budget;
55
+ this.requested = requested;
56
+ }
57
+ }
58
+ export class PaymentNotAcceptedError extends Error {
59
+ name = "PaymentNotAcceptedError";
60
+ field;
61
+ value;
62
+ constructor(reason, field, value) {
63
+ super(reason);
64
+ this.field = field;
65
+ this.value = value;
66
+ }
67
+ }
@@ -0,0 +1,66 @@
1
+ import { type PaymentCaps } from "./caps.js";
2
+ import type { BeforePaymentFn } from "./guard.js";
3
+ import { type SpendTracker } from "./session.js";
4
+ import { type DepositResult } from "../gateway/deposit.js";
5
+ export interface BuyerSigner {
6
+ address: `0x${string}`;
7
+ signTypedData?: (args: {
8
+ domain: Record<string, unknown>;
9
+ types: Record<string, unknown>;
10
+ primaryType: string;
11
+ message: Record<string, unknown>;
12
+ }) => Promise<`0x${string}`>;
13
+ writeContract?: (args: {
14
+ address: `0x${string}`;
15
+ abi: unknown;
16
+ functionName: string;
17
+ args: readonly unknown[];
18
+ }) => Promise<`0x${string}`>;
19
+ signMessage?: (args: {
20
+ message: string;
21
+ }) => Promise<`0x${string}`>;
22
+ }
23
+ export declare function viemSigner(client: {
24
+ account?: {
25
+ address: `0x${string}`;
26
+ } | `0x${string}`;
27
+ signTypedData?: BuyerSigner["signTypedData"];
28
+ writeContract?: BuyerSigner["writeContract"];
29
+ signMessage?: BuyerSigner["signMessage"];
30
+ }): BuyerSigner;
31
+ export declare class PaymentRefusedError extends Error {
32
+ readonly field: string;
33
+ readonly value: unknown;
34
+ constructor(field: string, value: unknown, reason: string);
35
+ }
36
+ export interface GatewayFundingOptions {
37
+ autoDepositUsd?: string;
38
+ minDepositUsd?: string;
39
+ apiUrl?: string;
40
+ }
41
+ export interface PayingClientOptions {
42
+ caps: PaymentCaps;
43
+ signer: BuyerSigner;
44
+ fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
45
+ onSpend?: (entry: {
46
+ amountAtomic: string;
47
+ network?: string;
48
+ scheme?: string;
49
+ resource?: string;
50
+ }) => void;
51
+ gateway?: GatewayFundingOptions;
52
+ beforePayment?: BeforePaymentFn;
53
+ checkAllOffers?: boolean;
54
+ }
55
+ export interface PayingClient {
56
+ request(url: string, init?: RequestInit): Promise<Response>;
57
+ get(url: string, init?: RequestInit): Promise<Response>;
58
+ post(url: string, init?: RequestInit): Promise<Response>;
59
+ spent(): string;
60
+ budget(): string;
61
+ deposits(): readonly DepositResult[];
62
+ readonly tracker: SpendTracker;
63
+ readonly caps: PaymentCaps;
64
+ readonly signer: BuyerSigner;
65
+ }
66
+ export declare function createPayingClient(opts: PayingClientOptions): PayingClient;