@agentbadge/circle-payments 0.1.25 → 0.1.27

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.
@@ -1,4 +1,5 @@
1
1
  import { sanitizeUrlForCheck } from "./sanitize-url.js";
2
+ import { normalizeNetwork } from "./terms.js";
2
3
  export function vet402ClientOptionsFromEnv(env) {
3
4
  const int = (k) => {
4
5
  const v = env[k];
@@ -11,6 +12,7 @@ export function vet402ClientOptionsFromEnv(env) {
11
12
  decisionTtlMs: int("COUNTERPARTY_DECISION_TTL_MS"),
12
13
  blockTtlMs: int("COUNTERPARTY_BLOCK_TTL_MS"),
13
14
  maxRpm: int("COUNTERPARTY_MAX_RPM"),
15
+ perWalletRpm: int("COUNTERPARTY_WALLET_RPM"),
14
16
  connectTimeoutMs: int("COUNTERPARTY_CONNECT_TIMEOUT_MS"),
15
17
  totalTimeoutMs: int("COUNTERPARTY_TOTAL_TIMEOUT_MS"),
16
18
  };
@@ -66,6 +68,13 @@ class TokenBucket {
66
68
  const rate = this.capacity / 60_000;
67
69
  return { ok: false, waitMs: Math.ceil((1 - this.tokens) / rate) };
68
70
  }
71
+ peekWaitMs() {
72
+ this.refill();
73
+ if (this.tokens >= 1)
74
+ return 0;
75
+ const rate = this.capacity / 60_000;
76
+ return Math.ceil((1 - this.tokens) / rate);
77
+ }
69
78
  }
70
79
  const LEDGER_UNIT_FACTOR = {
71
80
  "eip155:56": 10n ** 12n,
@@ -87,6 +96,8 @@ export class Vet402Client {
87
96
  decisionCache;
88
97
  inflight = new Map();
89
98
  bucket;
99
+ perWalletRpm;
100
+ walletBuckets;
90
101
  constructor(opts = {}) {
91
102
  this.baseUrl = (opts.baseUrl ?? "https://vet402.com").replace(/\/+$/, "");
92
103
  this.fetch = opts.fetchImpl ?? fetch;
@@ -94,13 +105,26 @@ export class Vet402Client {
94
105
  this.sleep =
95
106
  opts.sleepImpl ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
96
107
  this.decisionTtlMs = opts.decisionTtlMs ?? 5 * 60_000;
97
- this.blockTtlMs = opts.blockTtlMs ?? 60_000;
108
+ this.blockTtlMs = Math.max(opts.blockTtlMs ?? this.decisionTtlMs, this.decisionTtlMs);
98
109
  this.connectTimeoutMs = opts.connectTimeoutMs ?? 2_000;
99
110
  this.totalTimeoutMs = opts.totalTimeoutMs ?? 8_000;
100
111
  this.metrics = opts.metrics;
101
112
  this.resolveCache = new LruCache(opts.resolveCacheSize ?? 1024);
102
113
  this.decisionCache = new LruCache(opts.decisionCacheSize ?? 1024);
103
114
  this.bucket = new TokenBucket(Math.max(1, opts.maxRpm ?? 11), this.now);
115
+ this.perWalletRpm = Math.max(1, opts.perWalletRpm ?? 4);
116
+ this.walletBuckets = new LruCache(opts.decisionCacheSize ?? 1024);
117
+ }
118
+ walletBucketFor(wallet) {
119
+ if (!wallet)
120
+ return undefined;
121
+ const key = wallet.toLowerCase();
122
+ let b = this.walletBuckets.get(key);
123
+ if (!b) {
124
+ b = new TokenBucket(this.perWalletRpm, this.now);
125
+ this.walletBuckets.set(key, b);
126
+ }
127
+ return b;
104
128
  }
105
129
  async check(input) {
106
130
  const t0 = this.now();
@@ -121,16 +145,16 @@ export class Vet402Client {
121
145
  this.emitCheck(a, t0, true);
122
146
  return a;
123
147
  }
124
- const p = this.runCheck(s.url, t0, input.signal)
148
+ const p = this.runCheck(s.url, t0, input.signal, input.wallet)
125
149
  .finally(() => this.inflight.delete(key));
126
150
  this.inflight.set(key, p);
127
151
  return p;
128
152
  }
129
- async runCheck(url, t0, callerSignal) {
153
+ async runCheck(url, t0, callerSignal, wallet) {
130
154
  const deadline = t0 + this.totalTimeoutMs;
131
155
  let rereolved = false;
132
156
  for (;;) {
133
- const resolved = await this.resolveResourceId(url, deadline, callerSignal);
157
+ const resolved = await this.resolveResourceId(url, deadline, callerSignal, wallet);
134
158
  if (resolved.assessment) {
135
159
  this.emitCheck(resolved.assessment, t0, resolved.cacheHit === true);
136
160
  return resolved.assessment;
@@ -142,7 +166,7 @@ export class Vet402Client {
142
166
  this.emitCheck(a, t0, true);
143
167
  return a;
144
168
  }
145
- const out = await this.fetchDecision(resourceId, url, deadline, callerSignal);
169
+ const out = await this.fetchDecision(resourceId, url, deadline, callerSignal, wallet);
146
170
  if (out.assessment) {
147
171
  if (out.assessment.kind === "unavailable" &&
148
172
  out.assessment.failure === "invalid_response" &&
@@ -178,7 +202,7 @@ export class Vet402Client {
178
202
  this.metrics?.onCheck?.(outcome, this.now() - t0);
179
203
  this.metrics?.onCache?.(cacheHit ? "hit" : "miss");
180
204
  }
181
- async resolveResourceId(url, deadline, callerSignal) {
205
+ async resolveResourceId(url, deadline, callerSignal, wallet) {
182
206
  const cached = this.resolveCache.get(url);
183
207
  if (cached && cached.expiresAt > this.now()) {
184
208
  if (cached.notInCatalog) {
@@ -189,11 +213,17 @@ export class Vet402Client {
189
213
  }
190
214
  return { resourceId: cached.resourceId, cacheHit: true };
191
215
  }
192
- const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal);
216
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resolve?q=${encodeURIComponent(url)}`, "resolve", deadline, callerSignal, wallet);
193
217
  if (r.failure)
194
218
  return { assessment: this.unavailable(r.failure) };
195
- if (r.status !== 200)
196
- return { assessment: this.unavailable("invalid_response") };
219
+ if (r.status !== 200) {
220
+ const st = r.status ?? 0;
221
+ return {
222
+ assessment: st >= 400 && st < 500
223
+ ? this.rejected(st)
224
+ : this.unavailable("invalid_response"),
225
+ };
226
+ }
197
227
  const body = r.body;
198
228
  if (body?.not_found?.reason === "not_in_catalog") {
199
229
  this.resolveCache.set(url, {
@@ -209,9 +239,9 @@ export class Vet402Client {
209
239
  }
210
240
  return { assessment: this.unavailable("invalid_response") };
211
241
  }
212
- async fetchDecision(resourceId, url, deadline, callerSignal) {
242
+ async fetchDecision(resourceId, url, deadline, callerSignal, wallet) {
213
243
  const qs = new URLSearchParams({ role: "payer", url });
214
- const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal);
244
+ const r = await this.outbound(`${this.baseUrl}/api/v1/resources/${resourceId}/decision?${qs}`, "decision", deadline, callerSignal, wallet);
215
245
  if (r.failure)
216
246
  return { assessment: this.unavailable(r.failure) };
217
247
  if (r.status === 404) {
@@ -224,8 +254,14 @@ export class Vet402Client {
224
254
  }
225
255
  return { assessment: this.unavailable("invalid_response") };
226
256
  }
227
- if (r.status !== 200)
228
- return { assessment: this.unavailable("invalid_response") };
257
+ if (r.status !== 200) {
258
+ const st = r.status ?? 0;
259
+ return {
260
+ assessment: st >= 400 && st < 500
261
+ ? this.rejected(st)
262
+ : this.unavailable("invalid_response"),
263
+ };
264
+ }
229
265
  const b = r.body;
230
266
  if (b?.recommendation !== "ALLOW" && b?.recommendation !== "WARN" && b?.recommendation !== "BLOCK") {
231
267
  return { assessment: this.unavailable("invalid_response") };
@@ -238,7 +274,9 @@ export class Vet402Client {
238
274
  kind: "verdict",
239
275
  verdict: b.recommendation,
240
276
  reasonCodes: Array.isArray(b.reason_codes)
241
- ? b.reason_codes.filter((c) => typeof c === "string")
277
+ ? b.reason_codes
278
+ .filter((c) => typeof c === "string")
279
+ .map((c) => c.replace(/[\u0000-\u001F\u007F]+/g, " ").slice(0, 200))
242
280
  : [],
243
281
  verifiedTerms: vt,
244
282
  evidenceAgeSeconds: typeof b.evidence_age?.days_since_last_delivery === "number"
@@ -260,11 +298,18 @@ export class Vet402Client {
260
298
  typeof asset !== "string" ||
261
299
  typeof amount !== "string" ||
262
300
  !/^\d+$/.test(amount) ||
301
+ amount.length > 78 ||
263
302
  typeof network !== "string" ||
264
303
  typeof scheme !== "string") {
265
304
  return "invalid";
266
305
  }
267
- const factor = LEDGER_UNIT_FACTOR[network] ?? 1n;
306
+ let factor = 1n;
307
+ try {
308
+ factor = LEDGER_UNIT_FACTOR[normalizeNetwork(network)] ?? 1n;
309
+ }
310
+ catch {
311
+ return "invalid";
312
+ }
268
313
  return {
269
314
  payTo: pay_to,
270
315
  asset,
@@ -276,20 +321,27 @@ export class Vet402Client {
276
321
  unavailable(failure) {
277
322
  return { kind: "unavailable", failure, checkedAt: this.iso() };
278
323
  }
324
+ rejected(httpStatus) {
325
+ return { kind: "rejected", httpStatus, checkedAt: this.iso() };
326
+ }
279
327
  iso() {
280
328
  return new Date(this.now()).toISOString();
281
329
  }
282
- async outbound(url, endpoint, deadline, callerSignal) {
330
+ async outbound(url, endpoint, deadline, callerSignal, wallet) {
331
+ const wb = this.walletBucketFor(wallet);
283
332
  for (;;) {
284
333
  const remaining = deadline - this.now();
285
334
  if (remaining <= 0)
286
335
  return { failure: "timeout" };
287
- const t = this.bucket.tryAcquire();
288
- if (t.ok)
336
+ const waitMs = Math.max(this.bucket.peekWaitMs(), wb?.peekWaitMs() ?? 0);
337
+ if (waitMs === 0) {
338
+ this.bucket.tryAcquire();
339
+ wb?.tryAcquire();
289
340
  break;
290
- if (this.now() + t.waitMs > deadline)
341
+ }
342
+ if (this.now() + waitMs > deadline)
291
343
  return { failure: "rate_limited" };
292
- await this.sleep(t.waitMs);
344
+ await this.sleep(waitMs);
293
345
  }
294
346
  const remaining = deadline - this.now();
295
347
  if (remaining <= 0)
@@ -319,7 +371,25 @@ export class Vet402Client {
319
371
  }
320
372
  if (res.status === 429) {
321
373
  this.metrics?.onRateLimited?.(endpoint);
322
- return { failure: "rate_limited" };
374
+ const ra = Number(res.headers.get("retry-after"));
375
+ if (Number.isFinite(ra) && ra > 0 && ra * 1000 < deadline - this.now()) {
376
+ await this.sleep(ra * 1000);
377
+ try {
378
+ res = await this.fetch(url, {
379
+ method: "GET",
380
+ headers: { accept: "application/json" },
381
+ signal: AbortSignal.timeout(Math.max(0, deadline - this.now())),
382
+ });
383
+ }
384
+ catch {
385
+ return { failure: "rate_limited" };
386
+ }
387
+ if (res.status === 429)
388
+ return { failure: "rate_limited" };
389
+ }
390
+ else {
391
+ return { failure: "rate_limited" };
392
+ }
323
393
  }
324
394
  if (res.status === 503)
325
395
  return { failure: "degraded" };
@@ -387,220 +387,7 @@ export declare const ERC8183_ACP_ABI: readonly [{
387
387
  }];
388
388
  readonly anonymous: false;
389
389
  }];
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";
390
+ export type Erc8183Variant = "circle" | "acp";
604
391
  export interface WriteClient {
605
392
  writeContract(args: {
606
393
  address: `0x${string}`;
@@ -668,7 +455,6 @@ export declare function createErc8183(cfg: Erc8183Config): {
668
455
  expiredAt: bigint;
669
456
  description: string;
670
457
  hook?: `0x${string}`;
671
- providerAgentId?: bigint;
672
458
  }): Promise<{
673
459
  jobId: bigint;
674
460
  txHash: Hex;