@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.
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+ import { createPublicClient, createWalletClient, defineChain, erc20Abi, http, } from "viem";
3
+ import { privateKeyToAccount } from "viem/accounts";
4
+ import { getChain } from "../chains.js";
5
+ import { decode402 } from "../identity/verify-passport.js";
6
+ import { assertCaps, BudgetExhaustedError, CapExceededError, PaymentNotAcceptedError, } from "../buyer/caps.js";
7
+ import { atomicToUsd, validateAccepts, } from "../buyer/accepts.js";
8
+ import { createPayingClient, PaymentRefusedError, } from "../buyer/client.js";
9
+ import { createRiskGuard } from "../buyer/risk-guard.js";
10
+ import { gatewayBalance } from "../gateway/deposit.js";
11
+ const EXIT_OK = 0;
12
+ const EXIT_REFUSED = 2;
13
+ const EXIT_TRANSPORT = 3;
14
+ const USAGE = `agentbadge pay <url> — pay an x402-gated resource
15
+
16
+ Required (flag or env, flag wins):
17
+ --max-payment <usd> per-call cap (AGENTBADGE_MAX_PAYMENT)
18
+ --budget <usd> session budget (AGENTBADGE_BUDGET)
19
+
20
+ Optional:
21
+ --method <m> HTTP method (default GET)
22
+ --body <json> request body
23
+ --network <caip2> restrict to one network (e.g. eip155:5042002)
24
+ --auto-deposit <usd> auto top-up Gateway balance when short
25
+ --risk-check vet every payTo via risk API before signing
26
+ (AGENTBADGE_RISK_ENDPOINT to override)
27
+ --print-only show payment details, never sign
28
+ --help this text
29
+
30
+ Secrets:
31
+ AGENTBADGE_PAYER_KEY payer private key (env only — never a flag)
32
+
33
+ Exit codes: 0 ok · 2 refusal/cap/budget/usage · 3 transport`;
34
+ function parseArgs(argv) {
35
+ const args = { method: "GET", printOnly: false, help: false, riskCheck: false };
36
+ const takeValue = (i, flag) => {
37
+ const v = argv[i + 1];
38
+ if (v === undefined || v.startsWith("--")) {
39
+ throw new TypeError(`flag ${flag} requires a value`);
40
+ }
41
+ return v;
42
+ };
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const a = argv[i];
45
+ switch (a) {
46
+ case "pay":
47
+ break;
48
+ case "--max-payment":
49
+ args.maxPayment = takeValue(i++, a);
50
+ break;
51
+ case "--budget":
52
+ args.budget = takeValue(i++, a);
53
+ break;
54
+ case "--method":
55
+ args.method = takeValue(i++, a).toUpperCase();
56
+ break;
57
+ case "--body":
58
+ args.body = takeValue(i++, a);
59
+ break;
60
+ case "--network":
61
+ args.network = takeValue(i++, a);
62
+ break;
63
+ case "--auto-deposit":
64
+ args.autoDeposit = takeValue(i++, a);
65
+ break;
66
+ case "--risk-check":
67
+ args.riskCheck = true;
68
+ break;
69
+ case "--print-only":
70
+ args.printOnly = true;
71
+ break;
72
+ case "--help":
73
+ case "-h":
74
+ args.help = true;
75
+ break;
76
+ default:
77
+ if (!a.startsWith("-") && args.url === undefined) {
78
+ args.url = a;
79
+ }
80
+ else {
81
+ throw new TypeError(`unknown argument: ${a}`);
82
+ }
83
+ }
84
+ }
85
+ return args;
86
+ }
87
+ function toViemChain(c) {
88
+ return defineChain({
89
+ id: c.chainId,
90
+ name: c.name,
91
+ nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 18 },
92
+ rpcUrls: { default: { http: [c.rpcUrl] } },
93
+ });
94
+ }
95
+ function toCaps(args, env) {
96
+ const maxPaymentUsd = args.maxPayment ?? env.AGENTBADGE_MAX_PAYMENT;
97
+ const sessionBudgetUsd = args.budget ?? env.AGENTBADGE_BUDGET;
98
+ const caps = {
99
+ maxPaymentUsd: maxPaymentUsd ?? "",
100
+ sessionBudgetUsd: sessionBudgetUsd ?? "",
101
+ ...(args.network
102
+ ? { allowedNetworks: [args.network] }
103
+ : {}),
104
+ };
105
+ assertCaps(caps);
106
+ return caps;
107
+ }
108
+ async function eoaUsdcBalance(chain, address) {
109
+ try {
110
+ const client = createPublicClient({
111
+ chain: toViemChain(chain),
112
+ transport: http(chain.rpcUrl),
113
+ });
114
+ return (await client.readContract({
115
+ address: chain.usdc,
116
+ abi: erc20Abi,
117
+ functionName: "balanceOf",
118
+ args: [address],
119
+ }));
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
125
+ export async function runPay(argv, env = process.env, io = {}) {
126
+ const out = io.stdout ?? ((s) => console.log(s));
127
+ const err = io.stderr ?? ((s) => console.error(s));
128
+ const fetchImpl = io.fetchImpl ?? fetch;
129
+ let args;
130
+ try {
131
+ args = parseArgs(argv);
132
+ }
133
+ catch (e) {
134
+ err(`${e.message}\n\n${USAGE}`);
135
+ return EXIT_REFUSED;
136
+ }
137
+ if (args.help) {
138
+ out(USAGE);
139
+ return EXIT_OK;
140
+ }
141
+ if (!args.url) {
142
+ err(`missing <url>\n\n${USAGE}`);
143
+ return EXIT_REFUSED;
144
+ }
145
+ let caps;
146
+ try {
147
+ caps = toCaps(args, env);
148
+ }
149
+ catch (e) {
150
+ err(`${e.message}\n\n${USAGE}`);
151
+ return EXIT_REFUSED;
152
+ }
153
+ const init = {
154
+ method: args.method,
155
+ ...(args.body !== undefined ? { body: args.body } : {}),
156
+ };
157
+ let preflight;
158
+ try {
159
+ preflight = await fetchImpl(args.url, init);
160
+ }
161
+ catch (e) {
162
+ err(`transport error: ${e.message}`);
163
+ return EXIT_TRANSPORT;
164
+ }
165
+ if (preflight.status !== 402) {
166
+ out(`status ${preflight.status} — no payment required`);
167
+ return preflight.ok ? EXIT_OK : EXIT_TRANSPORT;
168
+ }
169
+ const pr = decode402((preflight.headers.get("payment-required") ??
170
+ (await preflight.clone().json().catch(() => undefined))));
171
+ const verdict = validateAccepts(pr, caps);
172
+ if (!verdict.ok) {
173
+ err(`refused field=${verdict.field} value=${JSON.stringify(verdict.value)}: ${verdict.reason}`);
174
+ return EXIT_REFUSED;
175
+ }
176
+ const req = verdict.requirements;
177
+ const chain = getChain(req.network);
178
+ err(`paying ${verdict.priceUsd} USDC to ${req.payTo} on ${chain?.name ?? req.network} (scheme ${req.scheme})`);
179
+ if (args.printOnly) {
180
+ out(JSON.stringify({
181
+ scheme: req.scheme,
182
+ network: req.network,
183
+ asset: req.asset,
184
+ amountAtomic: req.amount,
185
+ priceUsd: verdict.priceUsd,
186
+ payTo: req.payTo,
187
+ }, null, 2));
188
+ return EXIT_OK;
189
+ }
190
+ const key = env.AGENTBADGE_PAYER_KEY;
191
+ if (!key) {
192
+ err("AGENTBADGE_PAYER_KEY is not set — cannot sign payment");
193
+ return EXIT_REFUSED;
194
+ }
195
+ const account = privateKeyToAccount((key.startsWith("0x") ? key : `0x${key}`));
196
+ if (req.scheme === "gateway-batch" && !args.autoDeposit && chain) {
197
+ const gw = await gatewayBalance({
198
+ depositor: account.address,
199
+ chain,
200
+ fetchImpl,
201
+ });
202
+ const need = BigInt(req.amount);
203
+ if (gw && BigInt(gw.available ?? "0") < need) {
204
+ const eoa = await eoaUsdcBalance(chain, account.address);
205
+ const suggestion = eoa !== undefined && eoa >= need
206
+ ? `run: agentbadge gateway deposit --amount ${verdict.priceUsd} --network ${req.network}`
207
+ : `deposit USDC to GatewayWallet ${chain.gatewayWallet} on ${chain.name}`;
208
+ err(`gateway balance ${gw.available} < price ${req.amount} — ${suggestion}`);
209
+ return EXIT_REFUSED;
210
+ }
211
+ }
212
+ const signer = {
213
+ address: account.address,
214
+ signTypedData: (a) => account.signTypedData(a),
215
+ signMessage: (a) => account.signMessage(a),
216
+ writeContract: async (wcArgs) => {
217
+ if (!chain) {
218
+ throw new PaymentRefusedError("network", req.network, "unknown chain");
219
+ }
220
+ const wc = createWalletClient({
221
+ account,
222
+ chain: toViemChain(chain),
223
+ transport: http(chain.rpcUrl),
224
+ });
225
+ return wc.writeContract(wcArgs);
226
+ },
227
+ };
228
+ const client = createPayingClient({
229
+ caps,
230
+ signer,
231
+ fetch: fetchImpl,
232
+ ...(args.autoDeposit
233
+ ? { gateway: { autoDepositUsd: args.autoDeposit } }
234
+ : {}),
235
+ ...(args.riskCheck
236
+ ? {
237
+ beforePayment: createRiskGuard({
238
+ ...(env.AGENTBADGE_RISK_ENDPOINT
239
+ ? { endpoint: env.AGENTBADGE_RISK_ENDPOINT }
240
+ : {}),
241
+ fetchImpl,
242
+ }),
243
+ }
244
+ : {}),
245
+ });
246
+ try {
247
+ const res = await client.request(args.url, init);
248
+ const text = await res.text().catch(() => "");
249
+ out(`status ${res.status} spent=${client.spent()} atomic (${atomicToUsd(client.spent())} USDC of budget ${atomicToUsd(client.budget())})`);
250
+ if (text)
251
+ out(text);
252
+ return res.ok ? EXIT_OK : EXIT_TRANSPORT;
253
+ }
254
+ catch (e) {
255
+ if (e instanceof PaymentRefusedError ||
256
+ e instanceof CapExceededError ||
257
+ e instanceof BudgetExhaustedError ||
258
+ e instanceof PaymentNotAcceptedError ||
259
+ e instanceof TypeError) {
260
+ const named = e instanceof PaymentRefusedError
261
+ ? ` field=${e.field} value=${JSON.stringify(e.value)}`
262
+ : "";
263
+ err(`refused:${named} ${e.message}`);
264
+ return EXIT_REFUSED;
265
+ }
266
+ err(`transport error: ${e.message}`);
267
+ return EXIT_TRANSPORT;
268
+ }
269
+ }
270
+ const isMain = typeof process !== "undefined" &&
271
+ process.argv[1] !== undefined &&
272
+ import.meta.url === `file://${process.argv[1]}`;
273
+ if (isMain) {
274
+ runPay(process.argv.slice(2)).then((code) => process.exit(code));
275
+ }
@@ -387,7 +387,220 @@ export declare const ERC8183_ACP_ABI: readonly [{
387
387
  }];
388
388
  readonly anonymous: false;
389
389
  }];
390
- export type Erc8183Variant = "circle" | "acp";
390
+ export declare const ERC8183_REF_ABI: readonly [{
391
+ readonly type: "function";
392
+ readonly name: "createJob";
393
+ readonly stateMutability: "nonpayable";
394
+ readonly inputs: readonly [{
395
+ readonly name: "provider";
396
+ readonly type: "address";
397
+ }, {
398
+ readonly name: "evaluator";
399
+ readonly type: "address";
400
+ }, {
401
+ readonly name: "expiredAt";
402
+ readonly type: "uint48";
403
+ }, {
404
+ readonly name: "description";
405
+ readonly type: "string";
406
+ }, {
407
+ readonly name: "hook";
408
+ readonly type: "address";
409
+ }, {
410
+ readonly name: "providerAgentId";
411
+ readonly type: "uint256";
412
+ }];
413
+ readonly outputs: readonly [{
414
+ readonly name: "jobId";
415
+ readonly type: "uint256";
416
+ }];
417
+ }, {
418
+ readonly type: "function";
419
+ readonly name: "setProvider";
420
+ readonly stateMutability: "nonpayable";
421
+ readonly inputs: readonly [{
422
+ readonly name: "jobId";
423
+ readonly type: "uint256";
424
+ }, {
425
+ readonly name: "provider";
426
+ readonly type: "address";
427
+ }, {
428
+ readonly name: "agentId";
429
+ readonly type: "uint256";
430
+ }];
431
+ readonly outputs: readonly [];
432
+ }, {
433
+ readonly type: "function";
434
+ readonly name: "setBudget";
435
+ readonly stateMutability: "nonpayable";
436
+ readonly inputs: readonly [{
437
+ readonly name: "jobId";
438
+ readonly type: "uint256";
439
+ }, {
440
+ readonly name: "token";
441
+ readonly type: "address";
442
+ }, {
443
+ readonly name: "amount";
444
+ readonly type: "uint256";
445
+ }, {
446
+ readonly name: "optParams";
447
+ readonly type: "bytes";
448
+ }];
449
+ readonly outputs: readonly [];
450
+ }, {
451
+ readonly type: "function";
452
+ readonly name: "fund";
453
+ readonly stateMutability: "nonpayable";
454
+ readonly inputs: readonly [{
455
+ readonly name: "jobId";
456
+ readonly type: "uint256";
457
+ }, {
458
+ readonly name: "expectedToken";
459
+ readonly type: "address";
460
+ }, {
461
+ readonly name: "expectedBudget";
462
+ readonly type: "uint256";
463
+ }, {
464
+ readonly name: "optParams";
465
+ readonly type: "bytes";
466
+ }];
467
+ readonly outputs: readonly [];
468
+ }, {
469
+ readonly type: "function";
470
+ readonly name: "submit";
471
+ readonly stateMutability: "nonpayable";
472
+ readonly inputs: readonly [{
473
+ readonly name: "jobId";
474
+ readonly type: "uint256";
475
+ }, {
476
+ readonly name: "deliverable";
477
+ readonly type: "bytes32";
478
+ }, {
479
+ readonly name: "optParams";
480
+ readonly type: "bytes";
481
+ }];
482
+ readonly outputs: readonly [];
483
+ }, {
484
+ readonly type: "function";
485
+ readonly name: "complete";
486
+ readonly stateMutability: "nonpayable";
487
+ readonly inputs: readonly [{
488
+ readonly name: "jobId";
489
+ readonly type: "uint256";
490
+ }, {
491
+ readonly name: "reason";
492
+ readonly type: "bytes32";
493
+ }, {
494
+ readonly name: "optParams";
495
+ readonly type: "bytes";
496
+ }];
497
+ readonly outputs: readonly [];
498
+ }, {
499
+ readonly type: "function";
500
+ readonly name: "reject";
501
+ readonly stateMutability: "nonpayable";
502
+ readonly inputs: readonly [{
503
+ readonly name: "jobId";
504
+ readonly type: "uint256";
505
+ }, {
506
+ readonly name: "reason";
507
+ readonly type: "bytes32";
508
+ }, {
509
+ readonly name: "optParams";
510
+ readonly type: "bytes";
511
+ }];
512
+ readonly outputs: readonly [];
513
+ }, {
514
+ readonly type: "function";
515
+ readonly name: "claimRefund";
516
+ readonly stateMutability: "nonpayable";
517
+ readonly inputs: readonly [{
518
+ readonly name: "jobId";
519
+ readonly type: "uint256";
520
+ }];
521
+ readonly outputs: readonly [];
522
+ }, {
523
+ readonly type: "function";
524
+ readonly name: "getJob";
525
+ readonly stateMutability: "view";
526
+ readonly inputs: readonly [{
527
+ readonly name: "jobId";
528
+ readonly type: "uint256";
529
+ }];
530
+ readonly outputs: readonly [{
531
+ readonly type: "tuple";
532
+ readonly components: readonly [{
533
+ readonly name: "client";
534
+ readonly type: "address";
535
+ }, {
536
+ readonly name: "status";
537
+ readonly type: "uint8";
538
+ }, {
539
+ readonly name: "provider";
540
+ readonly type: "address";
541
+ }, {
542
+ readonly name: "expiredAt";
543
+ readonly type: "uint48";
544
+ }, {
545
+ readonly name: "evaluator";
546
+ readonly type: "address";
547
+ }, {
548
+ readonly name: "submittedAt";
549
+ readonly type: "uint48";
550
+ }, {
551
+ readonly name: "budget";
552
+ readonly type: "uint256";
553
+ }, {
554
+ readonly name: "hook";
555
+ readonly type: "address";
556
+ }, {
557
+ readonly name: "paymentToken";
558
+ readonly type: "address";
559
+ }, {
560
+ readonly name: "providerAgentId";
561
+ readonly type: "uint256";
562
+ }, {
563
+ readonly name: "description";
564
+ readonly type: "string";
565
+ }, {
566
+ readonly name: "settledAmount";
567
+ readonly type: "uint256";
568
+ }, {
569
+ readonly name: "payoutReceiver";
570
+ readonly type: "address";
571
+ }];
572
+ }];
573
+ }, {
574
+ readonly type: "event";
575
+ readonly name: "JobCreated";
576
+ readonly inputs: readonly [{
577
+ readonly indexed: true;
578
+ readonly name: "jobId";
579
+ readonly type: "uint256";
580
+ }, {
581
+ readonly indexed: true;
582
+ readonly name: "client";
583
+ readonly type: "address";
584
+ }, {
585
+ readonly indexed: true;
586
+ readonly name: "provider";
587
+ readonly type: "address";
588
+ }, {
589
+ readonly indexed: false;
590
+ readonly name: "evaluator";
591
+ readonly type: "address";
592
+ }, {
593
+ readonly indexed: false;
594
+ readonly name: "expiredAt";
595
+ readonly type: "uint48";
596
+ }, {
597
+ readonly indexed: false;
598
+ readonly name: "hook";
599
+ readonly type: "address";
600
+ }];
601
+ readonly anonymous: false;
602
+ }];
603
+ export type Erc8183Variant = "circle" | "acp" | "ref";
391
604
  export interface WriteClient {
392
605
  writeContract(args: {
393
606
  address: `0x${string}`;
@@ -455,6 +668,7 @@ export declare function createErc8183(cfg: Erc8183Config): {
455
668
  expiredAt: bigint;
456
669
  description: string;
457
670
  hook?: `0x${string}`;
671
+ providerAgentId?: bigint;
458
672
  }): Promise<{
459
673
  jobId: bigint;
460
674
  txHash: Hex;