@devlab.group/agent-commerce 2.4.0 → 2.5.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.
Files changed (108) hide show
  1. package/README.md +115 -15
  2. package/dist/ap2.d.ts +24 -12
  3. package/dist/ap2.js +31 -13
  4. package/dist/ap2.js.map +1 -1
  5. package/dist/{chunk-AITMDXKW.js → chunk-3OTCFFFT.js} +37 -4
  6. package/dist/chunk-3OTCFFFT.js.map +1 -0
  7. package/dist/{chunk-4OEXK3YG.js → chunk-4K7FIBJM.js} +25 -4
  8. package/dist/chunk-4K7FIBJM.js.map +1 -0
  9. package/dist/{chunk-WUIAUAA7.js → chunk-FKQK5XZA.js} +652 -68
  10. package/dist/chunk-FKQK5XZA.js.map +1 -0
  11. package/dist/chunk-GA3O2A7R.js +92 -0
  12. package/dist/chunk-GA3O2A7R.js.map +1 -0
  13. package/dist/{chunk-6WACRJVT.js → chunk-VUCMBGUR.js} +3 -3
  14. package/dist/{chunk-6WACRJVT.js.map → chunk-VUCMBGUR.js.map} +1 -1
  15. package/dist/cli/{ap2-QDHPRSTF.js → ap2-YAPLERSC.js} +34 -15
  16. package/dist/cli/ap2-YAPLERSC.js.map +1 -0
  17. package/dist/cli/{chunk-G2JEY7MB.js → chunk-2J2IQQ4X.js} +8 -7
  18. package/dist/cli/chunk-2J2IQQ4X.js.map +1 -0
  19. package/dist/cli/chunk-2UPPX3FJ.js +311 -0
  20. package/dist/cli/chunk-2UPPX3FJ.js.map +1 -0
  21. package/dist/cli/{chunk-WYOGIANL.js → chunk-4H2QLHQI.js} +4 -4
  22. package/dist/cli/{chunk-WYOGIANL.js.map → chunk-4H2QLHQI.js.map} +1 -1
  23. package/dist/cli/{chunk-OZ4LAWBK.js → chunk-5R7DM5LM.js} +25 -4
  24. package/dist/cli/chunk-5R7DM5LM.js.map +1 -0
  25. package/dist/cli/chunk-663ALDZA.js +92 -0
  26. package/dist/cli/chunk-663ALDZA.js.map +1 -0
  27. package/dist/cli/{chunk-QQ3WY5L3.js → chunk-IDY2735M.js} +36 -104
  28. package/dist/cli/chunk-IDY2735M.js.map +1 -0
  29. package/dist/cli/chunk-JFVRG2HH.js +107 -0
  30. package/dist/cli/chunk-JFVRG2HH.js.map +1 -0
  31. package/dist/cli/chunk-M7NXVRU5.js +8 -0
  32. package/dist/cli/{chunk-UXB65XCS.js.map → chunk-M7NXVRU5.js.map} +1 -1
  33. package/dist/cli/chunk-NIU5EMSB.js +119 -0
  34. package/dist/cli/chunk-NIU5EMSB.js.map +1 -0
  35. package/dist/cli/{chunk-AZDWFVDW.js → chunk-QA2OPHBF.js} +655 -70
  36. package/dist/cli/chunk-QA2OPHBF.js.map +1 -0
  37. package/dist/cli/{chunk-DCMW67JM.js → chunk-QLUCNPRT.js} +404 -161
  38. package/dist/cli/chunk-QLUCNPRT.js.map +1 -0
  39. package/dist/cli/chunk-SYQLJXIU.js +105 -0
  40. package/dist/cli/chunk-SYQLJXIU.js.map +1 -0
  41. package/dist/cli/{chunk-3MGAJ5FX.js → chunk-VJ4EO4LE.js} +3 -3
  42. package/dist/cli/{chunk-3MGAJ5FX.js.map → chunk-VJ4EO4LE.js.map} +1 -1
  43. package/dist/cli/{chunk-PIMFPCNZ.js → chunk-Z34UMZBB.js} +234 -85
  44. package/dist/cli/chunk-Z34UMZBB.js.map +1 -0
  45. package/dist/cli/config-BWFMN2ZB.js +12 -0
  46. package/dist/cli/{config-UI4EDG4L.js.map → config-BWFMN2ZB.js.map} +1 -1
  47. package/dist/cli/index.js +258 -11
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/cli/{mcp-26LJMN4N.js → mcp-KZEMXLHR.js} +5 -4
  50. package/dist/cli/mcp-KZEMXLHR.js.map +1 -0
  51. package/dist/cli/{near-5AY3HWYF.js → near-U6365VFX.js} +15 -4
  52. package/dist/cli/near-U6365VFX.js.map +1 -0
  53. package/dist/cli/payment-providers-SZL36H3Y.js +6 -0
  54. package/dist/cli/payment-providers-SZL36H3Y.js.map +1 -0
  55. package/dist/cli/{provider-Z4OJNAYI.js → provider-6TKB5ADJ.js} +30 -16
  56. package/dist/cli/provider-6TKB5ADJ.js.map +1 -0
  57. package/dist/cli/receipts-ZGLJWMQG.js +8 -0
  58. package/dist/cli/receipts-ZGLJWMQG.js.map +1 -0
  59. package/dist/cli/reconcile-IC22MJD5.js +4 -0
  60. package/dist/cli/reconcile-IC22MJD5.js.map +1 -0
  61. package/dist/cli/{run-TEPYJUHG.js → run-ZTYPQI4D.js} +151 -115
  62. package/dist/cli/run-ZTYPQI4D.js.map +1 -0
  63. package/dist/cli/svm-KDSPDFJG.js +48 -0
  64. package/dist/cli/svm-KDSPDFJG.js.map +1 -0
  65. package/dist/cli/{x402-BMVONZKA.js → x402-WLYBLODI.js} +10 -9
  66. package/dist/cli/x402-WLYBLODI.js.map +1 -0
  67. package/dist/index.d.ts +112 -12
  68. package/dist/index.js +948 -157
  69. package/dist/index.js.map +1 -1
  70. package/dist/mcp.d.ts +1 -2
  71. package/dist/mcp.js +1 -1
  72. package/dist/mpp.js +24 -11
  73. package/dist/mpp.js.map +1 -1
  74. package/dist/{near-D6C42VPE.js → near-FH7HPZV3.js} +15 -4
  75. package/dist/near-FH7HPZV3.js.map +1 -0
  76. package/dist/{protocol-adapter-C9odYl6l.d.ts → protocol-adapter-DEXpdp8m.d.ts} +102 -48
  77. package/dist/{runtime-Cl_BLVZV.d.ts → runtime-Dz2fSO-P.d.ts} +220 -2
  78. package/dist/svm-KNC3PHMS.js +48 -0
  79. package/dist/svm-KNC3PHMS.js.map +1 -0
  80. package/dist/x402.js +5 -5
  81. package/package.json +1 -1
  82. package/dist/authorization-DjAecwuW.d.ts +0 -115
  83. package/dist/chunk-4OEXK3YG.js.map +0 -1
  84. package/dist/chunk-AITMDXKW.js.map +0 -1
  85. package/dist/chunk-KA2AX5FH.js +0 -44
  86. package/dist/chunk-KA2AX5FH.js.map +0 -1
  87. package/dist/chunk-WUIAUAA7.js.map +0 -1
  88. package/dist/cli/ap2-QDHPRSTF.js.map +0 -1
  89. package/dist/cli/chunk-AZDWFVDW.js.map +0 -1
  90. package/dist/cli/chunk-DCMW67JM.js.map +0 -1
  91. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  92. package/dist/cli/chunk-OSTCU6ZK.js +0 -44
  93. package/dist/cli/chunk-OSTCU6ZK.js.map +0 -1
  94. package/dist/cli/chunk-OZ4LAWBK.js.map +0 -1
  95. package/dist/cli/chunk-PIMFPCNZ.js.map +0 -1
  96. package/dist/cli/chunk-QQ3WY5L3.js.map +0 -1
  97. package/dist/cli/chunk-UXB65XCS.js +0 -8
  98. package/dist/cli/config-UI4EDG4L.js +0 -11
  99. package/dist/cli/mcp-26LJMN4N.js.map +0 -1
  100. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  101. package/dist/cli/provider-Z4OJNAYI.js.map +0 -1
  102. package/dist/cli/run-TEPYJUHG.js.map +0 -1
  103. package/dist/cli/svm-3MMYFPC7.js +0 -33
  104. package/dist/cli/svm-3MMYFPC7.js.map +0 -1
  105. package/dist/cli/x402-BMVONZKA.js.map +0 -1
  106. package/dist/near-D6C42VPE.js.map +0 -1
  107. package/dist/svm-QEUAUNPQ.js +0 -33
  108. package/dist/svm-QEUAUNPQ.js.map +0 -1
@@ -67,6 +67,75 @@ interface AdapterDescriptor {
67
67
  readonly unsupported?: readonly string[];
68
68
  }
69
69
 
70
+ interface CommerceReceipt {
71
+ readonly id: string;
72
+ readonly requestId: string;
73
+ /** Optional for compatibility with rows written before 2.5.0 */
74
+ readonly transactionId?: string;
75
+ readonly resourceId: string;
76
+ /** Absent for free resources */
77
+ readonly payment?: PaymentResult;
78
+ /**
79
+ * Present only when the resource required authorization. A method and a digest,
80
+ * so the receipt records that consent existed without storing the proof.
81
+ */
82
+ readonly authorization?: AuthorizationRecord;
83
+ readonly deliveredAt: IsoTimestamp;
84
+ readonly backendStatus: number;
85
+ readonly durationMs?: number;
86
+ readonly protocol?: string;
87
+ /** Non-secret summary only, never a sensitive backend body */
88
+ readonly metadata?: Readonly<Record<string, unknown>>;
89
+ }
90
+ /** Record of a single payment authorization seen by the gateway */
91
+ interface PaymentAttempt {
92
+ readonly id: string;
93
+ readonly requestId: string;
94
+ /** Optional for compatibility with rows written before 2.5.0 */
95
+ readonly transactionId?: string;
96
+ readonly resourceId: string;
97
+ readonly provider: string;
98
+ /** Unique across the store; see `PaymentResult.replayKey` */
99
+ readonly replayKey: string;
100
+ /**
101
+ * State of the authorization, as far as the gateway can prove it.
102
+ *
103
+ * `settlement-uncertain` means settlement was attempted and no verdict came
104
+ * back (RPC timeout, dropped connection, a facilitator that accepted the
105
+ * transfer and lost the response). The transfer may or may not have
106
+ * happened, so the attempt is unresolved rather than terminal and needs
107
+ * evidence from the chain, not a retry. `externalReference` holds the
108
+ * broadcast transaction hash when one is known.
109
+ *
110
+ * The execution pipeline never writes `failed`: a throw out of `settle()`
111
+ * never proves that nothing moved. It stays in the union because existing
112
+ * databases hold rows with that status.
113
+ */
114
+ readonly status: 'reserved' | 'verified' | 'settled' | 'rejected' | 'failed' | 'settlement-uncertain';
115
+ readonly amount: string;
116
+ readonly currency: string;
117
+ readonly payer?: string;
118
+ readonly payee?: string;
119
+ readonly externalReference?: string;
120
+ readonly rejectionReason?: string;
121
+ /** Records how an unresolved attempt became `settled` or `rejected` after its request ended */
122
+ readonly resolution?: PaymentAttemptResolution;
123
+ readonly createdAt: IsoTimestamp;
124
+ readonly updatedAt: IsoTimestamp;
125
+ }
126
+ /** Who resolved an attempt, manually or by reconciliation, and why */
127
+ interface PaymentAttemptResolution {
128
+ readonly method: 'reconcile' | 'manual';
129
+ /** Caller-supplied identity; the admin token does not identify an individual */
130
+ readonly actor: string;
131
+ readonly reason: string;
132
+ readonly at: IsoTimestamp;
133
+ /** For `manual`, an unverified reference supplied by the operator */
134
+ readonly externalReference?: string;
135
+ /** Public chain facts only */
136
+ readonly evidence?: Readonly<Record<string, unknown>>;
137
+ }
138
+
70
139
  /** HTTP methods a backend handler may use */
71
140
  type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
72
141
  /**
@@ -157,6 +226,13 @@ interface ResourceRegistry {
157
226
  * EVM-specific type may appear in this file.
158
227
  */
159
228
 
229
+ /**
230
+ * `PaymentResult.metadata` key for public coordinates returned by `verify`
231
+ * for later provider reconciliation. Core must store the value unchanged and
232
+ * interpret only `expiresAt`. Never include signatures, payloads or
233
+ * transaction bytes. Experimental: may change in a minor release.
234
+ */
235
+ declare const RECONCILIATION_METADATA_KEY = "reconciliation";
160
236
  /**
161
237
  * Provider-native payment challenge, opaque to core. For x402 the `accepts`
162
238
  * entries are x402 `PaymentRequirements` objects, passed to protocol adapters
@@ -263,6 +339,30 @@ interface PaymentVerificationContext {
263
339
  interface PaymentSettlementContext extends PaymentVerificationContext {
264
340
  readonly verification: PaymentResult;
265
341
  }
342
+ /** Input to {@link PaymentProvider.reconcile}. Experimental: may change in a minor release */
343
+ interface PaymentReconciliationContext {
344
+ readonly attempt: PaymentAttempt;
345
+ /** Coordinates from `verify`; optional for compatibility with pre-2.5.0 attempts */
346
+ readonly locator?: Readonly<Record<string, unknown>>;
347
+ readonly now: IsoTimestamp;
348
+ }
349
+ /** Chain evidence for resolving an attempt. Experimental: may change in a minor release */
350
+ interface PaymentReconciliationResult {
351
+ /**
352
+ * Report `settled` only with a final transfer record for this authorization.
353
+ * Report `not-settled` only when a state read proves it unused after it can
354
+ * no longer land; missing logs or receipts are insufficient. Otherwise,
355
+ * report `unknown`.
356
+ */
357
+ readonly outcome: 'settled' | 'not-settled' | 'unknown';
358
+ /** A machine-readable token, such as `not_final` */
359
+ readonly reason: string;
360
+ readonly externalReference?: string;
361
+ /** Public chain facts only */
362
+ readonly evidence?: Readonly<Record<string, unknown>>;
363
+ /** For `unknown`, the earliest time a different answer is possible, if known */
364
+ readonly retryAfter?: IsoTimestamp;
365
+ }
266
366
  /**
267
367
  * Contract every payment rail implements. Implementations must be
268
368
  * non-custodial: they orchestrate an external payment protocol and never hold
@@ -296,6 +396,124 @@ interface PaymentProvider {
296
396
  * returned result; the pipeline records any throw as settlement-uncertain.
297
397
  */
298
398
  settle(context: PaymentSettlementContext): Promise<PaymentResult>;
399
+ /**
400
+ * Read chain evidence for an attempt with an unknown outcome. Implementations
401
+ * must not write, broadcast or call a facilitator. Providers without this
402
+ * hook require manual resolution. Experimental: may change in a minor release.
403
+ */
404
+ reconcile?(context: PaymentReconciliationContext): Promise<PaymentReconciliationResult>;
405
+ health(): Promise<AdapterHealth>;
406
+ }
407
+
408
+ /**
409
+ * Canonical authorization model. FROZEN CONTRACT.
410
+ *
411
+ * Payment proves that funds moved; authorization proves that the human behind
412
+ * the agent approved this exact purchase. A valid authorization gates
413
+ * settlement but never unlocks a paid resource on its own and never moves
414
+ * money, so a resource that requires one still needs a payment proof.
415
+ *
416
+ * Core decides that a resource requires authorization and when the pipeline
417
+ * checks it. Authorization providers decide how a submission is parsed,
418
+ * verified and bound to the purchase. No AP2, SD-JWT or JWT type may appear in
419
+ * this file.
420
+ */
421
+
422
+ /**
423
+ * Opaque authorization proof supplied by the buyer's client. Over HTTP it
424
+ * arrives as base64url JSON in the `Agent-Authorization` header; over MCP and
425
+ * A2A it is the same `{ method, payload }` object in the reserved
426
+ * `_authorization` input field.
427
+ *
428
+ * `payload` is kept byte for byte from the wire. It may hold signed or
429
+ * encoding-sensitive provider data, so transport adapters must not normalize
430
+ * it.
431
+ */
432
+ interface AuthorizationSubmission {
433
+ readonly method: AuthorizationMethodName;
434
+ readonly payload: string;
435
+ }
436
+ /**
437
+ * What a buyer must present, advertised with the payment challenge so a client
438
+ * learns before it pays that a payment proof alone will not do. The gateway
439
+ * never issues the authorization; it names the method, the spec version it
440
+ * verifies against and the payload profile it expects.
441
+ */
442
+ interface AuthorizationRequirement {
443
+ readonly method: AuthorizationMethodName;
444
+ readonly version: string;
445
+ readonly profile?: string;
446
+ }
447
+ /**
448
+ * Safe audit identity of an authorization, fit for a receipt. `reference` is a
449
+ * digest, because a receipt outlives its request and a stored proof would be a
450
+ * spendable secret at rest.
451
+ */
452
+ interface AuthorizationRecord {
453
+ readonly method: AuthorizationMethodName;
454
+ readonly reference: string;
455
+ /** Safe audit summary only. Never the proof, its disclosures, or PII */
456
+ readonly metadata?: Readonly<Record<string, unknown>>;
457
+ }
458
+ /**
459
+ * A verified, reserved authorization. `reservationId` is the handle the
460
+ * pipeline consumes, releases or marks uncertain once the payment resolves. It
461
+ * stays out of `AuthorizationRecord` because a handle is not an audit fact.
462
+ */
463
+ interface AuthorizationVerification extends AuthorizationRecord {
464
+ readonly status: 'verified';
465
+ readonly reservationId: string;
466
+ }
467
+ /** Input to {@link AuthorizationProvider.verifyAndReserve} */
468
+ interface AuthorizationVerificationContext {
469
+ readonly requestId: string;
470
+ readonly resourceId: string;
471
+ /**
472
+ * The validated resource input with reserved fields stripped: the same value
473
+ * the merchant backend is called with. A provider that binds a proof to the
474
+ * request hashes it, so it excludes `_payment`, `_authorization`, the request
475
+ * id and transport metadata.
476
+ */
477
+ readonly input: unknown;
478
+ readonly submission: AuthorizationSubmission;
479
+ /** The resolved price and destination the proof must match */
480
+ readonly requirement: PaymentRequirement;
481
+ }
482
+ /** Input to {@link AuthorizationProvider.consume}, `release` and `markUncertain` */
483
+ interface AuthorizationFinalizeContext {
484
+ readonly requestId: string;
485
+ readonly resourceId: string;
486
+ }
487
+ /**
488
+ * Contract every authorization method implements.
489
+ *
490
+ * The lifecycle straddles settlement: a proof is reserved before funds move, so
491
+ * a replay cannot race it, and its fate is known only afterwards. A reservation
492
+ * is released only after a failure that provably moved no money. Anything
493
+ * ambiguous is marked uncertain, because a proof handed back after a settlement
494
+ * that may have landed can be spent twice.
495
+ */
496
+ interface AuthorizationProvider {
497
+ readonly name: AuthorizationMethodName;
498
+ readonly descriptor: AdapterDescriptor;
499
+ /** What a buyer must present, advertised with the payment challenge */
500
+ readonly requirement: AuthorizationRequirement;
501
+ /**
502
+ * Verify a submission against the resolved purchase and atomically reserve it
503
+ * against reuse. Throws a `CommerceError` with an `AUTHORIZATION_*` code,
504
+ * never a payment code; a verifier or store outage is
505
+ * `AUTHORIZATION_PROVIDER_UNAVAILABLE`, not the buyer's fault.
506
+ */
507
+ verifyAndReserve(context: AuthorizationVerificationContext): Promise<AuthorizationVerification>;
508
+ /** Mark a reservation permanently spent. Called after settlement succeeds */
509
+ consume(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
510
+ /** Return a reservation to unused. Only for failures that moved no funds */
511
+ release(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
512
+ /**
513
+ * Settlement threw, so whether funds moved is unknown: neither spend the
514
+ * reservation nor hand it back, and flag it for an operator
515
+ */
516
+ markUncertain(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
299
517
  health(): Promise<AdapterHealth>;
300
518
  }
301
519
 
@@ -328,5 +546,5 @@ interface IdGenerator {
328
546
  }
329
547
  declare const systemClock: Clock;
330
548
 
331
- export { NOOP_LOGGER as N, DEFAULT_BACKEND_TIMEOUT_MS as i, PAYMENT_METHOD_NAMES as j, PROTOCOL_NAMES as k, systemClock as t };
332
- export type { AdapterDescriptor as A, BackendHandler as B, Clock as C, DecimalAmount as D, IsoTimestamp as I, JsonSchema as J, Logger as L, PaymentMethodName as P, ResourceRegistry as R, CommerceResource as a, PaymentSubmission as b, AdapterHealth as c, PaymentProvider as d, IdGenerator as e, AdapterHealthComponent as f, AuthorizationMethodName as g, BackendMethod as h, PaymentChallenge as l, PaymentContext as m, PaymentRequirement as n, PaymentResult as o, PaymentSettlementContext as p, PaymentVerificationContext as q, Pricing as r, ProtocolName as s };
549
+ export { RECONCILIATION_METADATA_KEY as M, NOOP_LOGGER as N, systemClock as O, DEFAULT_BACKEND_TIMEOUT_MS as t, PAYMENT_METHOD_NAMES as u, PROTOCOL_NAMES as v };
550
+ export type { AuthorizationProvider as A, BackendHandler as B, Clock as C, DecimalAmount as D, PaymentRequirement as E, PaymentResult as F, PaymentSettlementContext as G, PaymentVerificationContext as H, IsoTimestamp as I, JsonSchema as J, Pricing as K, Logger as L, PaymentMethodName as P, ResourceRegistry as R, AuthorizationRequirement as a, CommerceResource as b, PaymentSubmission as c, AuthorizationSubmission as d, ProtocolName as e, AuthorizationRecord as f, PaymentAttempt as g, CommerceReceipt as h, PaymentAttemptResolution as i, AdapterDescriptor as j, AdapterHealth as k, PaymentProvider as l, IdGenerator as m, AdapterHealthComponent as n, AuthorizationFinalizeContext as o, AuthorizationMethodName as p, AuthorizationVerification as q, AuthorizationVerificationContext as r, BackendMethod as s, PaymentChallenge as w, PaymentContext as x, PaymentReconciliationContext as y, PaymentReconciliationResult as z };
@@ -0,0 +1,48 @@
1
+ import { LOCATOR_VERSION, computeSvmReplayKey } from './chunk-GA3O2A7R.js';
2
+ import { isRecord } from './chunk-2CJNA7MS.js';
3
+ import { getAddressEncoder, getProgramDerivedAddress, address, getCompiledTransactionMessageDecoder } from '@solana/kit';
4
+ import { decodeTransactionFromPayload, transactionMessageHash } from '@x402/svm';
5
+
6
+ var MAX_TRANSACTION_BASE64 = 1644;
7
+ var ASSOCIATED_TOKEN_PROGRAM = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL";
8
+ async function associatedTokenAccount(owner, mint, tokenProgram) {
9
+ const encoder = getAddressEncoder();
10
+ const [account] = await getProgramDerivedAddress({
11
+ programAddress: address(ASSOCIATED_TOKEN_PROGRAM),
12
+ seeds: [owner, tokenProgram, mint].map((key) => encoder.encode(address(key)))
13
+ });
14
+ return account;
15
+ }
16
+ function inspectSvmPayload(payload, network) {
17
+ if (!isRecord(payload)) return "invalid_exact_svm_payload_transaction";
18
+ const transaction = payload["transaction"];
19
+ if (typeof transaction !== "string" || transaction.length > MAX_TRANSACTION_BASE64) {
20
+ return "invalid_exact_svm_payload_transaction";
21
+ }
22
+ let messageHash;
23
+ let recentBlockhash;
24
+ try {
25
+ const decoded = decodeTransactionFromPayload({ transaction });
26
+ messageHash = transactionMessageHash(decoded);
27
+ recentBlockhash = getCompiledTransactionMessageDecoder().decode(
28
+ decoded.messageBytes
29
+ ).lifetimeToken;
30
+ } catch {
31
+ return "invalid_exact_svm_payload_transaction_could_not_be_decoded";
32
+ }
33
+ return {
34
+ replayKey: computeSvmReplayKey({ network, messageHash }),
35
+ locator: { v: LOCATOR_VERSION, network, messageHash, recentBlockhash }
36
+ };
37
+ }
38
+ function messageHashOf(transaction) {
39
+ try {
40
+ return transactionMessageHash(decodeTransactionFromPayload({ transaction }));
41
+ } catch {
42
+ return void 0;
43
+ }
44
+ }
45
+
46
+ export { associatedTokenAccount, inspectSvmPayload, messageHashOf };
47
+ //# sourceMappingURL=svm-KNC3PHMS.js.map
48
+ //# sourceMappingURL=svm-KNC3PHMS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/payments/x402/svm.ts"],"names":[],"mappings":";;;;;AAsBA,IAAM,sBAAA,GAAyB,IAAA;AAE/B,IAAM,wBAAA,GAA2B,8CAAA;AAMjC,eAAsB,sBAAA,CACpB,KAAA,EACA,IAAA,EACA,YAAA,EACiB;AACjB,EAAA,MAAM,UAAU,iBAAA,EAAkB;AAClC,EAAA,MAAM,CAAC,OAAO,CAAA,GAAI,MAAM,wBAAA,CAAyB;AAAA,IAC/C,cAAA,EAAgB,QAAQ,wBAAwB,CAAA;AAAA,IAChD,KAAA,EAAO,CAAC,KAAA,EAAO,YAAA,EAAc,IAAI,CAAA,CAAE,GAAA,CAAI,CAAC,GAAA,KAAQ,OAAA,CAAQ,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAC,CAAC;AAAA,GAC7E,CAAA;AACD,EAAA,OAAO,OAAA;AACT;AAOO,SAAS,iBAAA,CACd,SACA,OAAA,EAC8F;AAC9F,EAAA,IAAI,CAAC,QAAA,CAAS,OAAO,CAAA,EAAG,OAAO,uCAAA;AAC/B,EAAA,MAAM,WAAA,GAAc,QAAQ,aAAa,CAAA;AACzC,EAAA,IAAI,OAAO,WAAA,KAAgB,QAAA,IAAY,WAAA,CAAY,SAAS,sBAAA,EAAwB;AAClF,IAAA,OAAO,uCAAA;AAAA,EACT;AACA,EAAA,IAAI,WAAA;AACJ,EAAA,IAAI,eAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,GAAU,4BAAA,CAA6B,EAAE,WAAA,EAAa,CAAA;AAC5D,IAAA,WAAA,GAAc,uBAAuB,OAAO,CAAA;AAC5C,IAAA,eAAA,GAAkB,sCAAqC,CAAE,MAAA;AAAA,MACvD,OAAA,CAAQ;AAAA,KACV,CAAE,aAAA;AAAA,EACJ,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,4DAAA;AAAA,EACT;AACA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,mBAAA,CAAoB,EAAE,OAAA,EAAS,aAAa,CAAA;AAAA,IACvD,SAAS,EAAE,CAAA,EAAG,eAAA,EAAiB,OAAA,EAAS,aAAa,eAAA;AAAgB,GACvE;AACF;AAMO,SAAS,cAAc,WAAA,EAAyC;AACrE,EAAA,IAAI;AACF,IAAA,OAAO,sBAAA,CAAuB,4BAAA,CAA6B,EAAE,WAAA,EAAa,CAAC,CAAA;AAAA,EAC7E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"svm-KNC3PHMS.js","sourcesContent":["/**\n * Solana `exact` payload inspection with bounded decoding, replay identity and\n * reconciliation coordinates. The provider loads this module, including its\n * `@x402/svm` and `@solana/kit` imports, when a Solana offer is configured.\n *\n * The facilitator checks the transaction itself: the fee payer, signatures,\n * instruction layout, mint, recipient token account and amount, and a\n * simulation. Its smart-wallet path accepts layouts the gateway could not\n * parse, so the gateway does not read the transfer.\n */\nimport {\n address,\n getAddressEncoder,\n getCompiledTransactionMessageDecoder,\n getProgramDerivedAddress,\n} from '@solana/kit';\nimport { decodeTransactionFromPayload, transactionMessageHash } from '@x402/svm';\nimport { isRecord } from '../../core/is-record';\nimport { LOCATOR_VERSION } from './locator';\nimport { computeSvmReplayKey } from './replay-key';\n\n// A Solana transaction fits a 1232-byte packet, which is 1644 base64 characters\nconst MAX_TRANSACTION_BASE64 = 1644;\n\nconst ASSOCIATED_TOKEN_PROGRAM = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n\n/**\n * The associated token account of `owner` for `mint`, where the SDK client\n * sends a Solana `exact` payment. Its transaction cannot create the account.\n */\nexport async function associatedTokenAccount(\n owner: string,\n mint: string,\n tokenProgram: string,\n): Promise<string> {\n const encoder = getAddressEncoder();\n const [account] = await getProgramDerivedAddress({\n programAddress: address(ASSOCIATED_TOKEN_PROGRAM),\n seeds: [owner, tokenProgram, mint].map((key) => encoder.encode(address(key))),\n });\n return account;\n}\n\n/**\n * Returns the Solana `exact` replay key and locator, or an SDK refusal reason\n * for a missing, oversized or undecodable transaction. The provider adds the\n * payer from the facilitator's verdict when a usable address is available.\n */\nexport function inspectSvmPayload(\n payload: unknown,\n network: string,\n): { readonly replayKey: string; readonly locator: Readonly<Record<string, unknown>> } | string {\n if (!isRecord(payload)) return 'invalid_exact_svm_payload_transaction';\n const transaction = payload['transaction'];\n if (typeof transaction !== 'string' || transaction.length > MAX_TRANSACTION_BASE64) {\n return 'invalid_exact_svm_payload_transaction';\n }\n let messageHash: string;\n let recentBlockhash: string;\n try {\n const decoded = decodeTransactionFromPayload({ transaction });\n messageHash = transactionMessageHash(decoded);\n recentBlockhash = getCompiledTransactionMessageDecoder().decode(\n decoded.messageBytes,\n ).lifetimeToken;\n } catch {\n return 'invalid_exact_svm_payload_transaction_could_not_be_decoded';\n }\n return {\n replayKey: computeSvmReplayKey({ network, messageHash }),\n locator: { v: LOCATOR_VERSION, network, messageHash, recentBlockhash },\n };\n}\n\n/**\n * Returns the message hash of base64 transaction bytes using the same decoder\n * as payment inspection, or undefined if decoding or hashing fails\n */\nexport function messageHashOf(transaction: string): string | undefined {\n try {\n return transactionMessageHash(decodeTransactionFromPayload({ transaction }));\n } catch {\n return undefined;\n }\n}\n"]}
package/dist/x402.js CHANGED
@@ -1,8 +1,8 @@
1
- import { chainIdFromCaip2 } from './chunk-WUIAUAA7.js';
2
- export { createX402PaymentProvider, createX402PaymentProvider as x402 } from './chunk-WUIAUAA7.js';
3
- export { SUPPORTED_NETWORK_IDS } from './chunk-4OEXK3YG.js';
4
- import { CommerceError } from './chunk-AITMDXKW.js';
5
- import './chunk-KA2AX5FH.js';
1
+ import { chainIdFromCaip2 } from './chunk-FKQK5XZA.js';
2
+ export { createX402PaymentProvider, createX402PaymentProvider as x402 } from './chunk-FKQK5XZA.js';
3
+ export { SUPPORTED_NETWORK_IDS } from './chunk-4K7FIBJM.js';
4
+ import { CommerceError } from './chunk-3OTCFFFT.js';
5
+ import './chunk-GA3O2A7R.js';
6
6
  import './chunk-2CJNA7MS.js';
7
7
  import { PaymentRequirementsV2Schema } from '@x402/core/schemas';
8
8
  import { getAddress, toHex } from 'viem';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devlab.group/agent-commerce",
3
- "version": "2.4.0",
3
+ "version": "2.5.0",
4
4
  "description": "Open-source, self-hosted, non-custodial commerce and payment orchestration gateway for AI agents.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -1,115 +0,0 @@
1
- import { g as AuthorizationMethodName, A as AdapterDescriptor, n as PaymentRequirement, c as AdapterHealth } from './runtime-Cl_BLVZV.js';
2
-
3
- /**
4
- * Canonical authorization model. FROZEN CONTRACT.
5
- *
6
- * Payment proves that funds moved; authorization proves that the human behind
7
- * the agent approved this exact purchase. A valid authorization gates
8
- * settlement but never unlocks a paid resource on its own and never moves
9
- * money, so a resource that requires one still needs a payment proof.
10
- *
11
- * Core decides that a resource requires authorization and when the pipeline
12
- * checks it. Authorization providers decide how a submission is parsed,
13
- * verified and bound to the purchase. No AP2, SD-JWT or JWT type may appear in
14
- * this file.
15
- */
16
-
17
- /**
18
- * Opaque authorization proof supplied by the buyer's client. Over HTTP it
19
- * arrives as base64url JSON in the `Agent-Authorization` header; over MCP and
20
- * A2A it is the same `{ method, payload }` object in the reserved
21
- * `_authorization` input field.
22
- *
23
- * `payload` is kept byte for byte from the wire. It may hold signed or
24
- * encoding-sensitive provider data, so transport adapters must not normalize
25
- * it.
26
- */
27
- interface AuthorizationSubmission {
28
- readonly method: AuthorizationMethodName;
29
- readonly payload: string;
30
- }
31
- /**
32
- * What a buyer must present, advertised with the payment challenge so a client
33
- * learns before it pays that a payment proof alone will not do. The gateway
34
- * never issues the authorization; it names the method, the spec version it
35
- * verifies against and the payload profile it expects.
36
- */
37
- interface AuthorizationRequirement {
38
- readonly method: AuthorizationMethodName;
39
- readonly version: string;
40
- readonly profile?: string;
41
- }
42
- /**
43
- * Safe audit identity of an authorization, fit for a receipt. `reference` is a
44
- * digest, because a receipt outlives its request and a stored proof would be a
45
- * spendable secret at rest.
46
- */
47
- interface AuthorizationRecord {
48
- readonly method: AuthorizationMethodName;
49
- readonly reference: string;
50
- /** Safe audit summary only. Never the proof, its disclosures, or PII */
51
- readonly metadata?: Readonly<Record<string, unknown>>;
52
- }
53
- /**
54
- * A verified, reserved authorization. `reservationId` is the handle the
55
- * pipeline consumes, releases or marks uncertain once the payment resolves. It
56
- * stays out of `AuthorizationRecord` because a handle is not an audit fact.
57
- */
58
- interface AuthorizationVerification extends AuthorizationRecord {
59
- readonly status: 'verified';
60
- readonly reservationId: string;
61
- }
62
- /** Input to {@link AuthorizationProvider.verifyAndReserve} */
63
- interface AuthorizationVerificationContext {
64
- readonly requestId: string;
65
- readonly resourceId: string;
66
- /**
67
- * The validated resource input with reserved fields stripped: the same value
68
- * the merchant backend is called with. A provider that binds a proof to the
69
- * request hashes it, so it excludes `_payment`, `_authorization`, the request
70
- * id and transport metadata.
71
- */
72
- readonly input: unknown;
73
- readonly submission: AuthorizationSubmission;
74
- /** The resolved price and destination the proof must match */
75
- readonly requirement: PaymentRequirement;
76
- }
77
- /** Input to {@link AuthorizationProvider.consume}, `release` and `markUncertain` */
78
- interface AuthorizationFinalizeContext {
79
- readonly requestId: string;
80
- readonly resourceId: string;
81
- }
82
- /**
83
- * Contract every authorization method implements.
84
- *
85
- * The lifecycle straddles settlement: a proof is reserved before funds move, so
86
- * a replay cannot race it, and its fate is known only afterwards. A reservation
87
- * is released only after a failure that provably moved no money. Anything
88
- * ambiguous is marked uncertain, because a proof handed back after a settlement
89
- * that may have landed can be spent twice.
90
- */
91
- interface AuthorizationProvider {
92
- readonly name: AuthorizationMethodName;
93
- readonly descriptor: AdapterDescriptor;
94
- /** What a buyer must present, advertised with the payment challenge */
95
- readonly requirement: AuthorizationRequirement;
96
- /**
97
- * Verify a submission against the resolved purchase and atomically reserve it
98
- * against reuse. Throws a `CommerceError` with an `AUTHORIZATION_*` code,
99
- * never a payment code; a verifier or store outage is
100
- * `AUTHORIZATION_PROVIDER_UNAVAILABLE`, not the buyer's fault.
101
- */
102
- verifyAndReserve(context: AuthorizationVerificationContext): Promise<AuthorizationVerification>;
103
- /** Mark a reservation permanently spent. Called after settlement succeeds */
104
- consume(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
105
- /** Return a reservation to unused. Only for failures that moved no funds */
106
- release(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
107
- /**
108
- * Settlement threw, so whether funds moved is unknown: neither spend the
109
- * reservation nor hand it back, and flag it for an operator
110
- */
111
- markUncertain(reservationId: string, context: AuthorizationFinalizeContext): Promise<void>;
112
- health(): Promise<AdapterHealth>;
113
- }
114
-
115
- export type { AuthorizationProvider as A, AuthorizationRequirement as a, AuthorizationSubmission as b, AuthorizationFinalizeContext as c, AuthorizationRecord as d, AuthorizationVerification as e, AuthorizationVerificationContext as f };
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/payments/x402/networks.ts","../src/core/execution/settlement-order.ts","../src/payments/x402/addresses.ts","../src/payments/x402/local-chain/accounts.ts","../src/payments/x402/dev-key-guard.ts","../src/payments/x402/guardrails.ts","../src/payments/x402/options.ts","../src/payments/x402/payment-flow.ts"],"names":["invalid"],"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AAY,EAAE,YAAA,EAAc,KAAA,CAAM,YAAA,EAAa,GAAI,EAAC;AAAA,IAC/E,eAAe,KAAA,CAAM,aAAA;AAAA,IACrB,mBAAA,EAAqB;AAAA,GACvB;AACF;;;AC9LO,IAAM,kBAAA,GAAqB,CAAC,eAAA,EAAiB,SAAS;AAItD,IAAM,yBAAA,GAA6C","file":"chunk-4OEXK3YG.js","sourcesContent":["/**\n * Network profiles: family, display name, environment, EVM chain ID and\n * default stablecoin. Config load rejects unknown IDs; parsing an EVM chain\n * ID cannot establish whether it is mainnet. Merchants must declare custom\n * EVM networks under `payments.x402.networks`; built-ins cannot be redeclared.\n *\n * Profiles copy SDK asset defaults to keep config load and the CLI SDK-free.\n * Tests compare each profile with the pinned SDK tables.\n *\n * The local Anvil chain has a profile of its own, `eip155:31337` (Anvil's\n * default chain id), so the network alone tells a local deployment from a\n * public one. Local health checks still require an Anvil response, because an\n * RPC endpoint can report any chain id.\n */\nimport { CommerceError } from '../../core';\n\n/** Chain id of the local Anvil dev chain, Anvil's default */\nexport const LOCAL_CHAIN_ID = 31337;\n\nexport type X402NetworkFamily = 'evm' | 'svm' | 'near';\n\nexport type NetworkKind = 'testnet' | 'mainnet';\n\n/** An EVM network the x402 provider can settle on */\nexport interface NetworkProfile {\n /** CAIP-2 identifier, e.g. `eip155:84532` */\n readonly id: string;\n /** Signed into the buyer's EIP-712 domain */\n readonly chainId: number;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** The local Anvil dev chain, where the in-process facilitator runs */\n readonly local?: boolean;\n /**\n * Default USDC deployment and EIP-712 domain. EVM offers may name another\n * token; the local chain has no default and requires explicit token metadata.\n *\n * `name` is the signed EIP-712 domain name, not the symbol, and deployments\n * differ: `\"USDC\"` on Base Sepolia, `\"USD Coin\"` on Base.\n */\n readonly canonicalAsset?: {\n readonly symbol: string;\n readonly address: string;\n readonly name: string;\n readonly version: string;\n readonly decimals: number;\n };\n}\n\ninterface NonEvmNetwork<F extends X402NetworkFamily> {\n readonly family: F;\n readonly id: string;\n readonly displayName: string;\n readonly kind: NetworkKind;\n /** Solana mint or NEAR NEP-141 contract account, with no EIP-712 domain */\n readonly canonicalAsset: {\n readonly symbol: string;\n readonly address: string;\n readonly decimals: number;\n };\n}\n\nexport type X402Network =\n | (NetworkProfile & { readonly family: 'evm' })\n | NonEvmNetwork<'svm'>\n | NonEvmNetwork<'near'>;\n\n/** A merchant-declared EVM network, from `payments.x402.networks` */\nexport interface CustomNetworkDeclaration {\n readonly kind: NetworkKind;\n readonly displayName: string;\n}\n\nexport type CustomNetworks = Readonly<Record<string, CustomNetworkDeclaration>>;\n\nconst usdc = (address: string, name: string) =>\n ({ symbol: 'USDC', address, name, version: '2', decimals: 6 }) as const;\n\nconst PROFILES: readonly X402Network[] = [\n {\n family: 'evm',\n id: `eip155:${LOCAL_CHAIN_ID}`,\n chainId: LOCAL_CHAIN_ID,\n displayName: 'Local Anvil',\n kind: 'testnet',\n local: true,\n },\n {\n family: 'evm',\n id: 'eip155:84532',\n chainId: 84532,\n displayName: 'Base Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x036CbD53842c5426634e7929541eC2318f3dCF7e', 'USDC'),\n },\n {\n family: 'evm',\n id: 'eip155:8453',\n chainId: 8453,\n displayName: 'Base',\n kind: 'mainnet',\n canonicalAsset: usdc('0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:1',\n chainId: 1,\n displayName: 'Ethereum',\n kind: 'mainnet',\n canonicalAsset: usdc('0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:137',\n chainId: 137,\n displayName: 'Polygon',\n kind: 'mainnet',\n canonicalAsset: usdc('0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:42161',\n chainId: 42161,\n displayName: 'Arbitrum One',\n kind: 'mainnet',\n canonicalAsset: usdc('0xaf88d065e77c8cC2239327C5EDb3A432268e5831', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:421614',\n chainId: 421614,\n displayName: 'Arbitrum Sepolia',\n kind: 'testnet',\n canonicalAsset: usdc('0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d', 'USD Coin'),\n },\n {\n family: 'evm',\n id: 'eip155:43114',\n chainId: 43114,\n displayName: 'Avalanche C-Chain',\n kind: 'mainnet',\n canonicalAsset: usdc('0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', 'USD Coin'),\n },\n {\n family: 'svm',\n id: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',\n displayName: 'Solana',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n decimals: 6,\n },\n },\n {\n family: 'svm',\n id: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',\n displayName: 'Solana Devnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',\n decimals: 6,\n },\n },\n // NEAR's USDC contracts are implicit accounts: 64 lowercase hex characters\n {\n family: 'near',\n id: 'near:mainnet',\n displayName: 'NEAR',\n kind: 'mainnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1',\n decimals: 6,\n },\n },\n {\n family: 'near',\n id: 'near:testnet',\n displayName: 'NEAR Testnet',\n kind: 'testnet',\n canonicalAsset: {\n symbol: 'USDC',\n address: '3e2210e1184b45b64c8a434c0a7e7b23cc04ea7eb7a6c3c32520d03d4afcb8af',\n decimals: 6,\n },\n },\n];\n\nconst BY_ID = new Map(PROFILES.map((profile) => [profile.id, profile]));\n\n/** Built-in networks of every family, for tests and diagnostics */\nexport const BUILT_IN_NETWORKS: readonly X402Network[] = PROFILES;\n\n/** The built-in EVM networks the x402 provider settles on without a declaration */\nexport const SUPPORTED_NETWORK_IDS: readonly string[] = PROFILES.filter(\n (p) => p.family === 'evm',\n).map((p) => p.id);\n\n// A chain id viem and EIP-712 can carry as a JS number\nconst EVM_NETWORK_ID = /^eip155:([1-9]\\d{0,15})$/;\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/** Built-in EVM profile for callers using the original network interface */\nexport function findNetworkProfile(id: string): NetworkProfile | undefined {\n const profile = BY_ID.get(id);\n return profile?.family === 'evm' ? profile : undefined;\n}\n\n/** A built-in network of any family, or a declared custom EVM network */\nexport function findX402Network(id: string, custom?: CustomNetworks): X402Network | undefined {\n const builtIn = BY_ID.get(id);\n if (builtIn) return builtIn;\n const declared = custom?.[id];\n const chainId = Number(EVM_NETWORK_ID.exec(id)?.[1]);\n if (!declared || !Number.isSafeInteger(chainId)) return undefined;\n return {\n family: 'evm',\n id,\n chainId,\n displayName: declared.displayName,\n kind: declared.kind,\n };\n}\n\nexport function requireX402Network(id: string, path: string, custom?: CustomNetworks): X402Network {\n const network = findX402Network(id, custom);\n if (!network) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `${path}: \"${id}\" is not a known network. Built-in CAIP-2 identifiers: ${PROFILES.map((p) => p.id).join(', ')}. Declare another EVM network under payments.x402.networks with its kind and displayName.`,\n { details: { path, network: id } },\n );\n }\n return network;\n}\n\n/**\n * Allows only new `eip155` networks in `payments.x402.networks`. Redeclaring\n * built-ins could relabel mainnet as testnet; Solana and NEAR IDs are SDK-fixed.\n */\nexport function validateCustomNetworks(custom: CustomNetworks, path: string): void {\n for (const id of Object.keys(custom)) {\n const at = `${path}.${id}`;\n if (BY_ID.has(id)) {\n throw invalid(\n `${at}: \"${id}\" is a built-in network and cannot be redeclared; remove this entry`,\n at,\n );\n }\n if (!findX402Network(id, custom)) {\n throw invalid(\n `${at}: \"${id}\" is not an EVM CAIP-2 identifier (\"eip155:\" followed by a positive chain id below 2^53). Only EVM networks can be declared.`,\n at,\n );\n }\n }\n}\n\n/** What a deployment is: the local dev chain, or a public testnet or mainnet */\nexport type DeploymentMode = 'local' | 'testnet' | 'mainnet';\n\nexport function resolveDeploymentMode(profile: {\n readonly kind: NetworkKind;\n readonly local?: boolean;\n}): DeploymentMode {\n return profile.local ? 'local' : profile.kind;\n}\n\n// The banner an operator must not miss. Printed for mainnet only\nconst LIVE_MAINNET_BANNER = 'LIVE MAINNET MODE - REAL FUNDS';\n\nexport function describeDeploymentMode(mode: DeploymentMode): string {\n return mode === 'mainnet' ? LIVE_MAINNET_BANNER : mode.toUpperCase();\n}\n","/**\n * Set on a payment requirement to run the backend before settlement.\n * The pipeline settles first unless this metadata value is `true`.\n */\nexport const SETTLE_AFTER_BACKEND_METADATA_KEY = 'settleAfterBackend';\n\n/**\n * Set to `true` when the rail permits presenting an authorization again after\n * its attempt was rejected, which settled nothing; the chain still spends each\n * nonce once. The pipeline lets retries reclaim the rejected attempt;\n * otherwise, it refuses them as replays.\n */\nexport const REUSE_REJECTED_AUTHORIZATION_METADATA_KEY = 'reuseRejectedAuthorization';\n","/**\n * SDK-free address checks for config load and the CLI. EVM addresses compare\n * without case; Solana keys and NEAR account IDs compare exactly.\n */\nimport type { X402Network } from './networks';\n\n// `0x` + 40 hex characters. Config load cannot check the EIP-55 checksum,\n// which needs keccak-256; the x402 and MPP providers refuse a mixed-case\n// address whose checksum is wrong when they start.\nconst EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst EVM_ZERO = /^0x0{40}$/i;\n\n/** `0x` followed by 40 hex characters, in any case */\nexport const isEvmAddress = (value: unknown): value is `0x${string}` =>\n typeof value === 'string' && EVM_ADDRESS.test(value);\n\n/** The EVM zero address, in any case */\nexport const isEvmZeroAddress = (value: string): boolean => EVM_ZERO.test(value);\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n// A 32-byte key is 32 to 44 base58 characters\nconst SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n// The all-zero key, which is the System Program and owns nothing recoverable\nconst SOLANA_ZERO = '11111111111111111111111111111111';\nconst EVM_TRANSACTION_HASH = /^0x[0-9a-fA-F]{64}$/;\n// A 64-byte Ed25519 signature is at most 88 base58 characters\nconst SOLANA_SIGNATURE = /^[1-9A-HJ-NP-Za-km-z]{64,88}$/;\n\n// nearcore's account ID rule: 2 to 64 characters, lowercase alphanumeric runs\n// joined by single \"-\", \"_\" or \".\"; implicit accounts are 64 hex characters\nconst NEAR_ACCOUNT_ID = /^(([a-z\\d]+[-_])*[a-z\\d]+\\.)*([a-z\\d]+[-_])*[a-z\\d]+$/;\n// A transaction hash: 32 bytes in base58\nconst NEAR_TRANSACTION_HASH = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;\n\n/**\n * Returns the family's wire address or `undefined`. NEAR uses named or\n * implicit account IDs; a `.near` suffix does not identify the network.\n */\nexport function normalizeAddress(network: X402Network, value: string): string | undefined {\n switch (network.family) {\n case 'evm':\n return isEvmAddress(value) ? value : undefined;\n case 'svm':\n return SOLANA_ADDRESS.test(value) && base58ByteLength(value) === 32 ? value : undefined;\n case 'near':\n return value.length >= 2 && value.length <= 64 && NEAR_ACCOUNT_ID.test(value)\n ? value\n : undefined;\n }\n}\n\n/**\n * An address funds cannot be recovered from: the zero address of its family.\n * NEAR has no zero account.\n */\nexport function isBurnAddress(network: X402Network, wireAddress: string): boolean {\n switch (network.family) {\n case 'evm':\n return isEvmZeroAddress(wireAddress);\n case 'svm':\n return wireAddress === SOLANA_ZERO;\n case 'near':\n return false;\n }\n}\n\n/** Compare EVM addresses case-insensitively, Solana keys and NEAR account IDs exactly */\nexport function sameAddress(network: X402Network, a: string, b: string): boolean {\n return network.family === 'evm' ? a.toLowerCase() === b.toLowerCase() : a === b;\n}\n\n/**\n * A settlement reference in its family's form: an EVM transaction hash, a\n * Solana transaction signature or a NEAR transaction hash\n */\nexport function isTransactionReference(network: X402Network, value: string): boolean {\n switch (network.family) {\n case 'evm':\n return EVM_TRANSACTION_HASH.test(value);\n case 'svm':\n return SOLANA_SIGNATURE.test(value) && base58ByteLength(value) === 64;\n case 'near':\n return NEAR_TRANSACTION_HASH.test(value) && base58ByteLength(value) === 32;\n }\n}\n\nfunction base58ByteLength(value: string): number {\n let n = 0n;\n for (const char of value) n = n * 58n + BigInt(BASE58_ALPHABET.indexOf(char));\n // Each leading '1' encodes one leading zero byte\n const leadingZeros = value.length - value.replace(/^1+/, '').length;\n return leadingZeros + (n === 0n ? 0 : Math.ceil(n.toString(16).length / 2));\n}\n","/**\n * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY - DO NOT FUND. The keys come from Foundry's public\n * default mnemonic (\"test test ... junk\"), so value sent to these addresses on\n * a real network can be taken by anyone.\n *\n * Index layout on the local demo chain:\n * 0 - deployer and local facilitator signer (pays gas, broadcasts settlement)\n * 1 - merchant settlement destination (`payTo`)\n * 2 - buyer (signs EIP-3009 authorizations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** A fixed-length tuple, so indexing by the layout above is typed */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Label printed wherever a dev key appears in output, logs or manifests */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n","/**\n * Rejects well-known Anvil keys and payment destinations when the RPC host\n * does not look local or private. Their private keys are published, so anyone\n * can spend what such an address receives on a public chain.\n *\n * The check uses the RPC hostname because the local chain shares Base\n * Sepolia's chain id. Both guards run at provider construction.\n */\nimport { CommerceError } from '../../core';\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from './local-chain/accounts';\n\nconst WELL_KNOWN_DEV_KEYS: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.privateKey.toLowerCase()),\n);\n\nconst WELL_KNOWN_DEV_ADDRESSES: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.address.toLowerCase()),\n);\n\n// `0x` plus 64 hex characters, the only shape `privateKeyToAccount` accepts\nconst PRIVATE_KEY_SHAPE = /^0x[0-9a-fA-F]{64}$/;\n\nexport function isWellKnownDevKey(privateKey: string): boolean {\n return WELL_KNOWN_DEV_KEYS.has(privateKey.toLowerCase());\n}\n\nexport function isWellKnownDevAddress(address: string): boolean {\n return WELL_KNOWN_DEV_ADDRESSES.has(address.toLowerCase());\n}\n\n/**\n * True for loopback addresses, RFC 1918 private ranges, and bare (dot-free)\n * hostnames, such as the compose service name \"anvil\".\n *\n * Bare hostnames are treated as local without resolving them. Operators must\n * point them at a private chain.\n */\nexport function isLikelyLocalOrPrivateHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (h === 'localhost' || h === '::1') return true;\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (!h.includes('.') && !h.includes(':')) return true; // bare hostname\n return false;\n}\n\nfunction parseHostnameOrThrow(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).hostname;\n } catch (cause) {\n // Never the URL itself: RPC providers commonly put an API key in the path,\n // and this message reaches startup output and CI logs\n throw new CommerceError('CONFIG_INVALID', 'x402 provider: rpcUrl is not a valid URL', {\n cause,\n });\n }\n}\n\n/** Origin only, for diagnostics: RPC URLs often carry an API key in the path or query */\nexport function describeRpc(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).origin;\n } catch {\n return '[unparseable rpcUrl]';\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `signerPrivateKey` is not shaped like a private key,\n * or if it is a well-known dev key and the RPC is not local.\n *\n * The shape check runs first, so a truncated key is reported as malformed\n * instead of passing as \"not a dev key\".\n */\nexport function assertDevKeyIsLocalOnly(rpcUrl: string, signerPrivateKey: string): void {\n if (!PRIVATE_KEY_SHAPE.test(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is not a well-formed private key ' +\n '(expected \"0x\" followed by exactly 64 hex characters).',\n );\n }\n\n if (!isWellKnownDevKey(signerPrivateKey)) return; // the operator's own key\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is a well-known Anvil development key, but rpcUrl ' +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. A public dev key must never sign against ` +\n 'a public network: it is instantly drainable and can grief real settlements via nonce exhaustion. ' +\n 'Use a real facilitator key for any non-local RPC, or point rpcUrl at your local/dev chain.',\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `payTo` is a well-known Anvil address and `rpcUrl`\n * does not look local or private.\n *\n * Guards the receiving side, in every facilitator mode. `agent-commerce init`\n * defaults `payTo` to a well-known address for the local demo, and on a real\n * network that default sends every payment where anyone can sweep it.\n */\nexport function assertPayToIsNotDevAddress(rpcUrl: string, payTo: string): void {\n if (!isWellKnownDevAddress(payTo)) return;\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" (${payTo}) is a well-known Anvil development address, but rpcUrl ` +\n `${describeRpc(rpcUrl)} does not look like a local/private chain. The private key behind that address ` +\n 'is public knowledge, so any revenue settled to it is immediately spendable by anyone. Set ' +\n '\"payTo\" to your own merchant wallet for any non-local RPC, or point rpcUrl at your ' +\n 'local/dev chain.',\n );\n }\n}\n","/**\n * What must hold before this gateway may settle a payment on the configured\n * network. Two callers share these checks: the provider runs them at\n * construction, so a library consumer who skips our config loader still gets\n * them, and the config loader runs them, so `validate` and `doctor` report\n * them too.\n *\n * Both run before any request, because a failure found in `settle()` would\n * come after the pipeline reserved the buyer's replay key.\n *\n * Imports no peer (no viem, no `@x402/*`), so the CLI can load it.\n */\nimport { CommerceError } from '../../core';\nimport { isBurnAddress, sameAddress } from './addresses';\nimport { isLikelyLocalOrPrivateHost, isWellKnownDevAddress } from './dev-key-guard';\nimport {\n type CustomNetworks,\n type DeploymentMode,\n LOCAL_CHAIN_ID,\n requireX402Network,\n resolveDeploymentMode,\n type X402Network,\n} from './networks';\n\n/**\n * How the gateway authenticates to a remote facilitator.\n *\n * - `none`: send no credential; use it when the facilitator accepts\n * anonymous requests.\n * - `bearer`: send a static token; no extra peer package is needed.\n * - `cdp`: Coinbase Developer Platform. The optional peer `@coinbase/x402`,\n * imported only for this type, signs a fresh JWT per request.\n *\n * Any other auth type is refused at config load.\n */\nexport type FacilitatorAuth =\n | { readonly type: 'none' }\n | { readonly type: 'bearer'; readonly token: string }\n | { readonly type: 'cdp'; readonly apiKeyId: string; readonly apiKeySecret: string };\n\nexport type X402FacilitatorConfig =\n | { readonly mode: 'local'; readonly signerPrivateKey: string }\n | { readonly mode: 'remote'; readonly url: string; readonly auth: FacilitatorAuth };\n\nexport interface X402DeploymentInput {\n readonly network: string;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain of the asset, as the token itself reports it */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly facilitator: X402FacilitatorConfig;\n /** Must be `true` before anything settles on a mainnet */\n readonly allowMainnet?: boolean;\n /**\n * Must be `true` on mainnet when facilitator auth is `none`. A separate\n * decision from `allowMainnet`: it accepts settling without an account at\n * the facilitator, under its anonymous-access limits.\n */\n readonly allowUnauthenticatedFacilitator?: boolean;\n /**\n * Allow other tokens on built-in EVM networks with explicit metadata.\n * MPP config leaves this unset; Solana and NEAR still require USDC.\n */\n readonly allowOtherEvmToken?: boolean;\n /** Error-path prefix, `payments.x402` by default */\n readonly configPath?: string;\n /** Settlement-recipient field named in errors, `payTo` by default */\n readonly payToField?: string;\n /** EVM networks declared under `payments.x402.networks` */\n readonly customNetworks?: CustomNetworks;\n}\n\nexport interface X402Deployment {\n readonly profile: X402Network;\n readonly mode: DeploymentMode;\n}\n\nconst BASE_SEPOLIA = 'eip155:84532';\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\n/**\n * Resolves the deployment and refuses the combinations that could move real\n * money by accident. The network must resolve first; the other checks are\n * independent.\n */\nexport function resolveX402Deployment(input: X402DeploymentInput): X402Deployment {\n const at = input.configPath ?? 'payments.x402';\n const payTo = input.payToField ?? 'payTo';\n const profile = requireX402Network(input.network, `${at}.network`, input.customNetworks);\n const mode = resolveDeploymentMode(profile);\n\n // Local mode keeps a gas-paying key in the gateway process. A compromise\n // could expose that key, so mainnet requires a remote facilitator.\n if (profile.kind === 'mainnet' && input.facilitator.mode === 'local') {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) is a mainnet and cannot be served by facilitator.mode \"local\". A mainnet deployment must settle through a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n // The in-process facilitator signs with a client built for the Anvil chain\n // id, so on any other chain every settlement would fail\n if (input.facilitator.mode === 'local' && mode !== 'local') {\n throw invalid(\n profile.id === BASE_SEPOLIA\n ? `${at}: the local Anvil chain is eip155:${LOCAL_CHAIN_ID}, Anvil's default chain id; \"${BASE_SEPOLIA}\" is public Base Sepolia. Set ${at}.network to eip155:${LOCAL_CHAIN_ID}, start Anvil with its default chain id and redeploy the local contracts (npm run chain:start, npm run chain:deploy).`\n : `${at}: facilitator.mode \"local\" serves the local Anvil chain (eip155:${LOCAL_CHAIN_ID}) only, not \"${profile.id}\" (${profile.displayName}). Use a remote facilitator.`,\n `${at}.facilitator.mode`,\n );\n }\n\n if (mode === 'mainnet' && input.allowMainnet !== true) {\n throw invalid(\n `${at}: network \"${profile.id}\" (${profile.displayName}) settles real funds. Set ${at}.allowMainnet: true to acknowledge this explicitly - it is never the default.`,\n `${at}.allowMainnet`,\n );\n }\n\n if (input.facilitator.mode === 'remote') {\n assertFacilitatorUrlIsSafe(input.facilitator.url, mode, at);\n // `@coinbase/x402` signs each request for CDP's own host and route,\n // whatever URL is configured, so no other facilitator can accept the credential\n if (input.facilitator.auth.type === 'cdp' && !isCdpFacilitatorUrl(input.facilitator.url)) {\n throw invalid(\n `${at}: facilitator.auth.type \"cdp\" signs requests for ${CDP_FACILITATOR_URL} only, so facilitator ${describeOrigin(input.facilitator.url)} cannot accept its credential. Set facilitator.url to ${CDP_FACILITATOR_URL}, or use auth.type \"bearer\" or \"none\".`,\n `${at}.facilitator.url`,\n );\n }\n // The authorization fixes recipient, amount and chain, so a facilitator\n // cannot redirect funds. A credential adds an account: rate limits, terms\n // and support. On mainnet, going without one is an explicit choice.\n if (\n mode === 'mainnet' &&\n input.facilitator.auth.type === 'none' &&\n input.allowUnauthenticatedFacilitator !== true\n ) {\n throw invalid(\n `${at}: no credential is configured for facilitator ${describeOrigin(input.facilitator.url)} on mainnet. Set ${at}.allowUnauthenticatedFacilitator: true to accept anonymous access and the facilitator's limits, or configure facilitator.auth.`,\n `${at}.allowUnauthenticatedFacilitator`,\n );\n }\n // A blank credential reaches the facilitator as \"unauthenticated\" and fails\n // every payment after the buyer signed. `${VAR:- }` resolving to whitespace\n // is the usual cause.\n for (const [field, value] of credentialFields(input.facilitator.auth)) {\n if (value.trim() === '') {\n throw invalid(\n `${at}: facilitator.auth.type is \"${input.facilitator.auth.type}\" but ${field} is empty. An empty credential is refused rather than sent.`,\n `${at}.facilitator.auth.${field}`,\n );\n }\n }\n }\n\n // The config loader's address check refuses this too; repeated here for a\n // library consumer who calls `createX402PaymentProvider` without it\n if (isBurnAddress(profile, input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" is the zero address. Every payment settled there is destroyed.`,\n `${at}.${payTo}`,\n );\n }\n\n // Anyone can spend from a well-known Anvil address. `dev-key-guard` refuses\n // one behind a public RPC; this refuses one on any non-local deployment,\n // whose RPC host says nothing about where a remote facilitator settles.\n if (mode !== 'local' && isWellKnownDevAddress(input.payTo)) {\n throw invalid(\n `${at}: \"${payTo}\" (${input.payTo}) is a well-known Anvil development address and this is a ${mode} deployment. Anyone can spend what settles there. Set ${payTo} to your own merchant wallet.`,\n `${at}.${payTo}`,\n );\n }\n\n // Public built-ins require USDC unless the caller allows another EVM token.\n // Local and declared networks have no default asset.\n const canonical = profile.canonicalAsset;\n if (canonical) {\n if (!sameAddress(profile, input.asset, canonical.address)) {\n if (input.allowOtherEvmToken !== true || profile.family !== 'evm') {\n const rule =\n input.allowOtherEvmToken === true\n ? `Only an EVM network accepts another token; ${profile.displayName} settles only in its ${canonical.symbol}.`\n : `A built-in network settles only in its ${canonical.symbol}.`;\n throw invalid(\n `${at}: asset ${input.asset} is not ${canonical.symbol} on ${profile.displayName} (expected ${canonical.address}). ${rule}`,\n `${at}.asset`,\n );\n }\n } else {\n // Catch USDC domain mismatches before accepting payments; a wrong name\n // can fail with `invalid_exact_evm_token_name_mismatch`\n const domain = 'name' in canonical ? canonical : undefined;\n if (domain && input.assetName !== undefined && input.assetName !== domain.name) {\n throw invalid(\n `${at}: assetName \"${input.assetName}\" is not the EIP-712 domain name ${canonical.symbol} reports on ${profile.displayName} (expected \"${domain.name}\"). Every payment would be refused after the buyer signed.`,\n `${at}.assetName`,\n );\n }\n if (domain && input.assetVersion !== undefined && input.assetVersion !== domain.version) {\n throw invalid(\n `${at}: assetVersion \"${input.assetVersion}\" is not the EIP-712 domain version ${canonical.symbol} reports on ${profile.displayName} (expected \"${domain.version}\").`,\n `${at}.assetVersion`,\n );\n }\n }\n }\n\n return { profile, mode };\n}\n\n/**\n * A facilitator sees every payment authorization this gateway handles. Plain\n * HTTP puts those on the wire in the clear and lets anyone in the path rewrite\n * a settlement result, so it is allowed only to a local or private host, and\n * never on a mainnet.\n */\nfunction assertFacilitatorUrlIsSafe(url: string, mode: DeploymentMode, at: string): void {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch (cause) {\n throw new CommerceError('CONFIG_INVALID', `${at}: facilitator.url is not a valid URL`, {\n cause,\n details: { path: `${at}.facilitator.url` },\n });\n }\n\n if (parsed.protocol === 'https:') return;\n if (parsed.protocol !== 'http:') {\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} must be reached over https (or http on a local/private host); got \"${parsed.protocol}//\"`,\n `${at}.facilitator.url`,\n );\n }\n if (mode !== 'mainnet' && isLikelyLocalOrPrivateHost(parsed.hostname)) return;\n\n // The origin, never the whole URL: the path can carry a tenant or an API\n // key, and this message reaches `validate`, `doctor`, startup output and CI logs\n throw invalid(\n `${at}: facilitator ${describeOrigin(url)} is reached over plain HTTP. Payment authorizations and settlement results would travel unencrypted. Use https, or point at a local/private host on a non-mainnet deployment.`,\n `${at}.facilitator.url`,\n );\n}\n\n/** The facilitator URL `@coinbase/x402` signs its JWTs for */\nexport const CDP_FACILITATOR_URL = 'https://api.cdp.coinbase.com/platform/v2/x402';\n\n// The SDK client strips trailing slashes before appending its route\nfunction isCdpFacilitatorUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n const expected = new URL(CDP_FACILITATOR_URL);\n return (\n parsed.origin === expected.origin &&\n parsed.pathname.replace(/\\/+$/, '') === expected.pathname &&\n parsed.search === ''\n );\n } catch {\n return false;\n }\n}\n\n// Origin only: a facilitator URL can carry a tenant path or an API key\nfunction describeOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n return '[unparseable facilitator.url]';\n }\n}\n\n// The secret-bearing fields of an auth block, for emptiness checks only. Never logged\nfunction credentialFields(auth: FacilitatorAuth): readonly (readonly [string, string])[] {\n switch (auth.type) {\n case 'bearer':\n return [['token', auth.token]];\n case 'cdp':\n return [\n ['apiKeyId', auth.apiKeyId],\n ['apiKeySecret', auth.apiKeySecret],\n ];\n default:\n return [];\n }\n}\n","/**\n * Resolves an x402 option into offer terms at config load, so `validate`\n * reports invalid options before startup. This module uses no SDK.\n *\n * Omitted assets use `canonicalAsset`. Overrides for the default token must\n * match its metadata; another token needs its own, including the EIP-712 domain\n * on EVM.\n */\nimport { CommerceError } from '../../core';\nimport { isBurnAddress, normalizeAddress, sameAddress } from './addresses';\nimport { type CustomNetworks, requireX402Network, type X402Network } from './networks';\n\nexport interface X402OptionInput {\n readonly scheme?: string;\n readonly network: string;\n readonly payTo: string;\n readonly asset?: string;\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals?: number;\n /** `eip3009` (the default) or `permit2`; EVM only */\n readonly assetTransferMethod?: string;\n}\n\nexport interface ResolvedX402Option {\n readonly scheme: 'exact';\n readonly network: X402Network;\n readonly payTo: string;\n readonly asset: string;\n /** EIP-712 domain; EVM only */\n readonly assetName?: string;\n readonly assetVersion?: string;\n readonly assetDecimals: number;\n /**\n * Default token symbol when `asset` is omitted; resource prices must use\n * this symbol or USD\n */\n readonly defaultAssetSymbol?: string;\n /** How the buyer authorizes the transfer; always `eip3009` off EVM */\n readonly assetTransferMethod: X402AssetTransferMethod;\n}\n\n/**\n * Names health components by network, asset and payee for discovery matching.\n * Lowercase EVM addresses so case variants identify the same offer.\n */\nexport function x402OfferName(offer: {\n readonly network: string;\n readonly asset: string;\n readonly payTo: string;\n}): string {\n const evm = offer.network.startsWith('eip155:');\n const address = (value: string) => (evm ? value.toLowerCase() : value);\n return `${offer.network} ${address(offer.asset)} ${address(offer.payTo)}`;\n}\n\n/** EIP-3009 `transferWithAuthorization`, or Permit2 with a prior token allowance */\nexport type X402AssetTransferMethod = 'eip3009' | 'permit2';\n\n// Incorrect EIP-712 domain values invalidate the buyer's signature\nconst FIELD_MEANINGS = {\n assetName: 'EIP-712 domain name',\n assetVersion: 'EIP-712 domain version',\n assetDecimals: 'decimals',\n} as const;\n\nconst ADDRESS_SHAPES = {\n evm: '\"0x\" followed by 40 hex characters',\n svm: 'a base58 public key of 32 bytes',\n near: 'a NEAR account ID: 2 to 64 lowercase characters, digits and single \"-\", \"_\" or \".\" separators',\n} as const;\n\nfunction invalid(message: string, path: string): CommerceError {\n return new CommerceError('CONFIG_INVALID', message, { details: { path } });\n}\n\nexport function resolveX402Option(\n input: X402OptionInput,\n path: string,\n custom?: CustomNetworks,\n): ResolvedX402Option {\n if (input.scheme !== undefined && input.scheme !== 'exact') {\n throw invalid(\n `${path}.scheme: \"${input.scheme}\" is not supported; the only x402 scheme is \"exact\"`,\n `${path}.scheme`,\n );\n }\n const network = requireX402Network(input.network, `${path}.network`, custom);\n const address = (field: 'payTo' | 'asset', value: string): string => {\n const wire = normalizeAddress(network, value);\n if (wire === undefined) {\n throw invalid(\n // The value is not echoed: a swapped variable could put a key here\n `${path}.${field} is not a plausible address on ${network.displayName} (expected ${ADDRESS_SHAPES[network.family]})`,\n `${path}.${field}`,\n );\n }\n return wire;\n };\n\n const payTo = address('payTo', input.payTo);\n if (isBurnAddress(network, payTo)) {\n throw invalid(\n `${path}.payTo is the zero address of ${network.displayName}. Every payment settled there is destroyed.`,\n `${path}.payTo`,\n );\n }\n\n const method = input.assetTransferMethod ?? 'eip3009';\n if (method !== 'eip3009' && method !== 'permit2') {\n throw invalid(\n `${path}.assetTransferMethod: \"${method}\" is not supported; use \"eip3009\" or \"permit2\"`,\n `${path}.assetTransferMethod`,\n );\n }\n if (network.family !== 'evm' && input.assetTransferMethod !== undefined) {\n throw invalid(\n `${path}.assetTransferMethod applies to EVM networks only, not to ${network.displayName}`,\n `${path}.assetTransferMethod`,\n );\n }\n\n if (network.family !== 'evm') {\n for (const field of ['assetName', 'assetVersion'] as const) {\n if (input[field] !== undefined) {\n throw invalid(\n `${path}.${field}: an EIP-712 domain applies to EVM tokens only, not to ${network.displayName}`,\n `${path}.${field}`,\n );\n }\n }\n }\n\n const canonical = network.canonicalAsset;\n const domain = canonical && 'name' in canonical ? canonical : undefined;\n\n const asset = input.asset !== undefined ? address('asset', input.asset) : undefined;\n if (asset !== undefined && isBurnAddress(network, asset)) {\n throw invalid(`${path}.asset must not be the zero address`, `${path}.asset`);\n }\n\n // The default asset applies when the option names none or names it exactly\n if (canonical && (asset === undefined || sameAddress(network, asset, canonical.address))) {\n const expected = {\n assetName: domain?.name,\n assetVersion: domain?.version,\n assetDecimals: canonical.decimals,\n };\n for (const field of ['assetName', 'assetVersion', 'assetDecimals'] as const) {\n const given = input[field];\n if (given !== undefined && given !== expected[field]) {\n throw invalid(\n `${path}.${field} does not match ${canonical.symbol} on ${network.displayName}, which reports ${FIELD_MEANINGS[field]} ${JSON.stringify(expected[field])}. Remove ${field}, or set asset to the token it describes.`,\n `${path}.${field}`,\n );\n }\n }\n return {\n scheme: 'exact',\n network,\n payTo,\n asset: asset ?? canonical.address,\n ...(domain ? { assetName: domain.name, assetVersion: domain.version } : {}),\n assetDecimals: canonical.decimals,\n defaultAssetSymbol: canonical.symbol,\n assetTransferMethod: method,\n };\n }\n\n // Another token: nothing about it can be borrowed from the default. The\n // token's EIP-712 domain matters to EIP-3009 only: a Permit2 buyer signs\n // Permit2's own domain.\n const required =\n network.family === 'evm' && method === 'eip3009'\n ? (['asset', 'assetName', 'assetVersion', 'assetDecimals'] as const)\n : (['asset', 'assetDecimals'] as const);\n const missing = required.filter((field) => input[field] === undefined);\n if (asset === undefined || missing.length > 0) {\n throw invalid(\n canonical\n ? `${path}: a token other than ${canonical.symbol} on ${network.displayName} needs ${missing.join(', ')}`\n : `${path}: ${network.displayName} has no default asset, so the option needs ${missing.join(', ')}`,\n `${path}.${missing[0] ?? 'asset'}`,\n );\n }\n return {\n scheme: 'exact',\n network,\n payTo,\n asset,\n ...(input.assetName !== undefined ? { assetName: input.assetName } : {}),\n ...(input.assetVersion !== undefined ? { assetVersion: input.assetVersion } : {}),\n assetDecimals: input.assetDecimals as number,\n assetTransferMethod: method,\n };\n}\n","/**\n * x402 exact-scheme flows, shared by the config loader and CLI.\n * The default `authorization` flow settles after a successful backend call;\n * `upfront` settles first.\n */\nexport const X402_PAYMENT_FLOWS = ['authorization', 'upfront'] as const;\n\nexport type X402PaymentFlow = (typeof X402_PAYMENT_FLOWS)[number];\n\nexport const X402_DEFAULT_PAYMENT_FLOW: X402PaymentFlow = 'authorization';\n"]}