@devlab.group/agent-commerce 2.4.1 → 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-DTKU3Z2M.js → chunk-3OTCFFFT.js} +37 -4
  6. package/dist/chunk-3OTCFFFT.js.map +1 -0
  7. package/dist/{chunk-QPV3EGJO.js → chunk-4K7FIBJM.js} +25 -4
  8. package/dist/chunk-4K7FIBJM.js.map +1 -0
  9. package/dist/{chunk-CXWC5LWM.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-WZW5ORZH.js → chunk-VUCMBGUR.js} +3 -3
  14. package/dist/{chunk-WZW5ORZH.js.map → chunk-VUCMBGUR.js.map} +1 -1
  15. package/dist/cli/{ap2-GWSP4LYY.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-ITWNSS2B.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-TNMLDPUO.js → chunk-QA2OPHBF.js} +655 -70
  36. package/dist/cli/chunk-QA2OPHBF.js.map +1 -0
  37. package/dist/cli/{chunk-GJIMDMYT.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-PGBRWZVA.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-I2ESL6RS.js → provider-6TKB5ADJ.js} +26 -15
  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-JK4ERPJV.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-7WBFZQXV.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 +20 -10
  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-CXWC5LWM.js.map +0 -1
  84. package/dist/chunk-DTKU3Z2M.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-QPV3EGJO.js.map +0 -1
  88. package/dist/cli/ap2-GWSP4LYY.js.map +0 -1
  89. package/dist/cli/chunk-G2JEY7MB.js.map +0 -1
  90. package/dist/cli/chunk-GJIMDMYT.js.map +0 -1
  91. package/dist/cli/chunk-ITWNSS2B.js +0 -8
  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-TNMLDPUO.js.map +0 -1
  98. package/dist/cli/config-UI4EDG4L.js +0 -11
  99. package/dist/cli/mcp-PGBRWZVA.js.map +0 -1
  100. package/dist/cli/near-5AY3HWYF.js.map +0 -1
  101. package/dist/cli/provider-I2ESL6RS.js.map +0 -1
  102. package/dist/cli/run-JK4ERPJV.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-7WBFZQXV.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
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/payments/x402/provider/constants.ts","../src/payments/x402/provider/fee-payer.ts","../src/payments/x402/provider/health.ts","../src/payments/x402/chain.ts","../src/payments/x402/facilitator.ts","../src/payments/x402/local-facilitator.ts","../src/payments/x402/provider/reasons.ts","../src/payments/x402/provider/offers.ts","../src/core/canonical-json.ts","../src/payments/x402/provider/quote.ts","../src/payments/x402/amount.ts","../src/payments/x402/payload.ts","../src/payments/x402/provider/requirement.ts","../src/payments/x402/provider/transfer.ts","../src/payments/x402/provider/settle.ts","../src/payments/x402/provider/verify.ts","../src/payments/x402/provider/index.ts"],"names":["privateKeyToAccount","offer","index","from","nonce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A,IACN,UAAA;AAAA,IACA,iBAAA;AAAA;AAAA,IAEA,GAAI,aAAA,GAAgB,EAAE,iBAAA,KAAsB,EAAC;AAAA,IAC7C,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAI,MAAA,GACA;AAAA,MACE,KAAA,EAAO;AAAA,QACL,QAAQ,MAAA,CAAO,MAAA;AAAA,QACf,aAAA,EAAe,oBAAA;AAAA,QACf,SAAA,EAAW;AAAA;AACb,QAEF;AAAC,GACP;AACF;AAMA,SAAS,kBAAA,CAAsB,MAAwB,OAAA,EAA6B;AAClF,EAAA,MAAM,OAAA,GAAU,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,KAAA,KAAmB;AAC/C,IAAA,MAAM,IAAI,aAAA,CAAc,8BAAA,EAAgC,CAAA,eAAA,EAAkB,OAAO,CAAA,CAAA,EAAI;AAAA,MACnF;AAAA,KACD,CAAA;AAAA,EACH,CAAC,CAAA;AAED,EAAA,OAAA,CAAQ,MAAM,MAAM;AAAA,EAAC,CAAC,CAAA;AACtB,EAAA,OAAO,OAAA;AACT","file":"chunk-CXWC5LWM.js","sourcesContent":["// Protocol constants shared by the x402 provider's modules\nimport type { IdGenerator } from '../../../core';\n\nexport const X402_VERSION = 2;\nexport const X402_PROTOCOL_VERSION = String(X402_VERSION);\nexport const DEFAULT_MAX_TIMEOUT_SECONDS = 60;\nexport const DEFAULT_MIME_TYPE = 'application/json';\nexport const HEALTH_TIMEOUT_MS = 4_000;\n\n/** Prefixed random UUIDs, shared with the MPP rail */\nexport const DEFAULT_IDS: IdGenerator = {\n next: (prefix?: string) => `${prefix ? `${prefix}_` : ''}${crypto.randomUUID()}`,\n};\n","// The Solana fee payer an offer names, read from the facilitator's `/supported`\nimport type { SupportedResponse } from '@x402/core/types';\nimport { CommerceError } from '../../../core';\nimport { normalizeAddress } from '../addresses';\nimport type { FacilitatorBinding } from '../facilitator';\nimport { X402_VERSION } from './constants';\nimport type { ProviderContext, SvmOffer } from './types';\n\n// How long a `/supported` snapshot names the Solana fee payer of new offers\nconst SUPPORTED_TTL_MS = 60_000;\n\n/** Returns the fee payer lookup, with its `/supported` snapshot, for one provider */\nexport function createSvmFeePayerSource(\n ctx: ProviderContext,\n): (offer: SvmOffer) => Promise<string> {\n const { clock, remoteBinding } = ctx;\n\n // A Solana offer carries the fee payer the facilitator names in `/supported`.\n // A snapshot lasts SUPPORTED_TTL_MS, and a refresh keeps the previous fee\n // payer while the facilitator still lists it, so a challenge and the retry\n // that pays it agree.\n let supportedSnapshot:\n | { readonly at: number; readonly response: Promise<SupportedResponse> }\n | undefined;\n const feePayers = new Map<string, string>();\n\n function currentSupported(): Promise<SupportedResponse> {\n const now = clock.monotonicMs();\n if (supportedSnapshot && now - supportedSnapshot.at < SUPPORTED_TTL_MS) {\n return supportedSnapshot.response;\n }\n const remote = remoteBinding as Extract<FacilitatorBinding, { kind: 'remote' }>;\n const response = remote.supported();\n const snapshot = { at: now, response };\n supportedSnapshot = snapshot;\n // A failed fetch is not kept; the next challenge asks again\n response.catch(() => {\n if (supportedSnapshot === snapshot) supportedSnapshot = undefined;\n });\n return response;\n }\n\n async function svmFeePayer(offer: SvmOffer): Promise<string> {\n let supported: SupportedResponse;\n try {\n supported = await currentSupported();\n } catch (cause) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: facilitator ${offer.binding.describe} did not answer /supported, which names the Solana fee payer`,\n { cause },\n );\n }\n const listed = supported.kinds.find(\n (kind) =>\n kind.x402Version === X402_VERSION &&\n kind.scheme === 'exact' &&\n kind.network === offer.network,\n )?.extra?.['feePayer'];\n const previous = feePayers.get(offer.network);\n const stillSigns =\n previous !== undefined &&\n (previous === listed || Object.values(supported.signers).some((s) => s.includes(previous)));\n const feePayer = stillSigns ? previous : listed;\n if (typeof feePayer !== 'string' || normalizeAddress(offer.profile, feePayer) === undefined) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: facilitator ${offer.binding.describe} names no Solana fee payer for ${offer.network}`,\n );\n }\n feePayers.set(offer.network, feePayer);\n return feePayer;\n }\n\n return svmFeePayer;\n}\n","// Readiness: each offer's chain, asset and facilitator support, cached briefly\n\nimport type { SupportedKind } from '@x402/core/types';\nimport { PERMIT2_ADDRESS, x402ExactPermit2ProxyAddress } from '@x402/evm';\nimport { erc20Abi } from 'viem';\nimport { type AdapterHealth, CommerceError } from '../../../core';\nimport { redactedErrorText } from '../../../core/errors';\nimport { isRecord } from '../../../core/is-record';\nimport { normalizeAddress } from '../addresses';\nimport type { createLocalPublicClient } from '../chain';\nimport type { FacilitatorBinding } from '../facilitator';\nimport { describeDeploymentMode } from '../networks';\nimport { x402OfferName } from '../options';\nimport { HEALTH_TIMEOUT_MS, X402_VERSION } from './constants';\nimport type { NearOffer, Offer, ProviderContext, SvmOffer } from './types';\n\n/** Builds the provider's `health`, which probes every offer and caches the result */\nexport function createHealthCheck(ctx: ProviderContext): () => Promise<AdapterHealth> {\n const { offers, clock, deploymentMode, remoteBinding, svm, near } = ctx;\n\n // One offer's chain, asset and facilitator support. `kinds` fetches the\n // remote facilitator's `/supported` once per probe, shared by every offer.\n async function offerHealth(\n offer: Offer,\n kinds: () => Promise<readonly SupportedKind[]>,\n ): Promise<{ readonly status: 'pass' | 'fail'; readonly detail: string }> {\n if (offer.family === 'svm') return svmOfferHealth(offer, kinds);\n if (offer.family === 'near') return nearOfferHealth(offer, kinds);\n const { profile, rpcOrigin, healthClient, binding } = offer;\n const chainId = await healthClient.getChainId();\n if (chainId !== profile.chainId) {\n return {\n status: 'fail',\n detail: `RPC at ${rpcOrigin} reports chain id ${chainId}, expected ${profile.chainId} (${profile.displayName})`,\n };\n }\n\n const code = await healthClient.getCode({ address: offer.asset });\n if (!code || code === '0x') {\n return {\n status: 'fail',\n detail: `No contract code found at configured asset address ${offer.asset}`,\n };\n }\n // Decimals scale signed amounts; verify them on-chain, as for Solana and NEAR\n const decimals = await healthClient.readContract({\n address: offer.asset,\n abi: erc20Abi,\n functionName: 'decimals',\n });\n if (decimals !== offer.assetDecimals) {\n return {\n status: 'fail',\n detail: `Token ${offer.asset} has ${decimals} decimals, configured ${offer.assetDecimals}`,\n };\n }\n // Permit2 offers settle through two contracts the merchant does not deploy\n if (offer.method === 'permit2') {\n for (const [name, address] of PERMIT2_CONTRACTS) {\n const deployed = await healthClient.getCode({ address });\n if (!deployed || deployed === '0x') {\n return {\n status: 'fail',\n detail: `No ${name} contract code found at ${address} on ${profile.displayName}`,\n };\n }\n }\n }\n const contracts = `asset ${offer.asset}${offer.method === 'permit2' ? ', Permit2 and its x402 proxy' : ''}`;\n\n if (binding.kind === 'remote') {\n // Reachable is not enough: a facilitator that does not carry our\n // scheme on our network fails every payment after the buyer has signed\n const supportsUs = (await kinds()).some(\n (kind) =>\n kind.x402Version === X402_VERSION &&\n kind.scheme === 'exact' &&\n kind.network === offer.network,\n );\n if (!supportsUs) {\n return {\n status: 'fail',\n detail:\n `Facilitator ${binding.describe} does not advertise x402 v${X402_VERSION} scheme=exact ` +\n `on ${offer.network} (${profile.displayName}); no payment on this deployment can settle`,\n };\n }\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(deploymentMode)}: RPC ${rpcOrigin} reachable, chain id ` +\n `${profile.chainId} (${profile.displayName}), ${contracts} have code, ` +\n `facilitator ${binding.describe} supports exact/${offer.network}`,\n };\n }\n\n // An RPC reports whatever chain id it was started with, so the id cannot\n // prove this is a dev chain. An Anvil-only RPC method must answer before\n // a local facilitator counts as healthy.\n const isAnvil = await probeIsAnvilNode(healthClient);\n if (!isAnvil) {\n return {\n status: 'fail',\n detail:\n `RPC at ${rpcOrigin} reports chain id ${profile.chainId} but does not answer ` +\n '\"anvil_nodeInfo\", so it does not look like a local Anvil dev node. Refusing to treat it ' +\n 'as safe for a local-facilitator dev key.',\n };\n }\n\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(deploymentMode)}: RPC ${rpcOrigin} reachable, chain id ` +\n `${profile.chainId}, ${contracts} have code, confirmed Anvil dev node`,\n };\n }\n\n // A Solana offer's cluster, mint and fee payer. The CAIP-2 reference is the\n // start of the genesis hash, so the RPC proves which cluster it serves.\n async function svmOfferHealth(\n offer: SvmOffer,\n kinds: () => Promise<readonly SupportedKind[]>,\n ): Promise<{ readonly status: 'pass' | 'fail'; readonly detail: string }> {\n const { profile, rpcOrigin, binding } = offer;\n // A missing Solana peer fails readiness, not the first paid request\n const svmModule = await svm();\n const genesis = await jsonRpc(offer.rpcUrl, 'getGenesisHash', []);\n const cluster = typeof genesis === 'string' ? `solana:${genesis.slice(0, 32)}` : undefined;\n if (cluster !== offer.network) {\n return {\n status: 'fail',\n detail: `RPC at ${rpcOrigin} serves ${cluster ?? 'an unknown cluster'}, expected ${offer.network} (${profile.displayName})`,\n };\n }\n const mint = await jsonRpc(offer.rpcUrl, 'getAccountInfo', [\n offer.asset,\n { encoding: 'base64' },\n ]);\n const mintInfo = readMint(mint);\n if (mintInfo === undefined) {\n return {\n status: 'fail',\n detail: `No initialized token mint found at configured asset address ${offer.asset}`,\n };\n }\n const { decimals, tokenProgram } = mintInfo;\n if (decimals !== offer.assetDecimals) {\n return {\n status: 'fail',\n detail: `Mint ${offer.asset} has ${decimals} decimals, configured ${offer.assetDecimals}`,\n };\n }\n // Without the payee's token account every payment fails the facilitator's\n // simulation, after the buyer signed\n const payeeAccount = await svmModule.associatedTokenAccount(\n offer.payTo,\n offer.asset,\n tokenProgram,\n );\n const account = await jsonRpc(offer.rpcUrl, 'getAccountInfo', [\n payeeAccount,\n { encoding: 'base64' },\n ]);\n const accountValue = isRecord(account) ? account['value'] : undefined;\n if (!isRecord(accountValue) || accountValue['owner'] !== tokenProgram) {\n return {\n status: 'fail',\n detail: `payTo ${offer.payTo} has no token account for mint ${offer.asset}; create its associated token account (${payeeAccount}) before taking payments`,\n };\n }\n const feePayer = (await kinds()).find(\n (kind) =>\n kind.x402Version === X402_VERSION &&\n kind.scheme === 'exact' &&\n kind.network === offer.network,\n )?.extra?.['feePayer'];\n if (typeof feePayer !== 'string' || normalizeAddress(profile, feePayer) === undefined) {\n return {\n status: 'fail',\n detail:\n `Facilitator ${binding.describe} does not advertise x402 v${X402_VERSION} scheme=exact ` +\n `on ${offer.network} (${profile.displayName}) with a fee payer; no payment on this deployment can settle`,\n };\n }\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(deploymentMode)}: RPC ${rpcOrigin} serves ${profile.displayName}, ` +\n `mint ${offer.asset} has ${decimals} decimals and a token account for ${offer.payTo}, ` +\n `facilitator ${binding.describe} supports ` +\n `exact/${offer.network} with fee payer ${feePayer}`,\n };\n }\n\n // A NEAR offer's chain, token and merchant registration. The RPC's `status`\n // names the chain it serves; an account suffix such as `.testnet` proves nothing.\n async function nearOfferHealth(\n offer: NearOffer,\n kinds: () => Promise<readonly SupportedKind[]>,\n ): Promise<{ readonly status: 'pass' | 'fail'; readonly detail: string }> {\n const { profile, rpcOrigin, binding, rpcUrl } = offer;\n // A missing NEAR peer fails readiness, not the first paid request\n await near();\n const status = await jsonRpc(rpcUrl, 'status', []);\n const chainId = isRecord(status) ? status['chain_id'] : undefined;\n const expected = offer.network.slice('near:'.length);\n if (chainId !== expected) {\n return {\n status: 'fail',\n detail: `RPC at ${rpcOrigin} serves chain ${String(chainId ?? 'unknown')}, expected ${expected} (${profile.displayName})`,\n };\n }\n const token = await jsonRpc(rpcUrl, 'query', {\n request_type: 'view_account',\n finality: 'final',\n account_id: offer.asset,\n });\n if (!isRecord(token) || token['code_hash'] === NEAR_EMPTY_CODE_HASH) {\n return {\n status: 'fail',\n detail: `No contract code found at configured asset account ${offer.asset}`,\n };\n }\n const metadata = await nearView(rpcUrl, offer.asset, 'ft_metadata', {});\n const decimals = isRecord(metadata) ? metadata['decimals'] : undefined;\n if (decimals !== offer.assetDecimals) {\n return {\n status: 'fail',\n detail: `Token ${offer.asset} has ${String(decimals)} decimals, configured ${offer.assetDecimals}`,\n };\n }\n // An unregistered recipient makes every transfer fail after the relayer\n // paid for it. A token without NEP-145 storage management needs none.\n let registered = true;\n try {\n registered =\n (await nearView(rpcUrl, offer.asset, 'storage_balance_of', {\n account_id: offer.payTo,\n })) !== null;\n } catch (err) {\n if (!/MethodNotFound|MethodResolveError/i.test(redactedErrorText(err))) throw err;\n }\n if (!registered) {\n return {\n status: 'fail',\n detail: `payTo ${offer.payTo} has no storage registered with token ${offer.asset}; register it (NEP-145 storage_deposit) before taking payments`,\n };\n }\n const listed = (await kinds()).some(\n (kind) =>\n kind.x402Version === X402_VERSION &&\n kind.scheme === 'exact' &&\n kind.network === offer.network,\n );\n if (!listed) {\n return {\n status: 'fail',\n detail:\n `Facilitator ${binding.describe} does not advertise x402 v${X402_VERSION} scheme=exact ` +\n `on ${offer.network} (${profile.displayName}); no payment on this deployment can settle`,\n };\n }\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(deploymentMode)}: RPC ${rpcOrigin} serves ${expected}, ` +\n `token ${offer.asset} has ${decimals} decimals and storage for ${offer.payTo}, ` +\n `facilitator ${binding.describe} supports exact/${offer.network}`,\n };\n }\n\n // Check all offers and report each status; any failure fails readiness.\n // Challenges retain the complete offer list.\n async function computeHealth(): Promise<AdapterHealth> {\n const startedAt = clock.monotonicMs();\n const checkedAt = clock.nowIso();\n let supported: Promise<readonly SupportedKind[]> | undefined;\n const kinds = () => {\n supported ??= (remoteBinding as Extract<FacilitatorBinding, { kind: 'remote' }>)\n .supported()\n .then((response) => response.kinds);\n return supported;\n };\n\n const results = await Promise.all(\n offers.map((offer) =>\n offerHealth(offer, kinds).catch((err: unknown) => ({\n status: 'fail' as const,\n detail: `x402 health check failed: ${redactedErrorText(err)}`,\n })),\n ),\n );\n const failed = results.some((result) => result.status === 'fail');\n const details = offers.flatMap((offer, index) => {\n const result = results[index] as (typeof results)[number];\n if (failed && result.status !== 'fail') return [];\n return [offers.length === 1 ? result.detail : `${x402OfferName(offer)}: ${result.detail}`];\n });\n return {\n status: failed ? 'fail' : 'pass',\n detail: details.join('; '),\n components: offers.map((offer, index) => ({\n name: x402OfferName(offer),\n status: (results[index] as (typeof results)[number]).status,\n })),\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n // A probe makes several upstream calls, and `/ready` is unauthenticated.\n // A short TTL plus one shared in-flight probe keeps upstream volume independent\n // of request volume, for library callers as well as the gateway, whose\n // readiness probe adds its own cache on top. Pass and fail share the TTL: a\n // shorter one for fail would bring the load back during an RPC outage,\n // exactly when each call is slowest.\n const HEALTH_CACHE_MS = 5_000;\n let cachedHealth: { at: number; value: AdapterHealth } | undefined;\n let inFlightHealth: Promise<AdapterHealth> | undefined;\n\n async function health(): Promise<AdapterHealth> {\n const now = clock.monotonicMs();\n if (cachedHealth && now - cachedHealth.at < HEALTH_CACHE_MS) {\n return cachedHealth.value;\n }\n if (inFlightHealth) return inFlightHealth;\n\n inFlightHealth = computeHealth()\n .then((value) => {\n cachedHealth = { at: clock.monotonicMs(), value };\n return value;\n })\n .finally(() => {\n inFlightHealth = undefined;\n });\n return inFlightHealth;\n }\n\n return health;\n}\n\nconst PERMIT2_CONTRACTS = [\n ['Permit2', PERMIT2_ADDRESS],\n ['x402 exact Permit2 proxy', x402ExactPermit2ProxyAddress],\n] as const;\n\nconst TOKEN_PROGRAMS: ReadonlySet<string> = new Set([\n 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',\n 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',\n]);\n\n// The decimals and owning token program of an initialized SPL Token or\n// Token-2022 mint, from a base64 `getAccountInfo` result: byte 44 holds the\n// decimals, byte 45 the initialized flag\nfunction readMint(\n result: unknown,\n): { readonly decimals: number; readonly tokenProgram: string } | undefined {\n const value = isRecord(result) ? result['value'] : undefined;\n if (!isRecord(value)) return undefined;\n const owner = value['owner'];\n if (typeof owner !== 'string' || !TOKEN_PROGRAMS.has(owner)) return undefined;\n const data = value['data'];\n if (!Array.isArray(data) || typeof data[0] !== 'string') return undefined;\n const bytes = Buffer.from(data[0], 'base64');\n const decimals = bytes[44];\n return bytes.length >= 82 && bytes[45] === 1 && decimals !== undefined\n ? { decimals, tokenProgram: owner }\n : undefined;\n}\n\n// One JSON-RPC call for health(), bounded like the EVM client's\nasync function jsonRpc(rpcUrl: string, method: string, params: unknown): Promise<unknown> {\n const response = await fetch(rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),\n signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),\n });\n const body = (await response.json()) as { result?: unknown; error?: unknown };\n if (body.error !== undefined) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `RPC ${method} failed: ${JSON.stringify(body.error)}`,\n );\n }\n return body.result;\n}\n\n// A NEAR contract view call at final finality, its result parsed as JSON\nasync function nearView(\n rpcUrl: string,\n accountId: string,\n method: string,\n args: Record<string, unknown>,\n): Promise<unknown> {\n const result = await jsonRpc(rpcUrl, 'query', {\n request_type: 'call_function',\n finality: 'final',\n account_id: accountId,\n method_name: method,\n args_base64: Buffer.from(JSON.stringify(args)).toString('base64'),\n });\n const bytes = isRecord(result) ? result['result'] : undefined;\n if (!Array.isArray(bytes)) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `NEAR view ${method} returned no result`,\n );\n }\n return JSON.parse(Buffer.from(bytes as number[]).toString('utf8'));\n}\n\n// The code hash of an account without a contract\nconst NEAR_EMPTY_CODE_HASH = '11111111111111111111111111111111';\n\n/**\n * True only when the RPC answers Anvil's own `anvil_nodeInfo` method. A public\n * node, Base Sepolia included, answers \"method not found\". Never throws.\n */\nasync function probeIsAnvilNode(\n client: ReturnType<typeof createLocalPublicClient>,\n): Promise<boolean> {\n // Anvil-only method, absent from viem's typed PublicRpcSchema, hence the cast\n const request = client.request as unknown as (args: {\n method: string;\n params: unknown[];\n }) => Promise<unknown>;\n try {\n await request({ method: 'anvil_nodeInfo', params: [] });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * viem clients for the x402 provider, built on the configured `rpcUrl`. The\n * SDK uses the client it is handed, so the provider's chain calls reach no\n * other RPC.\n *\n * `createLocalPublicClient` backs health checks on the configured network.\n * `createLocalFacilitatorClient` handles settlement and defaults to the local\n * chain ID, the only network the gateway's in-process facilitator serves.\n * Deployment tools and test facilitators can pass another chain ID.\n */\nimport {\n type Account,\n type Chain,\n type Client,\n createPublicClient,\n createWalletClient,\n http,\n type PublicActions,\n type PublicClient,\n publicActions,\n type Transport,\n type WalletActions,\n} from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { LOCAL_CHAIN_ID } from './networks';\n\n/** A wallet client that can also read chain state, matching x402's `SignerWallet` */\nexport type LocalFacilitatorClient = Client<\n Transport,\n Chain,\n Account,\n undefined,\n PublicActions<Transport, Chain, Account> & WalletActions<Chain, Account>\n>;\n\n/** CAIP-2 identifier the local dev chain is advertised under */\nexport const LOCAL_NETWORK = `eip155:${LOCAL_CHAIN_ID}`;\n\n/**\n * Chain id carried by a CAIP-2 `eip155` network identifier, or `undefined` for\n * anything else. A caller must never fall back to a default chain id, because\n * the chain id is part of the EIP-712 domain the buyer signed.\n */\nexport function chainIdFromCaip2(network: string): number | undefined {\n const match = /^eip155:(\\d+)$/.exec(network);\n if (!match?.[1]) return undefined;\n const chainId = Number(match[1]);\n return Number.isSafeInteger(chainId) && chainId > 0 ? chainId : undefined;\n}\n\n// `chainId` defaults to the local dev chain; callers on another chain pass its id\nfunction buildLocalChain(rpcUrl: string, chainId: number = LOCAL_CHAIN_ID): Chain {\n return {\n id: chainId,\n name: 'agent-commerce-local',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: { http: [rpcUrl] },\n },\n } satisfies Chain;\n}\n\n/**\n * A read-only viem `PublicClient`.\n *\n * `timeoutMs` goes to viem's `http()` transport, which aborts the underlying\n * `fetch` when it expires rather than only abandoning the wait. Omit it to keep\n * viem's default of 10s.\n */\nexport function createLocalPublicClient(\n rpcUrl: string,\n timeoutMs?: number,\n chainId?: number,\n): PublicClient {\n return createPublicClient({\n chain: buildLocalChain(rpcUrl, chainId),\n transport: http(rpcUrl, timeoutMs !== undefined ? { timeout: timeoutMs } : undefined),\n });\n}\n\n/**\n * A viem `WalletClient` extended with public actions, for the local\n * facilitator signer only: the SDK's settlement both writes and reads through\n * it.\n *\n * LOCAL DEVELOPMENT ONLY. The key behind it pays gas on the dev chain. It is\n * usually an Anvil well-known key, and must never be a merchant, buyer or\n * production key.\n */\nexport function createLocalFacilitatorClient(\n rpcUrl: string,\n signerPrivateKey: `0x${string}`,\n chainId?: number,\n): LocalFacilitatorClient {\n const chain = buildLocalChain(rpcUrl, chainId);\n const account = privateKeyToAccount(signerPrivateKey);\n return createWalletClient({\n account,\n chain,\n transport: http(rpcUrl),\n }).extend(publicActions);\n}\n","/**\n * Shared facilitator interface and remote HTTP binding. The in-process EVM\n * binding lives in `local-facilitator.ts` to keep EVM peers out of this module.\n * `@x402/core` loads statically; `@coinbase/x402` loads only for `auth.type: cdp`.\n * Both bindings use the SDK to verify authorizations and broadcast transfers.\n *\n * Each verify or settle call gets a session with its own `transportFailed()`\n * flag, isolating concurrent payments' transport failures.\n */\nimport { HTTPFacilitatorClient } from '@x402/core/http';\nimport {\n type Network,\n type PaymentPayload,\n type PaymentRequirements,\n SettleError,\n type SettleResponse,\n type SupportedResponse,\n VerifyError,\n type VerifyResponse,\n} from '@x402/core/types';\nimport { CommerceError } from '../../core';\nimport type { FacilitatorAuth } from './guardrails';\n\n/** One verify or one settle, with its own transport-failure flag */\nexport interface FacilitatorSession {\n verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;\n settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;\n /**\n * True when the call produced no verdict: the local binding sets it when an\n * RPC call to the chain fails in transport, the remote binding on every\n * throw other than a 400 refusal of a verify or a settle.\n *\n * The SDK's `exact`/EVM scheme reports its own RPC errors as ordinary\n * verification failures: an unreachable node comes back as\n * `invalid_exact_evm_signature`. Without this flag the buyer would be told\n * their signature is bad for a payment nothing checked.\n */\n transportFailed(): boolean;\n}\n\ninterface BindingBase {\n /** Human-readable, never a credential */\n readonly describe: string;\n open(): FacilitatorSession;\n}\n\nexport type FacilitatorBinding =\n | (BindingBase & { readonly kind: 'local' })\n | (BindingBase & {\n readonly kind: 'remote';\n /**\n * SDK-parsed `/supported` response, including kinds and their `extra`\n * (such as Solana's fee payer), extensions and signers. health() reads\n * it, and so does a Solana challenge, which names the fee payer\n */\n supported(): Promise<SupportedResponse>;\n });\n\n/** Bounds each receipt wait of the in-process facilitator, and each verify or settle request to a remote one */\nexport const SETTLEMENT_CONFIRMATION_TIMEOUT_MS = 60_000;\n/**\n * Bounds a remote `/supported` read, retries included. Readiness and every\n * Solana challenge wait on it, and the SDK retries a 429 for up to 30 s a time.\n */\nexport const SUPPORTED_TIMEOUT_MS = 10_000;\n\nexport interface RemoteFacilitatorOptions {\n readonly url: string;\n readonly auth: FacilitatorAuth;\n}\n\n// The SDK's path-keyed auth-header shape. A flat object throws inside it\ntype AuthHeaderFactory = () => Promise<Record<string, Record<string, string>>>;\n\n/**\n * CDP needs a fresh JWT per request over method, host and path, which a static\n * header cannot express. The optional peer `@coinbase/x402` does the signing.\n * It is imported dynamically, so only `auth.type: cdp` pulls in the CDP SDK and\n * its Solana, axios and JOSE dependencies.\n *\n * The import starts at construction, so a missing peer fails the health check\n * before any payment needs it. A payment that arrives first fails as\n * `PAYMENT_PROVIDER_UNAVAILABLE`, never as a rejection blamed on the buyer.\n */\nfunction cdpAuthHeaders(apiKeyId: string, apiKeySecret: string): AuthHeaderFactory {\n const loading = import('@coinbase/x402').then(\n (mod) => mod.createCdpAuthHeaders(apiKeyId, apiKeySecret),\n (cause: unknown) => {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.auth.type is \"cdp\", which needs the optional peer ' +\n '\"@coinbase/x402\". Install it (npm install @coinbase/x402), or use a facilitator ' +\n 'that accepts a static token with auth.type \"bearer\".',\n { cause },\n );\n },\n );\n // Nothing awaits this before the first call, so without a handler a failed\n // import would be an unhandled rejection at startup\n loading.catch(() => {});\n\n return async () => {\n const create = await loading;\n if (!create) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: @coinbase/x402 returned no auth-header factory',\n );\n }\n return (await create()) as Record<string, Record<string, string>>;\n };\n}\n\n/**\n * A 400 from `/verify` whose body names an `invalidReason` is the facilitator\n * refusing the payment, so it returns as an invalid verdict. The SDK throws it\n * as a `VerifyError`, which keeps the status and reason but not `isValid`.\n * A 400 without a reason and every other status, 401, 403, 429 and 5xx\n * included, are rethrown as \"no verdict\".\n */\nfunction verdictFromVerifyError(err: unknown): VerifyResponse {\n if (\n err instanceof VerifyError &&\n err.statusCode === 400 &&\n typeof err.invalidReason === 'string'\n ) {\n return {\n isValid: false,\n invalidReason: err.invalidReason,\n ...(err.payer !== undefined ? { payer: err.payer } : {}),\n };\n }\n throw err;\n}\n\n/**\n * Treat a remote 400 as a refusal only when it names a reason and no\n * transaction. A transaction may have broadcast; other errors have no\n * verdict. `SettleError` does not retain the response's `success`.\n */\nfunction verdictFromSettleError(err: unknown, network: Network): SettleResponse {\n if (\n err instanceof SettleError &&\n err.statusCode === 400 &&\n typeof err.errorReason === 'string' &&\n err.errorReason !== '' &&\n !err.transaction\n ) {\n return {\n success: false,\n errorReason: err.errorReason,\n transaction: '',\n network: err.network ?? network,\n ...(err.payer !== undefined ? { payer: err.payer } : {}),\n };\n }\n throw err;\n}\n\n/**\n * An HTTP facilitator. The SDK client produces the auth headers per request;\n * this module never logs them, and they appear neither in `/.well-known` nor\n * in `describe`.\n */\nexport function createRemoteFacilitatorBinding(\n options: RemoteFacilitatorOptions,\n): FacilitatorBinding {\n const auth = options.auth;\n let createAuthHeaders: AuthHeaderFactory | undefined;\n if (auth.type === 'bearer') {\n createAuthHeaders = async () => {\n // Path-keyed, as the SDK requires (see `AuthHeaderFactory`)\n const headers = { Authorization: `Bearer ${auth.token}` };\n return { verify: headers, settle: headers, supported: headers };\n };\n } else if (auth.type === 'cdp') {\n createAuthHeaders = cdpAuthHeaders(auth.apiKeyId, auth.apiKeySecret);\n }\n\n const client = new HTTPFacilitatorClient({\n url: options.url,\n timeoutMs: SETTLEMENT_CONFIRMATION_TIMEOUT_MS,\n ...(createAuthHeaders ? { createAuthHeaders } : {}),\n });\n const supportedClient = new HTTPFacilitatorClient({\n url: options.url,\n timeoutMs: SUPPORTED_TIMEOUT_MS,\n ...(createAuthHeaders ? { createAuthHeaders } : {}),\n });\n\n return {\n kind: 'remote',\n describe: `remote ${new URL(options.url).origin} (auth=${auth.type})`,\n open(): FacilitatorSession {\n let failed = false;\n const watch = async <T>(call: () => Promise<T>): Promise<T> => {\n try {\n return await call();\n } catch (err) {\n // After known 400 refusals, a throw gives no verdict. It may be\n // transport or authentication failure; settlement may have broadcast.\n // Do not record it as a payer refusal.\n failed = true;\n throw err;\n }\n };\n return {\n verify: (payload, requirements) =>\n watch(() => client.verify(payload, requirements).catch(verdictFromVerifyError)),\n settle: (payload, requirements) =>\n watch(() =>\n client\n .settle(payload, requirements)\n .catch((err: unknown) => verdictFromSettleError(err, requirements.network)),\n ),\n transportFailed: () => failed,\n };\n },\n supported: () => withDeadline(supportedClient.getSupported(), SUPPORTED_TIMEOUT_MS),\n };\n}\n\n// The SDK bounds each attempt but not its retry waits. `Promise.race` keeps\n// a handler on the abandoned call, so its later rejection is not unhandled.\nfunction withDeadline<T>(call: Promise<T>, ms: number): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: facilitator /supported did not answer within ${ms / 1000} s`,\n ),\n ),\n ms,\n );\n timer.unref();\n });\n return Promise.race([call, deadline]).finally(() => clearTimeout(timer));\n}\n","/**\n * In-process `x402Facilitator` using viem through `@x402/evm`.\n * EVM imports stay here so the remote binding can load without them.\n */\nimport { x402Facilitator } from '@x402/core/facilitator';\nimport type { Network } from '@x402/core/types';\nimport { toFacilitatorEvmSigner } from '@x402/evm';\nimport { registerExactEvmScheme } from '@x402/evm/exact/facilitator';\nimport type { LocalFacilitatorClient } from './chain';\nimport {\n type FacilitatorBinding,\n type FacilitatorSession,\n SETTLEMENT_CONFIRMATION_TIMEOUT_MS,\n} from './facilitator';\n\n/**\n * Registers `exact`/EVM for one network, so a payload naming another chain\n * finds no matching scheme\n */\nexport function createLocalFacilitatorBinding(\n client: LocalFacilitatorClient,\n network: string,\n isTransportError: (err: unknown) => boolean,\n): FacilitatorBinding {\n const build = (): { facilitator: x402Facilitator; failed: () => boolean } => {\n let failed = false;\n const watch = <T>(promise: Promise<T>): Promise<T> =>\n promise.catch((err: unknown) => {\n if (isTransportError(err)) failed = true;\n throw err;\n });\n\n // Watch the `FacilitatorEvmSigner` methods for transport failures and expose\n // `client.account.address` as the flat `address` the SDK expects\n const signer = {\n address: client.account.address,\n readContract: (args: Parameters<LocalFacilitatorClient['readContract']>[0]) =>\n watch(client.readContract(args)),\n verifyTypedData: (args: Parameters<LocalFacilitatorClient['verifyTypedData']>[0]) =>\n watch(client.verifyTypedData(args)),\n writeContract: (args: Parameters<LocalFacilitatorClient['writeContract']>[0]) =>\n watch(client.writeContract(args)),\n sendTransaction: (args: Parameters<LocalFacilitatorClient['sendTransaction']>[0]) =>\n watch(client.sendTransaction(args)),\n waitForTransactionReceipt: (\n args: Parameters<LocalFacilitatorClient['waitForTransactionReceipt']>[0],\n ) => watch(client.waitForTransactionReceipt(args)),\n getCode: (args: Parameters<LocalFacilitatorClient['getCode']>[0]) =>\n watch(client.getCode(args)),\n } as unknown as Parameters<typeof toFacilitatorEvmSigner>[0];\n\n // Bound receipt waits so a timeout returns `settlement_pending` with the\n // broadcast hash\n const facilitator = registerExactEvmScheme(new x402Facilitator(), {\n signer: toFacilitatorEvmSigner(signer, {\n confirmationTimeoutMs: SETTLEMENT_CONFIRMATION_TIMEOUT_MS,\n }),\n networks: network as Network,\n });\n\n return { facilitator, failed: () => failed };\n };\n\n return {\n kind: 'local',\n describe: 'local (in-process)',\n open(): FacilitatorSession {\n const { facilitator, failed } = build();\n return {\n verify: (payload, requirements) => facilitator.verify(payload, requirements),\n settle: (payload, requirements) => facilitator.settle(payload, requirements),\n transportFailed: failed,\n };\n },\n };\n}\n","/**\n * How the provider reads a facilitator's verify and settle results: which\n * reasons are verdicts, which leave the outcome unknown, and which errors mean\n * no verdict was obtained\n */\nimport {\n BaseError,\n ContractFunctionRevertedError,\n HttpRequestError,\n TimeoutError,\n WaitForTransactionReceiptTimeoutError,\n} from 'viem';\nimport { redactedErrorText } from '../../../core/errors';\n\n// `SettleResponse.errorReason` the SDK uses for \"broadcast, not confirmed\"\nexport const SETTLEMENT_PENDING_REASON = 'settlement_pending';\n/**\n * Each family's catch-all for a throw from the broadcast call, and its reason\n * for a transaction that failed on chain. Only the second carries a\n * transaction reference. A failure the SDK recognizes before the broadcast gets\n * its own reason instead. The EVM Permit2 path appends the thrown message as\n * `: <message>`. On NEAR the second is a failed inner `ft_transfer` receipt.\n */\nconst TRANSACTION_FAILED_REASONS = [\n 'invalid_exact_evm_transaction_failed',\n 'invalid_exact_svm_transaction_failed',\n 'settlement_failed',\n];\nexport const isTransactionFailedReason = (reason: string | undefined): boolean =>\n reason !== undefined &&\n TRANSACTION_FAILED_REASONS.some((known) => reason === known || reason.startsWith(`${known}:`));\n/**\n * The one failure reason per family that names a transaction and proves\n * nothing moved: a reverted EVM receipt, a Solana transaction that failed on\n * chain, or a failed inner NEAR `ft_transfer` receipt. Any other failure that\n * names a transaction may have moved funds. The EVM SDK, for one, reports a\n * mined transfer whose `Transfer` log it cannot match as a failure with the hash.\n */\nexport const ON_CHAIN_FAILURE_REASONS: Readonly<Record<'evm' | 'svm' | 'near', string>> = {\n evm: 'invalid_exact_evm_transaction_failed',\n svm: 'invalid_exact_svm_transaction_failed',\n near: 'settlement_failed',\n};\n/**\n * Solana outcomes that leave the payment unknown: the facilitator is already\n * settling the same transaction for another request, or it confirmed the\n * transaction but could not yet see the transfer\n */\nexport const UNKNOWN_OUTCOME_REASONS: ReadonlySet<string> = new Set([\n 'duplicate_settlement',\n 'post_settlement_transfer_not_confirmed',\n]);\n/**\n * Facilitator configuration and chain-read failures yield no payment verdict,\n * so they count as provider failures rather than buyer refusals. The NEAR SDK\n * returns its reasons before submission. The Solana ones compare the offer the\n * gateway sent with the facilitator's own fee payers, or with the buyer's\n * echo, which the gateway already matched.\n */\nexport const NO_VERDICT_REASONS: ReadonlySet<string> = new Set([\n 'unexpected_verify_error',\n 'invalid_exact_near_no_relayer_configured',\n 'invalid_exact_near_current_block_height_unavailable',\n 'invalid_exact_near_access_key_lookup_failed',\n 'invalid_exact_near_account_lookup_failed',\n 'invalid_exact_near_token_account_lookup_failed',\n 'invalid_exact_near_balance_check_failed',\n 'invalid_exact_near_storage_check_failed',\n 'invalid_exact_svm_payload_missing_fee_payer',\n 'invalid_exact_svm_fee_payer_not_managed_by_facilitator',\n 'invalid_exact_svm_unsupported_scheme',\n 'invalid_exact_svm_network_mismatch',\n]);\n/**\n * NEAR settle failures that are verdicts. The NEAR specification leaves the\n * reason implementation-specific and the transaction empty, even after a\n * submission, so only the SDK's verification reasons, returned before it\n * submits, and a failed inner `ft_transfer` with its hash prove nothing moved.\n */\nconst NEAR_PRE_SUBMISSION_REASONS: ReadonlySet<string> = new Set([\n 'invalid_x402_version',\n 'unsupported_scheme',\n 'invalid_network',\n 'insufficient_funds',\n 'verification_failed',\n]);\nexport const isNearVerdict = (reason: string | undefined): boolean =>\n reason !== undefined &&\n (reason === 'settlement_failed' ||\n reason.startsWith('invalid_exact_near_') ||\n NEAR_PRE_SUBMISSION_REASONS.has(reason));\n/**\n * `invalidReason`/`errorReason` are `z.string()` in the SDK schema, with no\n * length or charset bound. They reach the buyer's error, the persisted events\n * and the merchant's ledger. A remote facilitator controls these values, so\n * they are treated as untrusted input rather than diagnostic text.\n */\n// The SDKs' longest reason, a Solana compute-budget refusal, has 85 characters\nconst MAX_REASON_LENGTH = 128;\nconst REASON_SHAPE = /^[a-z0-9_.-]+$/i;\n\nexport function sanitizeReason(reason: string | undefined, fallback: string): string {\n if (reason === undefined) return fallback;\n const trimmed = reason.trim();\n if (trimmed.length === 0 || trimmed.length > MAX_REASON_LENGTH) return fallback;\n return REASON_SHAPE.test(trimmed) ? trimmed : fallback;\n}\n\n// viem wraps every failed contract call in ContractFunctionExecutionError, so\n// only the cause chain can show a revert. A revert alone does not prove nothing\n// moved, because viem also reports an RPC error on a send as one; settle()\n// relies on the SDK throwing only before the broadcast.\nexport function isOnChainRevertError(err: unknown): boolean {\n return (\n err instanceof BaseError && err.walk((e) => e instanceof ContractFunctionRevertedError) !== null\n );\n}\n\n/**\n * The `instanceof` checks cover what the pinned viem HTTP transport throws\n * (`HttpRequestError` for every fetch failure, including connection refused,\n * or `TimeoutError`) and what `waitForTransactionReceipt` throws when it stops\n * polling after a broadcast. Message matching is only a fallback for errors\n * outside those classes, such as a raw undici error, because message text can\n * change with any viem or undici upgrade.\n */\nexport function isProviderUnavailableError(err: unknown): boolean {\n if (\n err instanceof HttpRequestError ||\n err instanceof TimeoutError ||\n err instanceof WaitForTransactionReceiptTimeoutError\n ) {\n return true;\n }\n const message = redactedErrorText(err).toLowerCase();\n return (\n message.includes('econnrefused') ||\n message.includes('fetch failed') ||\n message.includes('enotfound') ||\n message.includes('etimedout') ||\n message.includes('timed out') ||\n message.includes('network error')\n );\n}\n","// Builds each offer from its options: validation, deployment guardrails and the facilitator binding\nimport type { Network } from '@x402/core/types';\nimport { isAddress } from 'viem';\nimport { CommerceError } from '../../../core';\nimport { normalizeAddress, sameAddress } from '../addresses';\nimport {\n createLocalFacilitatorClient,\n createLocalPublicClient,\n type LocalFacilitatorClient,\n} from '../chain';\nimport { assertDevKeyIsLocalOnly, assertPayToIsNotDevAddress, describeRpc } from '../dev-key-guard';\nimport { createRemoteFacilitatorBinding, type FacilitatorBinding } from '../facilitator';\nimport { resolveX402Deployment } from '../guardrails';\nimport { createLocalFacilitatorBinding } from '../local-facilitator';\nimport { type DeploymentMode, findX402Network } from '../networks';\nimport { HEALTH_TIMEOUT_MS } from './constants';\nimport { isProviderUnavailableError } from './reasons';\nimport type {\n Offer,\n X402MultiOfferProviderOptions,\n X402OfferOptions,\n X402ProviderOptions,\n} from './types';\n\n/**\n * Resolves provider and resource offers at construction, rejecting\n * misconfiguration before paid requests.\n */\nexport function resolveOffers(\n inputs: readonly X402OfferOptions[],\n options: X402ProviderOptions | X402MultiOfferProviderOptions,\n): {\n readonly offers: readonly Offer[];\n readonly resourceOffers: ReadonlyMap<string, readonly Offer[]>;\n /** Every distinct offer, the provider's first */\n readonly pool: readonly Offer[];\n readonly deploymentMode: DeploymentMode;\n readonly remoteBinding: FacilitatorBinding | undefined;\n} {\n // Share one remote binding, created after the first offer passes validation\n let remoteBinding: FacilitatorBinding | undefined;\n\n let mode: DeploymentMode | undefined;\n // An offer that several lists repeat is built, and health-checked, once\n const built = new Map<string, Offer>();\n const resolveList = (\n list: readonly X402OfferOptions[],\n field: (index: number, name: string) => string,\n ): readonly Offer[] => {\n const seen = new Set<string>();\n return list.map((input, index): Offer => {\n const at = (name: string) => field(index, name);\n // The network decides how the other fields are read. An unknown one\n // fails in `resolveX402Deployment` below.\n const known = findX402Network(input.network, options.customNetworks);\n if (known !== undefined && known.family !== 'evm') {\n const shape =\n known.family === 'svm' ? 'a Solana address (base58, 32 bytes)' : 'a NEAR account ID';\n for (const name of ['asset', 'payTo'] as const) {\n if (normalizeAddress(known, input[name]) === undefined) {\n throw new CommerceError('CONFIG_INVALID', `x402 provider: ${at(name)} is not ${shape}`);\n }\n }\n if (input.assetTransferMethod !== undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: ${at('assetTransferMethod')} applies to EVM networks only`,\n );\n }\n } else {\n // Neither address is echoed: a swapped variable could contain a key.\n // Check mixed-case EIP-55 checksums here; config load checks only shape.\n if (!isAddress(input.asset)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: ${at('asset')} is not a valid EVM address (0x and 40 hex characters; a mixed-case address needs a valid EIP-55 checksum)`,\n );\n }\n if (!isAddress(input.payTo)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: ${at('payTo')} is not a valid EVM address (0x and 40 hex characters; a mixed-case address needs a valid EIP-55 checksum)`,\n );\n }\n // In every facilitator mode. `resolveX402Deployment` below also refuses\n // a dev payTo on any non-local deployment, whatever the RPC host.\n assertPayToIsNotDevAddress(input.rpcUrl, input.payTo);\n // The buyer signs the token's EIP-712 domain under EIP-3009, so the\n // requirement must name it. Permit2 has a domain of its own.\n if (\n (input.assetTransferMethod ?? 'eip3009') === 'eip3009' &&\n (!input.assetName || !input.assetVersion)\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: an EIP-3009 offer needs ${at('assetName')} and ${at('assetVersion')}, the token's EIP-712 domain`,\n );\n }\n }\n if (!Number.isInteger(input.assetDecimals) || input.assetDecimals < 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: ${at('assetDecimals')} must be a non-negative integer`,\n );\n }\n // The chain id is signed into the buyer's EIP-712 domain, so a network it\n // cannot be resolved from fails here, never at request time\n const deployment = resolveX402Deployment({\n network: input.network,\n ...(options.customNetworks !== undefined ? { customNetworks: options.customNetworks } : {}),\n payTo: input.payTo,\n asset: input.asset,\n ...(input.assetName !== undefined ? { assetName: input.assetName } : {}),\n ...(input.assetVersion !== undefined ? { assetVersion: input.assetVersion } : {}),\n facilitator: options.facilitator,\n ...(options.allowMainnet !== undefined ? { allowMainnet: options.allowMainnet } : {}),\n ...(options.allowUnauthenticatedFacilitator !== undefined\n ? { allowUnauthenticatedFacilitator: options.allowUnauthenticatedFacilitator }\n : {}),\n // Every EVM offer names its decimals and, under EIP-3009, its domain\n allowOtherEvmToken: true,\n });\n const profile = deployment.profile;\n // Refuse offers mixing local, testnet and mainnet deployment modes\n if (mode !== undefined && deployment.mode !== mode) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: offers mix ${mode} and ${deployment.mode} networks; every offer must be on a ${mode} network`,\n );\n }\n mode = deployment.mode;\n // EVM addresses compare case-insensitively; Solana and NEAR exactly\n const comparable = (value: string) =>\n profile.family === 'evm' ? value.toLowerCase() : value;\n const key = `${input.network}|${comparable(input.asset)}|${comparable(input.payTo)}`;\n if (seen.has(key)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: ${at('network')} repeats an earlier offer of the same asset to the same payTo on ${input.network}`,\n );\n }\n seen.add(key);\n const identity = [\n key,\n input.assetTransferMethod ?? 'eip3009',\n input.assetName,\n input.assetVersion,\n input.assetDecimals,\n input.rpcUrl,\n ].join('|');\n const existing = built.get(identity);\n if (existing !== undefined) return existing;\n\n // Construct the signer before requests can reserve replay keys, so an\n // unusable key fails provider construction.\n let binding: FacilitatorBinding;\n if (options.facilitator.mode === 'local') {\n assertDevKeyIsLocalOnly(input.rpcUrl, options.facilitator.signerPrivateKey);\n let client: LocalFacilitatorClient;\n try {\n client = createLocalFacilitatorClient(\n input.rpcUrl,\n options.facilitator.signerPrivateKey as `0x${string}`,\n );\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: could not construct a local facilitator signer from ' +\n 'facilitator.signerPrivateKey. It must be a valid 32-byte hex private key.',\n { cause },\n );\n }\n binding = createLocalFacilitatorBinding(client, input.network, isProviderUnavailableError);\n } else {\n remoteBinding ??= createRemoteFacilitatorBinding({\n url: options.facilitator.url,\n auth: options.facilitator.auth,\n });\n binding = remoteBinding;\n }\n\n // health() reads the chain itself, with a timeout. Verification and\n // settlement go through the facilitator instead. Health details can reach\n // logs, so they name the RPC by origin.\n const base = {\n network: input.network as Network,\n assetDecimals: input.assetDecimals,\n rpcUrl: input.rpcUrl,\n rpcOrigin: describeRpc(input.rpcUrl),\n binding,\n };\n const offer: Offer =\n profile.family === 'svm'\n ? { ...base, family: 'svm', profile, asset: input.asset, payTo: input.payTo }\n : profile.family === 'near'\n ? { ...base, family: 'near', profile, asset: input.asset, payTo: input.payTo }\n : {\n ...base,\n family: 'evm',\n profile,\n method: input.assetTransferMethod ?? 'eip3009',\n asset: input.asset as `0x${string}`,\n assetName: input.assetName,\n assetVersion: input.assetVersion,\n payTo: input.payTo as `0x${string}`,\n healthClient: createLocalPublicClient(\n input.rpcUrl,\n HEALTH_TIMEOUT_MS,\n profile.chainId,\n ),\n };\n built.set(identity, offer);\n return offer;\n });\n };\n\n const offers = resolveList(inputs, (index, name) =>\n inputs.length === 1 ? `\"${name}\"` : `\"offers[${index}].${name}\"`,\n );\n const resourceOffers = new Map(\n Object.entries(options.resourceOffers ?? {}).map(([id, list]) => {\n if (list.length === 0) {\n throw new CommerceError('CONFIG_INVALID', `x402 provider: \"resourceOffers.${id}\" is empty`);\n }\n return [id, resolveList(list, (index, name) => `\"resourceOffers.${id}[${index}].${name}\"`)];\n }),\n );\n return {\n offers,\n resourceOffers,\n pool: [...built.values()],\n deploymentMode: mode as DeploymentMode,\n remoteBinding,\n };\n}\n\n/**\n * Uses the network's default token symbol when paying that asset; otherwise\n * uses the resource's currency, the gateway's only label for another token.\n */\nexport function offerCurrency(offer: Offer, quoted: string): string {\n const canonical = offer.profile.canonicalAsset;\n return canonical !== undefined && sameAddress(offer.profile, offer.asset, canonical.address)\n ? canonical.symbol\n : quoted;\n}\n","// RFC 8785 (JCS) serialization for request hashes\n\n// With the `u` flag, a valid surrogate pair is one code point, so this pattern\n// matches only lone surrogates\nconst LONE_SURROGATE = /\\p{Cs}/u;\n\n/**\n * Serializes JSON data using RFC 8785 (JCS) rules. Non-finite numbers, lone\n * surrogates and unsupported primitive values return undefined.\n * JSON.stringify supplies number formatting and string escaping; the default\n * sort orders keys by UTF-16 code units.\n */\nexport function canonicalJson(value: unknown): string | undefined {\n if (typeof value === 'string')\n return LONE_SURROGATE.test(value) ? undefined : JSON.stringify(value);\n if (typeof value === 'number') return Number.isFinite(value) ? JSON.stringify(value) : undefined;\n if (value === null || typeof value === 'boolean') return JSON.stringify(value);\n if (Array.isArray(value)) {\n const items = value.map(canonicalJson);\n return items.includes(undefined) ? undefined : `[${items.join(',')}]`;\n }\n if (typeof value !== 'object') return undefined;\n const members: string[] = [];\n for (const key of Object.keys(value).sort()) {\n const member = canonicalJson((value as Record<string, unknown>)[key]);\n if (member === undefined || LONE_SURROGATE.test(key)) return undefined;\n members.push(`${JSON.stringify(key)}:${member}`);\n }\n return `{${members.join(',')}}`;\n}\n","/**\n * Issues experimental ERC-8409 quotes when the provider enables `quote`.\n *\n * For requests that can be canonicalized, `extensions[\"erc-8409\"]` carries\n * one quote per EVM offer: chain, token, payee and amount in base units.\n * A dedicated issuer key signs the terms and request hash with EIP-712.\n * Quotes are informational; verify() and settle() use the offer without\n * reading the quotes.\n */\nimport { randomBytes } from 'node:crypto';\nimport { type Hex, keccak256, stringToBytes } from 'viem';\nimport { type PrivateKeyAccount, privateKeyToAccount } from 'viem/accounts';\nimport { type Clock, CommerceError } from '../../../core';\nimport { canonicalJson } from '../../../core/canonical-json';\nimport { isWellKnownDevKey } from '../dev-key-guard';\nimport type { DeploymentMode } from '../networks';\nimport type { EvmOffer, Offer } from './types';\n\n/** Key for quotes in `PaymentRequired.extensions` */\nexport const QUOTE_EXTENSION = 'erc-8409';\n\n/**\n * Request scheme for Keccak-256 hashes of the RFC 8785 (JCS) serialization of\n * `{ \"input\": <input>, \"resource\": <resource id> }`. The input is the validated\n * resource input used to build the backend request. The resource ID identifies\n * the operation and also names the MCP tool and A2A skill.\n */\nexport const QUOTE_REQUEST_SCHEME = 'agent-commerce/request/v1';\n\n/** The ERC's EIP-712 domain, with the chain ID added per quote */\nexport const QUOTE_DOMAIN = { name: 'Signed Service Payment Quotes', version: '1' } as const;\n\n/** The ERC's EIP-712 type; field order is part of the type hash */\nexport const QUOTE_TYPES = {\n ServicePaymentQuote: [\n { name: 'issuer', type: 'address' },\n { name: 'payer', type: 'address' },\n { name: 'recipient', type: 'address' },\n { name: 'asset', type: 'address' },\n { name: 'amount', type: 'uint256' },\n { name: 'requestScheme', type: 'string' },\n { name: 'requestHash', type: 'bytes32' },\n { name: 'quoteId', type: 'bytes32' },\n { name: 'validAfter', type: 'uint64' },\n { name: 'validUntil', type: 'uint64' },\n ],\n} as const;\n\n// A zero payer makes a bearer quote; the payment signature identifies the payer\nconst BEARER = '0x0000000000000000000000000000000000000000';\n\n// The JSON Schema x402 v2 requires beside each extension's `info`\nconst QUOTE_INFO_SCHEMA = {\n type: 'object',\n required: ['quotes'],\n properties: {\n quotes: {\n type: 'array',\n items: {\n type: 'object',\n required: ['chainId', 'quote', 'signature'],\n properties: {\n chainId: { type: 'string' },\n // Every field is a string in the ERC's JSON encoding\n quote: {\n type: 'object',\n required: QUOTE_TYPES.ServicePaymentQuote.map((field) => field.name),\n properties: Object.fromEntries(\n QUOTE_TYPES.ServicePaymentQuote.map((field) => [field.name, { type: 'string' }]),\n ),\n },\n signature: { type: 'string' },\n },\n },\n },\n },\n} as const;\n\n// Bound cache memory by evicting the oldest quote when the limit is reached\nconst QUOTE_CACHE_LIMIT = 1024;\n\n/** A quote in the ERC's JSON format, with integers as decimal strings */\nexport interface SignedQuote {\n readonly chainId: string;\n readonly quote: {\n readonly issuer: Hex;\n readonly payer: Hex;\n readonly recipient: Hex;\n readonly asset: Hex;\n readonly amount: string;\n readonly requestScheme: string;\n readonly requestHash: Hex;\n readonly quoteId: Hex;\n readonly validAfter: string;\n readonly validUntil: string;\n };\n readonly signature: Hex;\n}\n\n/** An EVM challenge offer and its `accepts` amount in base units */\nexport interface QuotedOffer {\n readonly offer: EvmOffer;\n readonly amount: string;\n}\n\nexport interface QuoteIssuer {\n readonly issuer: Hex;\n /**\n * Challenge extensions, or undefined when there are no EVM offers, input is\n * missing, or canonicalJson rejects the request\n */\n readonly extensionsFor: (\n resourceId: string,\n input: unknown,\n offers: readonly QuotedOffer[],\n ) => Promise<Record<string, unknown> | undefined>;\n}\n\n/**\n * Creates the issuer during provider construction. Rejects an invalid key,\n * a well-known Anvil key outside the local chain, a key matching an EVM\n * `payTo`, or a configuration without an EVM offer.\n */\nexport function createQuoteIssuer(options: {\n readonly signerPrivateKey: string;\n readonly offers: readonly Offer[];\n readonly deploymentMode: DeploymentMode;\n readonly clock: Clock;\n readonly maxTimeoutSeconds: number;\n}): QuoteIssuer {\n const { signerPrivateKey, offers, deploymentMode, clock, maxTimeoutSeconds } = options;\n let account: PrivateKeyAccount;\n try {\n account = privateKeyToAccount(signerPrivateKey as Hex);\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: quote.signerPrivateKey is not a valid private key (expected \"0x\" followed by 64 hex characters)',\n { cause },\n );\n }\n if (deploymentMode !== 'local' && isWellKnownDevKey(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: quote.signerPrivateKey is a well-known Anvil development key, so anyone could sign quotes as this gateway. Use a dedicated key outside the local chain.',\n );\n }\n const evmOffers = offers.filter((offer): offer is EvmOffer => offer.family === 'evm');\n if (evmOffers.length === 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: quote needs an EVM offer; ERC-8409 quotes cover EVM networks only',\n );\n }\n const issuer = account.address;\n if (evmOffers.some((offer) => offer.payTo.toLowerCase() === issuer.toLowerCase())) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: quote.signerPrivateKey controls a payTo address. Use a dedicated key, not the merchant wallet.',\n );\n }\n\n const cache = new Map<string, SignedQuote>();\n\n async function quoteFor(offer: EvmOffer, amount: string, requestHash: Hex): Promise<SignedQuote> {\n const now = Math.floor(clock.now().getTime() / 1000);\n const { chainId } = offer.profile;\n const key = [\n chainId,\n offer.payTo.toLowerCase(),\n offer.asset.toLowerCase(),\n amount,\n requestHash,\n ].join('|');\n const cached = cache.get(key);\n // Reuse a cached quote while a full payment window remains to avoid\n // signing retries; a cache miss requires a new signature\n if (cached !== undefined && Number(cached.quote.validUntil) - now >= maxTimeoutSeconds) {\n return cached;\n }\n const validUntil = now + 2 * maxTimeoutSeconds;\n const quote = {\n issuer,\n payer: BEARER,\n recipient: offer.payTo,\n asset: offer.asset,\n amount,\n requestScheme: QUOTE_REQUEST_SCHEME,\n requestHash,\n // Use a new ID for each signed body, as the ERC requires\n quoteId: `0x${randomBytes(32).toString('hex')}`,\n validAfter: String(now),\n validUntil: String(validUntil),\n } as const;\n const signature = await account.signTypedData({\n domain: { ...QUOTE_DOMAIN, chainId },\n types: QUOTE_TYPES,\n primaryType: 'ServicePaymentQuote',\n message: {\n ...quote,\n amount: BigInt(amount),\n validAfter: BigInt(now),\n validUntil: BigInt(validUntil),\n },\n });\n const signed: SignedQuote = { chainId: String(chainId), quote, signature };\n cache.delete(key);\n if (cache.size >= QUOTE_CACHE_LIMIT) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n cache.set(key, signed);\n return signed;\n }\n\n return {\n issuer,\n async extensionsFor(resourceId, input, quoted) {\n if (quoted.length === 0) return undefined;\n // Missing or non-canonicalizable input still gets a payment challenge\n // without quotes\n const requestHash = quoteRequestHash(resourceId, input);\n if (requestHash === undefined) return undefined;\n const quotes: SignedQuote[] = [];\n for (const { offer, amount } of quoted) {\n quotes.push(await quoteFor(offer, amount, requestHash));\n }\n return { [QUOTE_EXTENSION]: { info: { quotes }, schema: QUOTE_INFO_SCHEMA } };\n },\n };\n}\n\n/** Hash under {@link QUOTE_REQUEST_SCHEME}, or undefined when canonicalJson rejects the request */\nexport function quoteRequestHash(resourceId: string, input: unknown): Hex | undefined {\n const canonical = canonicalJson({ input, resource: resourceId });\n return canonical === undefined ? undefined : keccak256(stringToBytes(canonical));\n}\n","/**\n * Exact conversion from display amounts (\"0.01\" USDC) to the integer base\n * units x402 and EIP-3009 carry (\"10000\" at 6 decimals).\n *\n * It never goes through a JS `number`, which cannot represent most decimal\n * fractions. viem's `parseUnits` is not used either: it silently rounds excess\n * fractional digits, and \"0.0000001\" against a 6-decimal asset is a\n * configuration bug that must be refused, not rounded. The reverse direction\n * is viem's `formatUnits`, which is exact.\n */\nimport { CommerceError } from '../../core';\n\nconst DECIMAL_STRING_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\n/**\n * Parses a canonical decimal display amount (e.g. \"0.01\") into base units\n * for an asset with the given number of decimals, without floating point.\n *\n * Throws `CommerceError('PAYMENT_INVALID')` if the string is not a plain\n * non-negative decimal, or if it carries more fractional digits than the\n * asset supports.\n */\nexport function parseCanonicalAmount(amount: string, decimals: number): bigint {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new CommerceError('INTERNAL_ERROR', `Invalid asset decimals: ${decimals}`);\n }\n if (!DECIMAL_STRING_PATTERN.test(amount)) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" is not a valid non-negative decimal string`,\n {\n details: { amount },\n },\n );\n }\n\n const [integerPart = '0', fractionPart = ''] = amount.split('.');\n\n if (fractionPart.length > decimals) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" has more precision than the asset supports (${decimals} decimals)`,\n { details: { amount, assetDecimals: decimals } },\n );\n }\n\n const paddedFraction = fractionPart.padEnd(decimals, '0');\n const combined = `${integerPart}${paddedFraction}`;\n return BigInt(combined);\n}\n","/**\n * Decodes and validates the base64 `PAYMENT-SIGNATURE` submission.\n *\n * A malformed payload must become a `rejected` verification, never a thrown\n * request, so this returns `undefined` on any failure. That is why it parses\n * the schema itself instead of calling the SDK's `decodePaymentSignatureHeader`,\n * which throws.\n */\nimport { PaymentPayloadV2Schema } from '@x402/core/schemas';\nimport type { PaymentPayload } from '@x402/core/types';\nimport type { ExactEIP3009Payload, ExactPermit2Payload } from '@x402/evm';\nimport { isRecord } from '../../core/is-record';\nimport { isEvmAddress } from './addresses';\n\nexport function decodePaymentSubmission(payloadBase64: string): PaymentPayload | undefined {\n const json = decodeJson(payloadBase64);\n if (json === undefined) return undefined;\n const result = PaymentPayloadV2Schema.safeParse(json);\n return result.success ? (result.data as PaymentPayload) : undefined;\n}\n\n/** Read the declared version before v2 schema validation */\nexport function declaredX402Version(payloadBase64: string): unknown {\n const json = decodeJson(payloadBase64);\n return typeof json === 'object' && json !== null\n ? (json as Record<string, unknown>)['x402Version']\n : undefined;\n}\n\n/**\n * The payload as sent to a facilitator. `resource` is optional in v2 and\n * verify() has already matched it against the offer; hosted facilitators have\n * settled payloads without it, and none has been shown to accept this\n * gateway's `resource://` URL. `extensions` is dropped because quote echoes\n * are not used to verify payment, and a gas-sponsoring extension in a Permit2\n * payload would activate unsupported SDK facilitator behavior.\n */\nexport function forFacilitator<T extends PaymentPayload>(\n payload: T,\n): Omit<T, 'resource' | 'extensions'> {\n const { resource: _resource, extensions: _extensions, ...rest } = payload;\n return rest;\n}\n\nfunction decodeJson(payloadBase64: string): unknown {\n try {\n return JSON.parse(Buffer.from(payloadBase64, 'base64').toString('utf8'));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Narrows a decoded payload to the EIP-3009 `exact`/EVM shape.\n *\n * The SDK facilitator settles any payload carrying `permit2Authorization`\n * through Permit2, so a payload with both shapes is refused: the gateway would\n * check one authorization and the facilitator would settle the other.\n */\nexport function isExactEvmPayload(\n payload: PaymentPayload,\n): payload is PaymentPayload & { payload: ExactEIP3009Payload } {\n const inner = payload.payload;\n return (\n payload.accepted.scheme === 'exact' &&\n isRecord(inner) &&\n isRecord(inner['authorization']) &&\n !('permit2Authorization' in inner) &&\n typeof inner['signature'] === 'string'\n );\n}\n\n// A uint256 in decimal, the form the SDK client writes\nconst UINT256 = /^(0|[1-9]\\d{0,77})$/;\nconst UINT256_MAX = 2n ** 256n - 1n;\n// An EIP-3009 nonce: 32 bytes in hex\nconst BYTES32 = /^0x[0-9a-fA-F]{64}$/;\n\nconst isUint256 = (value: unknown): value is string =>\n typeof value === 'string' && UINT256.test(value) && BigInt(value) <= UINT256_MAX;\n\n/**\n * Checks an EIP-3009 authorization's fields in the forms the SDK client and\n * mppx write: addresses, decimal uint256 strings and a 32-byte hex nonce. A\n * value such as `\"0x2710\"` would otherwise reach the receipt as written.\n */\nexport function hasEip3009Fields(authorization: Readonly<Record<string, unknown>>): boolean {\n return (\n isEvmAddress(authorization['from']) &&\n isEvmAddress(authorization['to']) &&\n isUint256(authorization['value']) &&\n isUint256(authorization['validAfter']) &&\n isUint256(authorization['validBefore']) &&\n typeof authorization['nonce'] === 'string' &&\n BYTES32.test(authorization['nonce'])\n );\n}\n\n/**\n * Checks the Permit2 `exact`/EVM fields used to match the offer and derive\n * the replay key. The facilitator checks the signature and on-chain state.\n */\nexport function isExactPermit2Payload(\n payload: PaymentPayload,\n): payload is PaymentPayload & { payload: ExactPermit2Payload } {\n const inner = payload.payload;\n if (payload.accepted.scheme !== 'exact' || !isRecord(inner)) return false;\n const auth = inner['permit2Authorization'];\n if (!isRecord(auth) || 'authorization' in inner || typeof inner['signature'] !== 'string') {\n return false;\n }\n const { permitted, witness } = auth;\n return (\n isRecord(permitted) &&\n isRecord(witness) &&\n isEvmAddress(auth['from']) &&\n isEvmAddress(auth['spender']) &&\n isEvmAddress(permitted['token']) &&\n isEvmAddress(witness['to']) &&\n isUint256(permitted['amount']) &&\n isUint256(auth['nonce']) &&\n isUint256(auth['deadline']) &&\n isUint256(witness['validAfter'])\n );\n}\n","// The challenge a resource answers with, and the offer a proof selects from it\nimport type { PaymentRequired, PaymentRequirements } from '@x402/core/types';\nimport type { PaymentContext, PaymentRequirement, PaymentVerificationContext } from '../../../core';\nimport {\n REUSE_REJECTED_AUTHORIZATION_METADATA_KEY,\n SETTLE_AFTER_BACKEND_METADATA_KEY,\n} from '../../../core/execution/settlement-order';\nimport { sameAddress } from '../addresses';\nimport { parseCanonicalAmount } from '../amount';\nimport type { X402Network } from '../networks';\nimport { decodePaymentSubmission } from '../payload';\nimport { X402_DEFAULT_PAYMENT_FLOW } from '../payment-flow';\nimport { DEFAULT_MIME_TYPE, X402_PROTOCOL_VERSION, X402_VERSION } from './constants';\nimport type { ProviderContext, SvmOffer } from './types';\n\n// Requirement metadata naming the offer `selectRequirement` chose, by index\nexport const SELECTED_OFFER_KEY = 'x402.offer';\n\n// Use the selected or sole offer; multi-offer challenges require selection\nexport function offerIndexOf(requirement: PaymentRequirement): number | undefined {\n const selected = requirement.metadata?.[SELECTED_OFFER_KEY];\n if (typeof selected === 'number') return selected;\n // An empty list falls through to 'missing_payment_requirements'\n return requirement.challenge.accepts.length <= 1 ? 0 : undefined;\n}\n\n/**\n * Match echoed terms against the offer. Extra client keys and\n * `maxTimeoutSeconds` do not matter; EVM addresses ignore case, Solana's do\n * not. Compare effective payment flows so an upfront proof cannot pay a default\n * authorization offer.\n */\nexport function acceptedMatchesOffer(\n offered: PaymentRequirements,\n accepted: PaymentRequirements,\n network: X402Network | undefined,\n): boolean {\n if (!network) return false;\n const same = (a: string, b: string) => sameAddress(network, a, b);\n const offeredExtra = offered.extra ?? {};\n const acceptedExtra = accepted.extra ?? {};\n const flow = (extra: Record<string, unknown>) =>\n extra['paymentFlow'] ?? X402_DEFAULT_PAYMENT_FLOW;\n return (\n accepted.scheme === offered.scheme &&\n accepted.network === offered.network &&\n accepted.amount === offered.amount &&\n same(accepted.asset, offered.asset) &&\n same(accepted.payTo, offered.payTo) &&\n Object.entries(offeredExtra).every(([key, value]) => acceptedExtra[key] === value) &&\n flow(acceptedExtra) === flow(offeredExtra)\n );\n}\n\n/** Builds the provider's `createRequirement` and `selectRequirement` */\nexport function createRequirementBuilders(\n ctx: ProviderContext,\n svmFeePayer: (offer: SvmOffer) => Promise<string>,\n): {\n readonly createRequirement: (context: PaymentContext) => Promise<PaymentRequirement>;\n readonly selectRequirement: (context: PaymentVerificationContext) => Promise<PaymentRequirement>;\n} {\n const { options, offersFor, clock, ids, maxTimeoutSeconds } = ctx;\n\n async function createRequirement(context: PaymentContext): Promise<PaymentRequirement> {\n const offers = offersFor(context.resource.id);\n const paymentFlow =\n options.resourcePaymentFlows?.[context.resource.id] ??\n options.paymentFlow ??\n X402_DEFAULT_PAYMENT_FLOW;\n\n // x402 requires an explicit non-default flow. Omit the default\n // `authorization` flow here.\n const flow = paymentFlow === 'upfront' ? { paymentFlow } : {};\n const accepts: PaymentRequirements[] = await Promise.all(\n offers.map(async (offer) => ({\n scheme: 'exact',\n network: offer.network,\n asset: offer.asset,\n amount: parseCanonicalAmount(context.amount, offer.assetDecimals).toString(),\n payTo: offer.payTo,\n maxTimeoutSeconds,\n // EIP-3009 needs `name`/`version` for a shared EIP-712 domain without\n // a token `version()` call; Permit2 uses its own domain. EVM clients\n // sign the named `assetTransferMethod`. Solana needs the facilitator's\n // fee payer; NEAR needs no scheme-specific extra because the\n // facilitator chooses its relayer.\n extra:\n offer.family === 'svm'\n ? { feePayer: await svmFeePayer(offer), ...flow }\n : offer.family === 'near'\n ? { ...flow }\n : {\n ...(offer.assetName !== undefined ? { name: offer.assetName } : {}),\n ...(offer.assetVersion !== undefined ? { version: offer.assetVersion } : {}),\n assetTransferMethod: offer.method,\n ...flow,\n },\n })),\n );\n const single = offers.length === 1 ? offers[0] : undefined;\n const extensions = await ctx.quotes?.extensionsFor(\n context.resource.id,\n context.input,\n offers.flatMap((offer, index) => {\n const accepted = accepts[index];\n return offer.family === 'evm' && accepted ? [{ offer, amount: accepted.amount }] : [];\n }),\n );\n\n // The v2 challenge document as sent on the wire. The HTTP adapter\n // base64-encodes it into `PAYMENT-REQUIRED` and MCP passes it through, so\n // both surfaces offer the same challenge.\n //\n // `resource.url` is outside the EIP-3009 signature. A single offer puts its\n // network and payee in it, so the buyer's echo identifies the offer. With\n // several, the URL stays the same whichever one the buyer pays.\n const resourceId = encodeURIComponent(context.resource.id);\n const envelope: PaymentRequired = {\n x402Version: X402_VERSION,\n resource: {\n url: single\n ? `resource://agent-commerce/${encodeURIComponent(single.network)}/${single.payTo}/resources/${resourceId}`\n : `resource://agent-commerce/resources/${resourceId}`,\n description: context.resource.description ?? context.resource.name,\n // The media type the merchant declares, else `application/json`; an HTTP\n // delivery carries the backend's own type when it is text and fits the body\n mimeType: options.resourceMimeTypes?.[context.resource.id] ?? DEFAULT_MIME_TYPE,\n },\n accepts,\n ...(extensions !== undefined ? { extensions } : {}),\n };\n\n const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString();\n\n return {\n id: ids.next('payreq'),\n requestId: context.requestId,\n resourceId: context.resource.id,\n provider: 'x402',\n amount: context.amount,\n currency: context.currency,\n // Several offers name several destinations; selection fills these in\n ...(single\n ? { destination: single.payTo, network: single.network, asset: single.asset }\n : {}),\n expiresAt,\n challenge: {\n provider: 'x402',\n version: X402_PROTOCOL_VERSION,\n accepts: accepts as unknown as Record<string, unknown>[],\n envelope: envelope as unknown as Record<string, unknown>,\n },\n metadata: {\n [SETTLE_AFTER_BACKEND_METADATA_KEY]: paymentFlow === 'authorization',\n // The SDK server keeps no record of a payload whose handler or\n // settlement failed and verifies it again; the chain spends it once\n [REUSE_REJECTED_AUTHORIZATION_METADATA_KEY]: true,\n },\n };\n }\n\n /**\n * Selects the unique offer matching `accepted`, leaving zero or multiple\n * matches unchanged for `verify()` to reject. Selection identifies the\n * claimed offer; verification still validates the proof.\n */\n async function selectRequirement(\n context: PaymentVerificationContext,\n ): Promise<PaymentRequirement> {\n const { requirement, submission } = context;\n const offered = requirement.challenge.accepts as unknown as PaymentRequirements[];\n if (offered.length < 2) return requirement;\n const offers = offersFor(requirement.resourceId);\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload) return requirement;\n const matches = offered.flatMap((offer, index) =>\n acceptedMatchesOffer(offer, payload.accepted, offers[index]?.profile) ? [index] : [],\n );\n const index = matches.length === 1 ? matches[0] : undefined;\n const offer = index === undefined ? undefined : offers[index];\n if (index === undefined || !offer) return requirement;\n return {\n ...requirement,\n destination: offer.payTo,\n network: offer.network,\n asset: offer.asset,\n metadata: { ...requirement.metadata, [SELECTED_OFFER_KEY]: index },\n };\n }\n\n return { createRequirement, selectRequirement };\n}\n","// What an EVM payload authorizes: payer, payee, amount and replay key\n\nimport type { PaymentPayload } from '@x402/core/types';\nimport { x402ExactPermit2ProxyAddress } from '@x402/evm';\nimport { getAddress, isAddress } from 'viem';\nimport { hasEip3009Fields, isExactEvmPayload, isExactPermit2Payload } from '../payload';\nimport { computePermit2ReplayKey, computeReplayKey } from '../replay-key';\nimport type { EvmOffer } from './types';\n\n// What a payload authorizes, read the way the offer's method settles it\nexport interface Transfer {\n readonly from: `0x${string}`;\n readonly to: `0x${string}`;\n readonly value: string;\n readonly replayKey: string;\n readonly recipientMismatch: string;\n readonly amountMismatch: string;\n}\n\n/**\n * Reads the payer, payee, amount and replay key, or returns a refusal reason.\n * Enforces the offer's method because the SDK facilitator chooses the method\n * from the payload.\n */\nexport function readTransfer(payload: PaymentPayload, offer: EvmOffer): Transfer | string {\n // verify() refuses an `accepted.network` other than the offer's, so this\n // chain id is the one the authorization is bound to\n const { chainId } = offer.profile;\n if (offer.method === 'eip3009') {\n if (!isExactEvmPayload(payload)) return 'unsupported_scheme';\n const { authorization } = payload.payload;\n const { from, to, value, nonce } = authorization;\n if (!hasEip3009Fields(authorization) || !isAddress(from) || !isAddress(to)) {\n return 'invalid_payload';\n }\n return {\n from: getAddress(from),\n to: getAddress(to),\n value,\n replayKey: computeReplayKey({\n chainId,\n asset: getAddress(offer.asset),\n from: getAddress(from),\n nonce,\n }),\n recipientMismatch: 'invalid_exact_evm_payload_recipient_mismatch',\n amountMismatch: 'invalid_exact_evm_payload_authorization_value_mismatch',\n };\n }\n if (!isExactPermit2Payload(payload)) return 'unsupported_scheme';\n const { from, spender, permitted, witness, nonce } = payload.payload.permit2Authorization;\n // Permit2 lets the spender move the permitted tokens anywhere; only the x402\n // proxy binds the transfer to the signed witness recipient\n if (getAddress(spender) !== getAddress(x402ExactPermit2ProxyAddress)) {\n return 'invalid_permit2_spender';\n }\n if (getAddress(permitted.token) !== getAddress(offer.asset)) return 'permit2_token_mismatch';\n return {\n from: getAddress(from),\n to: getAddress(witness.to),\n value: permitted.amount,\n replayKey: computePermit2ReplayKey({ chainId, owner: getAddress(from), nonce }),\n recipientMismatch: 'invalid_permit2_recipient_mismatch',\n amountMismatch: 'permit2_amount_mismatch',\n };\n}\n","// Settles a verified proof and classifies the facilitator's answer\nimport type { PaymentRequirements, SettleResponse } from '@x402/core/types';\nimport type { PaymentResult, PaymentSettlementContext } from '../../../core';\nimport { CommerceError } from '../../../core';\nimport { redactedErrorText } from '../../../core/errors';\nimport { isTransactionReference } from '../addresses';\nimport { decodePaymentSubmission, forFacilitator } from '../payload';\nimport {\n isNearVerdict,\n isOnChainRevertError,\n isProviderUnavailableError,\n isTransactionFailedReason,\n NO_VERDICT_REASONS,\n ON_CHAIN_FAILURE_REASONS,\n SETTLEMENT_PENDING_REASON,\n sanitizeReason,\n UNKNOWN_OUTCOME_REASONS,\n} from './reasons';\nimport { offerIndexOf } from './requirement';\nimport { readTransfer } from './transfer';\nimport type { ProviderContext } from './types';\n\n/** Builds the provider's `settle`, which throws unless handed a successful verification */\nexport function createSettle(\n ctx: ProviderContext,\n): (context: PaymentSettlementContext) => Promise<PaymentResult> {\n const { offersFor, clock, logger } = ctx;\n\n async function settle(context: PaymentSettlementContext): Promise<PaymentResult> {\n const { requirement, submission, verification } = context;\n\n if (verification.status !== 'verified') {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() called without a successful verify()',\n );\n }\n\n const index = offerIndexOf(requirement);\n const offer = index === undefined ? undefined : offersFor(requirement.resourceId)[index];\n const requirements =\n index === undefined\n ? undefined\n : (requirement.challenge.accepts[index] as PaymentRequirements | undefined);\n if (!offer || !requirements) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() found no payment requirements to settle against',\n );\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n const transfer = payload && offer.family === 'evm' ? readTransfer(payload, offer) : undefined;\n if (!payload || typeof transfer === 'string') {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() received an undecodable payment payload',\n );\n }\n const reference = (value: string) => isTransactionReference(offer.profile, value);\n\n const rejectedSettlement = (rejectionReason: string): PaymentResult => ({\n status: 'rejected',\n provider: 'x402',\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.network !== undefined ? { network: verification.network } : {}),\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n rejectionReason,\n });\n\n const scope = offer.binding.open();\n let sdkResult: SettleResponse;\n try {\n sdkResult = await scope.settle(forFacilitator(payload), requirements);\n } catch (err) {\n if (isProviderUnavailableError(err) || scope.transportFailed()) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${offer.binding.kind} facilitator unreachable during settle()`,\n { cause: err },\n );\n }\n // The pinned SDK returns a result for every failure from gas estimation\n // on, so a throw comes from its checks before anything is sent. A revert\n // there is a real rejection, which releases any mandate the pipeline\n // holds for the purchase. Any other throw goes back as an unavailable\n // provider, which the pipeline records as `settlement-uncertain`, never\n // as a rejection blamed on the buyer.\n if (!isOnChainRevertError(err)) {\n logger.warn(\n { err: redactedErrorText(err) },\n 'x402 settle(): settlement failed with an unclassified error; outcome unknown',\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: settlement failed with an unclassified error; outcome unknown',\n { cause: err },\n );\n }\n logger.warn(\n { err: redactedErrorText(err), rejectionReason: 'transaction_reverted' },\n 'x402 settle(): settlement transaction reverted on chain',\n );\n return rejectedSettlement('transaction_reverted');\n }\n\n // verify() established the payer. The Solana scheme's settlement example\n // names the fee payer there, while x402 v2 defines the payer's wallet.\n const payer = verification.payer ?? sdkResult.payer;\n\n if (!sdkResult.success) {\n // \"Broadcast, never confirmed\" is not \"did not happen\": the transfer may\n // be on-chain, so it throws as an unavailable provider carrying the hash,\n // and the pipeline records the attempt `settlement-uncertain`, not\n // `rejected`. The SDK's catch-all without a hash is treated the same way,\n // because its throw may have followed a broadcast and viem reports an\n // RPC error on the send as a revert.\n if (isTransactionFailedReason(sdkResult.errorReason) && !reference(sdkResult.transaction)) {\n // The appended message can carry an RPC URL\n logger.warn(\n { reportedReason: redactedErrorText(sdkResult.errorReason) },\n 'x402 settle(): the broadcast failed without a transaction hash; outcome unknown',\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: settlement failed with an unclassified error; outcome unknown',\n );\n }\n // These NEAR SDK checks fail before submission. Release the attempt so\n // a retry using the same access-key nonce can reserve it again.\n if (\n offer.family === 'near' &&\n NO_VERDICT_REASONS.has(sdkResult.errorReason ?? '') &&\n !sdkResult.transaction\n ) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: the facilitator could not check the payment before submitting it',\n {\n details: {\n settlementNotSubmitted: true,\n reason: sanitizeReason(sdkResult.errorReason, 'facilitator_unavailable'),\n },\n },\n );\n }\n // A broadcast the SDK could not confirm nor record for a retry comes\n // back as its catch-all with the transaction, and a message starting\n // `settlement_pending`\n if (\n sdkResult.errorReason === SETTLEMENT_PENDING_REASON ||\n sdkResult.errorMessage?.startsWith(SETTLEMENT_PENDING_REASON) === true ||\n UNKNOWN_OUTCOME_REASONS.has(sdkResult.errorReason ?? '') ||\n NO_VERDICT_REASONS.has(sdkResult.errorReason ?? '') ||\n scope.transportFailed()\n ) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: settlement was broadcast but could not be confirmed',\n {\n ...(sdkResult.transaction\n ? { details: { transactionHash: sdkResult.transaction } }\n : {}),\n },\n );\n }\n // Only the family's on-chain failure proves a named transaction moved\n // nothing. Any other reason may follow a transfer that landed.\n if (\n sdkResult.transaction &&\n sdkResult.errorReason !== ON_CHAIN_FAILURE_REASONS[offer.family]\n ) {\n logger.warn(\n { reportedReason: redactedErrorText(sdkResult.errorReason ?? '') },\n 'x402 settle(): the facilitator reported a failure with a transaction; outcome unknown',\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: the facilitator reported a failed settlement with a transaction; outcome unknown',\n { details: { transactionHash: sdkResult.transaction } },\n );\n }\n // A `settlement_failed` that reaches here carries its hash\n if (offer.family === 'near' && !isNearVerdict(sdkResult.errorReason)) {\n logger.warn(\n { reportedReason: redactedErrorText(sdkResult.errorReason ?? '') },\n 'x402 settle(): NEAR facilitator failure reason is not a verdict; outcome unknown',\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: settlement failed with an unclassified error; outcome unknown',\n );\n }\n if (sdkResult.errorReason !== undefined) {\n logger.debug(\n { reportedReason: redactedErrorText(sdkResult.errorReason) },\n 'x402 settle(): facilitator failure reason',\n );\n }\n return {\n ...rejectedSettlement(sanitizeReason(sdkResult.errorReason, 'settlement_failed')),\n network: sdkResult.network,\n ...(payer !== undefined ? { payer } : {}),\n // The failed transaction, which the facilitator paid for\n ...(sdkResult.transaction ? { externalReference: sdkResult.transaction } : {}),\n };\n }\n\n // A success names the offer's network and a transaction in its family's\n // form; anything else unlocks nothing, and the outcome stays unknown\n if (!reference(sdkResult.transaction) || sdkResult.network !== offer.network) {\n logger.warn(\n { network: sdkResult.network },\n 'x402 settle(): the facilitator reported a success it did not identify; outcome unknown',\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: the facilitator reported a settlement without a valid transaction; outcome unknown',\n );\n }\n\n return {\n status: 'settled',\n provider: 'x402',\n externalReference: sdkResult.transaction,\n ...(payer !== undefined ? { payer } : {}),\n payee: requirements.payTo,\n amount: verification.amount,\n currency: verification.currency,\n network: sdkResult.network,\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n settledAt: clock.nowIso(),\n // `amount` is the display value; x402's settlement response reports base\n // units. verify() matched an EVM authorization's value to the offer.\n metadata: {\n amountBaseUnits: transfer?.value ?? requirements.amount,\n // The resource's own price, when it names a currency other than the token\n ...(verification.currency !== requirement.currency\n ? { quote: { amount: requirement.amount, currency: requirement.currency } }\n : {}),\n },\n };\n }\n\n return settle;\n}\n","// Checks a proof against the offer it pays, then asks the facilitator for a verdict\nimport type { PaymentRequired, PaymentRequirements, VerifyResponse } from '@x402/core/types';\nimport { formatUnits, getAddress } from 'viem';\nimport type { PaymentResult, PaymentVerificationContext } from '../../../core';\nimport { CommerceError } from '../../../core';\nimport { redactedErrorText } from '../../../core/errors';\nimport { normalizeAddress, sameAddress } from '../addresses';\nimport { declaredX402Version, decodePaymentSubmission, forFacilitator } from '../payload';\nimport { X402_VERSION } from './constants';\nimport { offerCurrency } from './offers';\nimport { isProviderUnavailableError, NO_VERDICT_REASONS, sanitizeReason } from './reasons';\nimport { acceptedMatchesOffer, offerIndexOf } from './requirement';\nimport { readTransfer, type Transfer } from './transfer';\nimport type { ProviderContext } from './types';\n\n/** Builds the provider's `verify`, which never moves funds */\nexport function createVerify(\n ctx: ProviderContext,\n): (context: PaymentVerificationContext) => Promise<PaymentResult> {\n const { offersFor, clock, logger, svm, near } = ctx;\n\n /**\n * Checks a submission against the requirement this provider built, never\n * against `payload.accepted`, the copy the client echoes back. That copy\n * must itself match the offer, or the proof is refused.\n *\n * The `exact` scheme requires the authorized amount to match exactly,\n * including when the buyer offers more. Local refusals use x402 error codes\n * where available.\n */\n async function verify(context: PaymentVerificationContext): Promise<PaymentResult> {\n const { requirement, submission } = context;\n\n const rejected = (reason: string): PaymentResult => ({\n status: 'rejected',\n provider: 'x402',\n amount: requirement.amount,\n currency: requirement.currency,\n ...(requirement.network !== undefined ? { network: requirement.network } : {}),\n ...(requirement.asset !== undefined ? { asset: requirement.asset } : {}),\n rejectionReason: reason,\n });\n\n if (requirement.provider !== 'x402' || requirement.challenge.provider !== 'x402') {\n return rejected('wrong_provider');\n }\n\n // With several offers and none selected, the proof matched no single offer\n const index = offerIndexOf(requirement);\n if (index === undefined) {\n return rejected('invalid_payment_requirements');\n }\n const offer = offersFor(requirement.resourceId)[index];\n const requirements = requirement.challenge.accepts[index] as PaymentRequirements | undefined;\n if (!offer || !requirements) {\n return rejected('missing_payment_requirements');\n }\n\n // Defense in depth only: the pipeline builds a fresh requirement for every\n // request, so this rarely fires. The real expiry is the authorization's\n // own, which the facilitator checks.\n if (\n requirement.expiresAt !== undefined &&\n Date.parse(requirement.expiresAt) < clock.now().getTime()\n ) {\n return rejected('requirement_expired');\n }\n\n // This provider built the requirement, so the asset always matches in\n // normal operation. A corrupted one must still never authorize a transfer\n // of a different asset.\n if (!sameAddress(offer.profile, requirements.asset, offer.asset)) {\n return rejected('wrong_asset');\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload) {\n const version = declaredX402Version(submission.payload);\n return rejected(\n typeof version === 'number' && version !== X402_VERSION\n ? 'invalid_x402_version'\n : 'invalid_payload',\n );\n }\n if (payload.x402Version !== X402_VERSION) {\n return rejected('invalid_x402_version');\n }\n // EVM: the authorization names payer, payee and amount. Solana: the\n // facilitator reads the transaction, and the gateway takes its identity.\n // NEAR: the delegate names the transfer, checked here against the offer.\n let transfer: Transfer | undefined;\n let replayKey: string;\n let derivedPayer: string | undefined;\n if (offer.family === 'svm') {\n const identity = (await svm()).svmReplayKey(payload.payload, offer.network);\n if (typeof identity === 'string') return rejected(identity);\n replayKey = identity.replayKey;\n } else if (offer.family === 'near') {\n const inspected = (await near()).inspectNearPayload(payload.payload, {\n network: offer.network,\n asset: offer.asset,\n payTo: offer.payTo,\n amount: requirements.amount,\n });\n if (typeof inspected === 'string') return rejected(inspected);\n replayKey = inspected.replayKey;\n derivedPayer = inspected.payer;\n } else {\n const read = readTransfer(payload, offer);\n if (typeof read === 'string') return rejected(read);\n transfer = read;\n replayKey = read.replayKey;\n derivedPayer = read.from;\n }\n // Reject a different network before calling the facilitator. NEAR's\n // delegate signature itself does not bind the chain.\n if (payload.accepted.network !== offer.network) {\n return rejected('invalid_network');\n }\n // The signature omits flow and resource. Check the echoed offer;\n // `resource` is optional, but must match when present.\n const offeredUrl = (requirement.challenge.envelope as PaymentRequired | undefined)?.resource\n ?.url;\n if (\n !acceptedMatchesOffer(requirements, payload.accepted, offer.profile) ||\n (payload.resource !== undefined && payload.resource.url !== offeredUrl)\n ) {\n return rejected('invalid_payment_requirements');\n }\n let required: bigint;\n try {\n required = BigInt(requirements.amount);\n } catch {\n return rejected('invalid_payload');\n }\n if (transfer) {\n if (transfer.to !== getAddress(offer.payTo)) {\n return rejected(transfer.recipientMismatch);\n }\n let authorizedValue: bigint;\n try {\n authorizedValue = BigInt(transfer.value);\n } catch {\n return rejected('invalid_payload');\n }\n if (authorizedValue !== required) {\n return rejected(transfer.amountMismatch);\n }\n }\n\n const scope = offer.binding.open();\n let sdkResult: VerifyResponse;\n try {\n sdkResult = await scope.verify(forFacilitator(payload), requirements);\n } catch (err) {\n // A throw means no verdict was obtained, so it is never held against the\n // buyer. Only an unclassified one is logged, as it may be an SDK fault.\n if (!isProviderUnavailableError(err) && !scope.transportFailed()) {\n logger.warn({ err: redactedErrorText(err) }, 'x402 verify(): unexpected SDK error');\n }\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${offer.binding.kind} facilitator returned no verdict during verify()`,\n { cause: err },\n );\n }\n\n if (!sdkResult.isValid) {\n // An RPC that never answered is not a payment that failed a check\n if (scope.transportFailed() || NO_VERDICT_REASONS.has(sdkResult.invalidReason ?? '')) {\n if (sdkResult.invalidReason !== undefined) {\n logger.debug(\n { reportedReason: redactedErrorText(sdkResult.invalidReason) },\n 'x402 verify(): local facilitator transport failure reason',\n );\n }\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${offer.binding.kind} facilitator unreachable during verify()`,\n );\n }\n // The raw reason is logged at debug level. Only what the buyer sees and\n // the ledger records is constrained.\n if (sdkResult.invalidReason !== undefined) {\n logger.debug(\n { reportedReason: redactedErrorText(sdkResult.invalidReason) },\n 'x402 verify(): facilitator rejection reason',\n );\n }\n return rejected(sanitizeReason(sdkResult.invalidReason, 'invalid_payment'));\n }\n\n // The Solana payer is the facilitator's reading of the transaction\n const payer =\n derivedPayer ??\n (sdkResult.payer !== undefined && normalizeAddress(offer.profile, sdkResult.payer)\n ? sdkResult.payer\n : undefined);\n return {\n status: 'verified',\n provider: 'x402',\n ...(payer !== undefined ? { payer } : {}),\n payee: transfer?.to ?? offer.payTo,\n amount: formatUnits(required, offer.assetDecimals),\n currency: offerCurrency(offer, requirement.currency),\n network: payload.accepted.network,\n asset: offer.family === 'evm' ? getAddress(requirements.asset) : offer.asset,\n replayKey,\n };\n }\n\n return verify;\n}\n","/**\n * x402 payment provider: protocol v2, `exact` scheme. On EVM the buyer signs an\n * EIP-3009 `transferWithAuthorization` or a Permit2 transfer through the x402\n * exact proxy; on Solana, a token transfer whose fee the facilitator pays; on\n * NEAR, a delegated NEP-141 `ft_transfer` that the facilitator's relayer\n * submits.\n *\n * `verify()` never moves funds. `settle()` does, and throws unless it is handed\n * a successful verification. Both run through a facilitator (see\n * `../facilitator.ts`): the SDK's own `x402Facilitator` in this process, or a\n * remote HTTP facilitator.\n */\nimport type { AdapterDescriptor } from '../../../core';\nimport { CommerceError, NOOP_LOGGER, systemClock } from '../../../core';\nimport { PACKAGE_VERSION } from '../../../version';\nimport { DEFAULT_IDS, DEFAULT_MAX_TIMEOUT_SECONDS, X402_VERSION } from './constants';\nimport { createSvmFeePayerSource } from './fee-payer';\nimport { createHealthCheck } from './health';\nimport { resolveOffers } from './offers';\nimport { createQuoteIssuer, QUOTE_EXTENSION, QUOTE_REQUEST_SCHEME } from './quote';\nimport { createRequirementBuilders } from './requirement';\nimport { createSettle } from './settle';\nimport type {\n EvmOffer,\n ProviderContext,\n X402MultiOfferProviderOptions,\n X402OfferOptions,\n X402PaymentProvider,\n X402ProviderOptions,\n} from './types';\nimport { createVerify } from './verify';\n\nexport { DEFAULT_IDS } from './constants';\nexport type {\n X402MultiOfferProviderOptions,\n X402OfferOptions,\n X402PaymentProvider,\n X402ProviderOptions,\n} from './types';\n\nexport function createX402PaymentProvider(\n options: X402ProviderOptions | X402MultiOfferProviderOptions,\n): X402PaymentProvider {\n const inputs: readonly X402OfferOptions[] = 'offers' in options ? options.offers : [options];\n if (inputs.length === 0) {\n throw new CommerceError('CONFIG_INVALID', 'x402 provider: \"offers\" is empty');\n }\n // The NEAR facilitator refuses every payment under any other value\n if (\n options.maxTimeoutSeconds !== undefined &&\n (!Number.isInteger(options.maxTimeoutSeconds) || options.maxTimeoutSeconds <= 0)\n ) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: maxTimeoutSeconds must be a positive integer (got ${options.maxTimeoutSeconds})`,\n );\n }\n const {\n offers: defaultOffers,\n resourceOffers,\n pool: offers,\n deploymentMode,\n remoteBinding,\n } = resolveOffers(inputs, options);\n const offersFor = (resourceId: string) => resourceOffers.get(resourceId) ?? defaultOffers;\n const severalOffers = [defaultOffers, ...resourceOffers.values()].some((list) => list.length > 1);\n\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? DEFAULT_IDS;\n const logger = options.logger ?? NOOP_LOGGER;\n const maxTimeoutSeconds = options.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;\n\n const quotes = options.quote\n ? createQuoteIssuer({\n signerPrivateKey: options.quote.signerPrivateKey,\n offers,\n deploymentMode,\n clock,\n maxTimeoutSeconds,\n })\n : undefined;\n\n const evmOffers = offers.filter((offer): offer is EvmOffer => offer.family === 'evm');\n const hasSvm = offers.some((offer) => offer.family === 'svm');\n const hasNear = offers.some((offer) => offer.family === 'near');\n const descriptor: AdapterDescriptor = {\n name: 'x402',\n kind: 'payment',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `x402/v${X402_VERSION} scheme=exact family=${[\n ...(evmOffers.length > 0 ? ['eip155'] : []),\n ...(hasSvm ? ['solana'] : []),\n ...(hasNear ? ['near'] : []),\n ].join(',')}`,\n capabilities: [\n ...(evmOffers.length > 0 ? ['exact-evm'] : []),\n ...(hasSvm ? ['exact-svm'] : []),\n ...(hasNear ? ['exact-near'] : []),\n `${options.facilitator.mode}-facilitator`,\n ...(evmOffers.some((offer) => offer.method === 'eip3009') ? ['eip-3009'] : []),\n ...(evmOffers.some((offer) => offer.method === 'permit2') ? ['permit2'] : []),\n 'caip-2',\n `mode=${deploymentMode}`,\n 'authorization-flow',\n 'upfront-flow',\n ...(severalOffers ? ['multiple-offers'] : []),\n ...(quotes ? ['erc-8409-quotes'] : []),\n ],\n status: 'stable',\n unsupported: [\n 'permit2 gas sponsoring extensions',\n 'upto scheme',\n 'batch-settlement scheme',\n 'auth-capture scheme',\n ],\n };\n\n // Loaded only with an offer of their family, so no deployment needs the\n // peers of a family it does not offer\n const svmModule = hasSvm\n ? loadOptionalModule(() => import('../svm'), 'Solana offers need @x402/svm and @solana/kit')\n : undefined;\n const nearModule = hasNear\n ? loadOptionalModule(() => import('../near'), 'NEAR offers need @x402/near')\n : undefined;\n const svm = async () => {\n if (!svmModule)\n throw new CommerceError('INTERNAL_ERROR', 'x402 provider: no Solana offer is configured');\n return svmModule;\n };\n const near = async () => {\n if (!nearModule)\n throw new CommerceError('INTERNAL_ERROR', 'x402 provider: no NEAR offer is configured');\n return nearModule;\n };\n\n const ctx: ProviderContext = {\n options,\n offers,\n offersFor,\n deploymentMode,\n remoteBinding,\n clock,\n ids,\n logger,\n maxTimeoutSeconds,\n quotes,\n svm,\n near,\n };\n const { createRequirement, selectRequirement } = createRequirementBuilders(\n ctx,\n createSvmFeePayerSource(ctx),\n );\n const verify = createVerify(ctx);\n const settle = createSettle(ctx);\n const health = createHealthCheck(ctx);\n\n return {\n name: 'x402',\n descriptor,\n createRequirement,\n // A single offer needs no selection\n ...(severalOffers ? { selectRequirement } : {}),\n verify,\n settle,\n health,\n ...(quotes\n ? {\n quote: {\n issuer: quotes.issuer,\n requestScheme: QUOTE_REQUEST_SCHEME,\n extension: QUOTE_EXTENSION,\n },\n }\n : {}),\n };\n}\n\n/**\n * Loads a family's inspection module, refusing with a clear error when its\n * optional peers are missing\n */\nfunction loadOptionalModule<T>(load: () => Promise<T>, missing: string): Promise<T> {\n const loading = load().catch((cause: unknown) => {\n throw new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', `x402 provider: ${missing}`, {\n cause,\n });\n });\n // verify() and health() report the failure; nothing else awaits it\n loading.catch(() => {});\n return loading;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/domain/common.ts","../src/core/domain/event.ts","../src/core/domain/resource.ts","../src/core/errors/codes.ts","../src/core/errors/commerce-error.ts","../src/core/domain/wire.ts","../src/core/interfaces/logger.ts","../src/core/interfaces/protocol-adapter.ts","../src/core/interfaces/runtime.ts","../src/version.ts"],"names":[],"mappings":";;;;AAaA,IAAM,kBAAA,GAAiD;AAAA,EACrD,IAAA,EAAM,IAAA;AAAA,EACN,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK,IAAA;AAAA,EACL,GAAA,EAAK;AACP,CAAA;AAMO,IAAM,iBAA0C,MAAA,CAAO,IAAA;AAAA,EAC5D;AACF;AAaA,IAAM,wBAAA,GAA4D,EAAE,IAAA,EAAM,IAAA,EAAM,KAAK,IAAA,EAAK;AAGnF,IAAM,uBAAqD,MAAA,CAAO,IAAA;AAAA,EACvE;AACF;;;ACrCO,IAAM,oBAAA,GAAuB;AAAA,EAClC,qBAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA;AAAA;AAAA,EAGA,wBAAA;AAAA,EACA,wBAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF;;;ACwBO,IAAM,0BAAA,GAA6B;;;ACxCnC,IAAM,oBAAA,GAAuB;AAAA,E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AkB,MAAA,GAAY,EAAE,aAAA,KAAkB;AAAC,GACzD;AACF;;;AChVO,IAAM,WAAA,GAAsB;AAAA,EACjC,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AACf;;;AC0DO,SAAS,sBAAsB,OAAA,EAA0D;AAC9F,EAAA,OAAO,OAAQ,QAAgC,UAAA,KAAe,UAAA;AAChE;;;ACnEO,IAAM,WAAA,GAAqB;AAAA,EAChC,GAAA,EAAK,sBAAM,IAAI,IAAA,EAAK;AAAA,EACpB,MAAA,EAAQ,MAAA,iBAAM,IAAI,IAAA,IAAO,WAAA,EAAY;AAAA,EACrC,WAAA,EAAa,MAAM,WAAA,CAAY,GAAA;AACjC;ACGO,IAAM,eAAA,GACmC,OAAA","file":"chunk-DTKU3Z2M.js","sourcesContent":["// Shared primitive aliases for the canonical domain model. FROZEN CONTRACT\n\n/**\n * A JSON Schema document (in practice a draft 2020-12 subset). Deliberately\n * loose: adapters translate it to their own schema representation. Never treat\n * it as trusted input without validation.\n */\nexport type JsonSchema = Record<string, unknown>;\n\n/** Protocol surfaces a resource can be exposed through */\nexport type ProtocolName = 'http' | 'mcp' | 'a2a' | 'acp';\n\n// A Record over the union fails to compile when a name is missing or extra\nconst PROTOCOL_NAME_KEYS: Record<ProtocolName, true> = {\n http: true,\n mcp: true,\n a2a: true,\n acp: true,\n};\n\n/**\n * The same names as a value, for code that checks one at runtime: config\n * validation and the OpenAPI importer's `--expose`\n */\nexport const PROTOCOL_NAMES: readonly ProtocolName[] = Object.keys(\n PROTOCOL_NAME_KEYS,\n) as ProtocolName[];\n\n/**\n * Payment rails a resource can accept.\n *\n * A resource's list is an ordered candidate list, not a buyer-selected menu.\n * The pipeline uses the first method with an enabled provider, and a\n * rejection ends the request instead of trying another rail. Config requires at\n * least one named rail to be enabled and permits others that are not.\n */\nexport type PaymentMethodName = 'x402' | 'mpp';\n\n// Checked for completeness the same way as PROTOCOL_NAME_KEYS\nconst PAYMENT_METHOD_NAME_KEYS: Record<PaymentMethodName, true> = { x402: true, mpp: true };\n\n/** The same names as a value, for config validation */\nexport const PAYMENT_METHOD_NAMES: readonly PaymentMethodName[] = Object.keys(\n PAYMENT_METHOD_NAME_KEYS,\n) as PaymentMethodName[];\n\n/**\n * Authorization methods a resource can require. Neither a transport nor a\n * payment rail: it proves the purchase was approved, and sits beside the\n * payment rather than replacing it.\n */\nexport type AuthorizationMethodName = 'ap2';\n\n/** ISO-8601 timestamp string, always UTC with millisecond precision */\nexport type IsoTimestamp = string;\n\n/**\n * A decimal amount as a string in the currency's display unit (for example\n * \"0.01\" USDC), never a float and never base units. Payment providers convert\n * it to on-chain base units.\n */\nexport type DecimalAmount = string;\n\n/** Health of an individual adapter or subsystem */\nexport interface AdapterHealth {\n readonly status: 'pass' | 'warn' | 'fail';\n readonly detail?: string;\n readonly checkedAt: IsoTimestamp;\n readonly durationMs?: number;\n /**\n * Results per checked part, such as each x402 offer. Names and statuses\n * may be published; exclude diagnostic detail.\n */\n readonly components?: readonly AdapterHealthComponent[];\n}\n\n/** One part of an {@link AdapterHealth} result */\nexport interface AdapterHealthComponent {\n readonly name: string;\n readonly status: 'pass' | 'warn' | 'fail';\n}\n\n/** Describes an adapter's supported surface for diagnostics */\nexport interface AdapterDescriptor {\n readonly name: string;\n readonly kind: 'protocol' | 'payment' | 'storage' | 'authorization';\n /** Version of this adapter implementation, independent of the spec */\n readonly implementationVersion: string;\n /** Exact pinned specification revision this adapter targets */\n readonly supportedSpec: string;\n readonly capabilities: readonly string[];\n readonly status: 'stable' | 'experimental' | 'planned';\n /** Capabilities explicitly not implemented, printed by `doctor` */\n readonly unsupported?: readonly string[];\n}\n","/**\n * Canonical commerce events. FROZEN CONTRACT. Every event in one flow shares\n * one `requestId`, which correlates logs, payment attempts, backend calls and\n * receipts.\n */\nimport type { IsoTimestamp } from './common';\n\nexport const COMMERCE_EVENT_TYPES = [\n 'resource.discovered',\n 'resource.requested',\n 'payment.required',\n 'payment.rejected',\n 'payment.verified',\n 'payment.settled',\n // The same two types for every authorization method, so an audit-trail\n // reader never has to know what AP2 is\n 'authorization.verified',\n 'authorization.rejected',\n 'backend.called',\n 'backend.failed',\n 'resource.delivered',\n] as const;\n\nexport type CommerceEventType = (typeof COMMERCE_EVENT_TYPES)[number];\n\nexport interface CommerceEvent {\n readonly id: string;\n readonly type: CommerceEventType;\n readonly requestId: string;\n readonly resourceId?: string;\n readonly at: IsoTimestamp;\n /** Protocol adapter that originated the request, e.g. 'mcp' or 'http' */\n readonly adapter?: string;\n readonly paymentProvider?: string;\n readonly durationMs?: number;\n readonly status?: 'ok' | 'error';\n /** Non-secret, structured detail. Must never contain keys, headers or proofs */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Sink for canonical events. `emit` must not throw: a sink failure must never\n * fail an otherwise successful commerce flow.\n */\nexport interface EventSink {\n emit(event: CommerceEvent): Promise<void>;\n}\n","// Canonical resource model. FROZEN CONTRACT\nimport type {\n AuthorizationMethodName,\n DecimalAmount,\n JsonSchema,\n PaymentMethodName,\n ProtocolName,\n} from './common';\n\n/** HTTP methods a backend handler may use */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * How the gateway calls the merchant's existing backend.\n *\n * Backend URLs come from operator configuration only, never from users or\n * agents (docs/security.md, SSRF). Secret header values belong in `${ENV_VAR}`\n * placeholders resolved by the config loader, not in plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to `DEFAULT_BACKEND_TIMEOUT_MS` */\n readonly timeoutMs?: number;\n /**\n * Names the top-level input properties carrying each part of the request.\n *\n * When absent, `{param}` values come from top-level input and everything left\n * over becomes the query string (GET/DELETE) or the whole JSON body\n * (POST/PUT/PATCH). That cannot express an operation with path, query and\n * body at once, such as `POST /users/{userId}/orders?notify=true`.\n *\n * When present, each group comes from its named property, and top-level input\n * that no binding names is not forwarded.\n */\n readonly inputBindings?: {\n readonly path?: string;\n readonly query?: string;\n readonly body?: string;\n };\n}\n\n/** Default backend timeout when a resource does not specify one */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing. `dynamic` exists in the type for forward compatibility;\n * config validation rejects it and the pipeline refuses it as defense in depth.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents. Protocol adapters map it outward and\n * never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n /**\n * Authorization the buyer must present in addition to payment. Opt-in per\n * resource. It sits beside `paymentMethods`, not inside it, because an\n * authorization method is not a payment rail and must never be selectable as\n * one.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationMethodName[];\n };\n}\n\n/** Read-only view of every configured resource */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Typed domain error codes. FROZEN CONTRACT. Protocol adapters map them into\n * their own response format. Never throw a bare string or untyped Error across\n * an area boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'AUTHORIZATION_REQUIRED',\n 'AUTHORIZATION_INVALID',\n 'AUTHORIZATION_REPLAYED',\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code. Every payment failure maps to a\n * 4xx or 5xx status, never to a delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n // 403, not 402: a 402 tells a client to pay and retry, which cannot fix a\n // missing or rejected mandate, and a client that auto-pays on 402 would be\n // charged for a request that was never going to be delivered\n AUTHORIZATION_REQUIRED: 403,\n AUTHORIZATION_INVALID: 403,\n AUTHORIZATION_REPLAYED: 409,\n AUTHORIZATION_PROVIDER_UNAVAILABLE: 503,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n // The verifier or replay store was unreachable, so the mandate got no\n // verdict. The same proof can verify once the outage clears.\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient: the caller should back off and try again.\n // Clients act on this flag, and leaving it out would make a momentary\n // throttle look like a permanent failure.\n 'GATEWAY_BUSY',\n]);\n","// The single error type crossing area boundaries. FROZEN CONTRACT\nimport { COMMERCE_ERROR_HTTP_STATUS, type CommerceErrorCode, RETRYABLE_ERROR_CODES } from './codes';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code */\n readonly httpStatus?: number;\n}\n\n/** Serializable wire form of a CommerceError */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. `cause` is never included */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Passes an existing CommerceError through. Other thrown values become a\n * CommerceError with a caller-chosen message, for example\n * `toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')`.\n *\n * Arbitrary Error messages may contain internal URLs, hostnames or file paths.\n * The original value remains on `cause` for internal logging; `toInfo()` and\n * `toErrorEnvelope()` do not serialize it.\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n\n/** A thrown value reduced to its message and name, for a log line */\nexport function describeError(error: unknown): { message: string; name?: string } {\n if (error instanceof Error) return { message: error.message, name: error.name };\n return { message: String(error) };\n}\n\n/**\n * `Name: message` for a log line, with every URL cut to its scheme and host,\n * because a backend or RPC URL can carry a credential in its userinfo, path or\n * query\n */\nexport function redactedErrorText(value: unknown): string {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : String(value);\n return text.replace(/\\b[a-z][a-z\\d+.-]*:\\/\\/[^\\s\"'<>]+/gi, (match) => {\n try {\n const url = new URL(match);\n return `${url.protocol}//${url.host}`;\n } catch {\n return '[unparseable URL]';\n }\n });\n}\n\n// Deepest `cause` level toLogInfo() follows, which also ends a cyclic chain\nconst MAX_LOGGED_CAUSES = 5;\n\n/**\n * An error for an operator log line: the `toInfo()` fields plus the `cause`\n * chain that `toInfo()` leaves out, each level as `redactedErrorText()` gives it\n */\nexport function toLogInfo(\n value: unknown,\n): CommerceErrorInfo & { readonly cause?: readonly string[] } {\n const error = toCommerceError(value);\n const cause: string[] = [];\n let current = error.cause;\n while (current !== undefined && cause.length < MAX_LOGGED_CAUSES) {\n cause.push(redactedErrorText(current));\n current = current instanceof Error ? current.cause : undefined;\n }\n return cause.length > 0 ? { ...error.toInfo(), cause } : error.toInfo();\n}\n","/**\n * Gateway-defined wire envelopes and carriers. FROZEN CONTRACT.\n *\n * The HTTP routes and the MCP and A2A adapters build their \"payment required\"\n * and \"error\" bodies with these helpers, so those surfaces send the same\n * shapes. The ACP adapter maps errors to ACP's own error format instead.\n */\n\nimport { CommerceError, type CommerceErrorCode } from '../errors';\nimport { isRecord } from '../is-record';\nimport type { AuthorizationRequirement, AuthorizationSubmission } from './authorization';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common';\nimport type { PaymentSubmission } from './payment';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request';\nimport type { CommerceResource } from './resource';\n\n/**\n * Reserved input property carrying a payment proof on protocols with no header\n * channel (MCP tool calls, A2A message data). HTTP uses a header instead.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/**\n * HTTP request header carrying an x402 payment proof. MPP proofs use\n * `Authorization: Payment ...` instead.\n *\n * The x402 v2 header names, lowercased as Node presents incoming headers. v1's\n * `X-PAYMENT` / `X-PAYMENT-RESPONSE` pair is not accepted: honoring both\n * versions would mean two verification paths for the same money.\n */\nexport const PAYMENT_HEADER = 'payment-signature';\n\n/** HTTP response header carrying the settlement result */\nexport const PAYMENT_RESPONSE_HEADER = 'payment-response';\n\n/**\n * Reserved input property carrying an authorization proof, the counterpart of\n * {@link PAYMENT_INPUT_FIELD}.\n *\n * `_payment` is a bare string whose method is taken from the resource's first\n * payment method. This field is a `{ method, payload }` object, because the\n * method of a security control should be stated, not inferred.\n */\nexport const AUTHORIZATION_INPUT_FIELD = '_authorization';\n\n/**\n * Every input property name the gateway claims for itself. The config loader\n * rejects a resource declaring one, protocol adapters lift them out of client\n * input, and the pipeline strips them again as defense in depth.\n */\nexport const RESERVED_INPUT_FIELDS: readonly string[] = [\n PAYMENT_INPUT_FIELD,\n AUTHORIZATION_INPUT_FIELD,\n];\n\n/**\n * HTTP request header carrying the authorization proof: base64url-encoded JSON\n * of the same `{ method, payload }` object the reserved input field carries.\n *\n * An Agent Commerce carrier, not a header from any authorization\n * specification. It is namespaced rather than reusing `Authorization`, which\n * already carries other credentials, including MPP payment proofs.\n */\nexport const AUTHORIZATION_HEADER = 'agent-authorization';\n\n/**\n * Hard cap on the encoded `Agent-Authorization` header.\n *\n * Node's default limit is 16 KiB across all request headers, and a request over\n * it is refused before the gateway sees it. Capping well below that gives an\n * oversized proof a deterministic `AUTHORIZATION_INVALID` naming the limit.\n */\nexport const MAX_AUTHORIZATION_HEADER_BYTES = 8192;\n\n/**\n * HTTP response header carrying the base64 x402 challenge on a 402.\n *\n * The body still carries the richer {@link PaymentRequiredEnvelope}, the only\n * channel MCP has, but an x402 v2 client reads the challenge from this header\n * and ignores the body, so both are sent.\n */\nexport const PAYMENT_REQUIRED_HEADER = 'payment-required';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata: MCP's `CallToolResult._meta` and the A2A task artifact's\n * metadata.\n *\n * Part of the frozen contract because producer and consumer must agree on it;\n * both import this constant. Follows MCP's `<namespace>/<name>` convention for\n * `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n /**\n * @deprecated Read each offer's `payTo` in `accepts`. Absent when the\n * challenge offers several destinations.\n */\n readonly destination?: string;\n /** @deprecated Read each offer's `network` in `accepts` */\n readonly network?: string;\n /** @deprecated Read each offer's `asset` in `accepts` */\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n /**\n * The provider's own challenge document, verbatim (see\n * {@link PaymentChallenge.envelope}). Present for providers that have one;\n * a buyer's protocol client can hand it straight to its SDK.\n */\n readonly envelope?: Readonly<Record<string, unknown>>;\n };\n /**\n * Present only when the resource also requires an authorization proof, so a\n * client learns before it spends anything that paying alone will not get the\n * resource delivered. A client that ignores the field sees the plain\n * envelope. The proof comes from the merchant's own approval flow, outside\n * the gateway.\n */\n readonly authorization?: {\n readonly required: readonly AuthorizationRequirement[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase: the request, whether\n * it settled, and the settlement reference they can check on-chain. The\n * merchant's ledger is not theirs to read, which is why `/api/receipts` is an\n * operator route behind `server.adminToken`.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n ...(r.destination !== undefined ? { destination: r.destination } : {}),\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n ...(r.challenge.envelope !== undefined ? { envelope: r.challenge.envelope } : {}),\n },\n ...(outcome.authorization !== undefined && outcome.authorization.length > 0\n ? { authorization: { required: outcome.authorization } }\n : {}),\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n\n/**\n * Parses the `{ method, payload }` authorization object, whichever carrier\n * brought it. Absent returns `undefined`; malformed throws\n * `AUTHORIZATION_INVALID`.\n *\n * An unusable `_payment` is dropped, which leaves the buyer a 402 to act on. A\n * dropped authorization would instead come back as \"not authorized\", with no\n * way to tell a rejected mandate from a typo in the object around it.\n */\nexport function parseAuthorizationSubmission(\n value: unknown,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n if (value === undefined || value === null) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (!isRecord(value)) {\n return fail(`expected an object with \"method\" and \"payload\", got ${typeof value}`);\n }\n const method = value['method'];\n const payload = value['payload'];\n\n // Compared against the literal rather than a registry: a second method needs\n // a second verifier, a deliberate addition rather than a string that starts\n // working because a client sent it\n if (method !== 'ap2') {\n fail(`unsupported method ${typeof method === 'string' ? `\"${method}\"` : typeof method}`);\n }\n if (typeof payload !== 'string' || payload.length === 0) {\n fail('\"payload\" must be a non-empty string');\n }\n\n return { method: 'ap2', payload: payload as string };\n}\n\n/**\n * Decodes the base64url JSON `Agent-Authorization` header. The size check runs\n * on the encoded value, so an oversized header costs a length comparison rather\n * than a decode and a JSON parse.\n */\nexport function parseAuthorizationHeader(\n raw: string | readonly string[] | undefined,\n requestId?: string,\n): AuthorizationSubmission | undefined {\n const value = Array.isArray(raw) ? raw[0] : (raw as string | undefined);\n if (value === undefined || value.length === 0) return undefined;\n\n const fail = (detail: string): never => {\n throw new CommerceError('AUTHORIZATION_INVALID', `Malformed authorization: ${detail}`, {\n ...(requestId !== undefined ? { requestId } : {}),\n });\n };\n\n if (Buffer.byteLength(value, 'utf8') > MAX_AUTHORIZATION_HEADER_BYTES) {\n fail(`header exceeds the ${MAX_AUTHORIZATION_HEADER_BYTES}-byte limit`);\n }\n\n let decoded: unknown;\n try {\n decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));\n } catch {\n // Nothing from the exception is repeated back: a JSON parse error quotes\n // the input it choked on, which here is whatever the caller sent\n fail('header is not base64url-encoded JSON');\n }\n return parseAuthorizationSubmission(decoded, requestId);\n}\n\n/**\n * Splits raw client input into resource input plus the reserved fields, for\n * protocols that carry them in the input object (MCP tool arguments, A2A\n * message data). HTTP carries both in headers.\n *\n * A payment proof is labeled with the resource's first payment method.\n * `createGateway` puts provider-backed methods first so the label matches the\n * pipeline's selection; a custom registry must keep that order. A resource with\n * no payment method gets no payment proof, so the request reaches the pipeline\n * unpaid.\n */\nexport function extractReservedInputFields(\n rawInput: Record<string, unknown>,\n resource: CommerceResource | undefined,\n requestId?: string,\n): {\n input: Record<string, unknown>;\n payment?: PaymentSubmission;\n authorization?: AuthorizationSubmission;\n} {\n const {\n [PAYMENT_INPUT_FIELD]: paymentValue,\n [AUTHORIZATION_INPUT_FIELD]: authorizationValue,\n ...input\n } = rawInput;\n\n const method = resource?.paymentMethods[0];\n const payment =\n typeof paymentValue === 'string' && paymentValue.length > 0 && method !== undefined\n ? ({ method, payload: paymentValue } satisfies PaymentSubmission)\n : undefined;\n const authorization = parseAuthorizationSubmission(authorizationValue, requestId);\n\n return {\n input,\n ...(payment !== undefined ? { payment } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n };\n}\n","/**\n * Minimal structural logger. Core does not depend on pino; the gateway injects\n * a pino instance that satisfies this shape.\n *\n * Never log secrets: private keys, seed phrases, Authorization headers or\n * payment authorization payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary. FROZEN CONTRACT.\n *\n * An adapter translates a protocol's wire format into a `CanonicalRequest`,\n * hands it to the execution pipeline and maps the outcome back. It must not\n * call merchant backends, implement payment logic or hold its own copy of the\n * canonical model. A failure while starting or serving one adapter must not\n * stop the others.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common';\nimport type { EventSink } from '../domain/event';\nimport type { ExecutionPipeline } from '../domain/request';\nimport type { ResourceRegistry } from '../domain/resource';\nimport type { Logger } from './logger';\nimport type { Clock, IdGenerator } from './runtime';\n\n/** Everything an adapter is given. Nothing else is available to it */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP. The gateway mounts `handleHttp` at\n * `mountPath` with raw Node request and response objects, so adapters stay\n * independent of the HTTP framework.\n *\n * Guarantee: `req` arrives with its body stream unread. The gateway suppresses\n * every body parser on the mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * The guarantee can break silently. Fastify prefers its exact-match\n * `application/json` and `text/plain` parsers over a `'*'` wildcard, so a\n * wildcard no-op alone lets the JSON parser drain the body and the adapter\n * reads an empty stream. The MCP conformance suite drives `handleHttp` over a\n * bare `node:http` server and cannot catch it, so any change to adapter mounting\n * needs a test that POSTs a JSON body through the real gateway and asserts the\n * adapter received it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp' */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n /**\n * Fixed paths this adapter owns outside its mount, for protocols whose\n * specification pins a discovery URL (A2A's `/.well-known/agent-card.json`).\n * The gateway mounts them with the same guarantees as `mountPath`: unread\n * body, concurrency cap and failure isolation.\n */\n readonly additionalHttpRoutes?: readonly AdapterHttpRoute[];\n}\n\n/**\n * One fixed, method-scoped route owned by an adapter. Unlike `mountPath` it\n * registers no wildcard and matches exactly the path given.\n */\nexport interface AdapterHttpRoute {\n readonly method: 'GET' | 'POST';\n /** Absolute gateway path, e.g. '/.well-known/agent-card.json' */\n readonly path: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n","// Time and ids are injected so tests can be deterministic\nimport type { IsoTimestamp } from '../domain/common';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","/**\n * The package version, resolved once for the whole package.\n *\n * The build injects `__OAC_PACKAGE_VERSION__` (tsup.config.ts), because a\n * relative manifest path resolves from the wrong depth once `src/**` is\n * bundled. From source, the root manifest is read instead. `typeof` on an\n * undeclared identifier is safe, so the source path runs without the constant.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}
@@ -1,44 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import { PERMIT2_ADDRESS } from '@x402/evm';
3
- import { encodeAbiParameters, keccak256 } from 'viem';
4
-
5
- // src/payments/x402/replay-key.ts
6
- function computeReplayKey(input) {
7
- const encoded = encodeAbiParameters(
8
- [{ type: "uint256" }, { type: "address" }, { type: "address" }, { type: "bytes32" }],
9
- [BigInt(input.chainId), input.asset, input.from, input.nonce]
10
- );
11
- return keccak256(encoded);
12
- }
13
- function computePermit2ReplayKey(input) {
14
- return keccak256(
15
- encodeAbiParameters(
16
- [
17
- { type: "string" },
18
- { type: "uint256" },
19
- { type: "address" },
20
- { type: "address" },
21
- { type: "uint256" }
22
- ],
23
- [
24
- "x402/exact/permit2/v1",
25
- BigInt(input.chainId),
26
- PERMIT2_ADDRESS,
27
- input.owner,
28
- BigInt(input.nonce)
29
- ]
30
- )
31
- );
32
- }
33
- function computeSvmReplayKey(input) {
34
- const digest = createHash("sha256").update("x402/exact/svm/v1\0").update(input.network).update("\0").update(Buffer.from(input.messageHash, "base64")).digest("hex");
35
- return `0x${digest}`;
36
- }
37
- function computeNearReplayKey(input) {
38
- const digest = createHash("sha256").update("x402/exact/near/v1\0").update(`${input.network}\0${input.senderId}\0${input.publicKey}\0${input.nonce.toString(10)}`).digest("hex");
39
- return `0x${digest}`;
40
- }
41
-
42
- export { computeNearReplayKey, computePermit2ReplayKey, computeReplayKey, computeSvmReplayKey };
43
- //# sourceMappingURL=chunk-KA2AX5FH.js.map
44
- //# sourceMappingURL=chunk-KA2AX5FH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/payments/x402/replay-key.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,iBAAiB,KAAA,EAA+B;AAC9D,EAAA,MAAM,OAAA,GAAU,mBAAA;AAAA,IACd,CAAC,EAAE,IAAA,EAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,SAAA,EAAU,EAAG,EAAE,MAAM,SAAA,EAAU,EAAG,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,IACnF,CAAC,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAG,MAAM,KAAA,EAAO,KAAA,CAAM,IAAA,EAAM,KAAA,CAAM,KAAK;AAAA,GAC9D;AACA,EAAA,OAAO,UAAU,OAAO,CAAA;AAC1B;AAOO,SAAS,wBAAwB,KAAA,EAI7B;AACT,EAAA,OAAO,SAAA;AAAA,IACL,mBAAA;AAAA,MACE;AAAA,QACE,EAAE,MAAM,QAAA,EAAS;AAAA,QACjB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA,EAAU;AAAA,QAClB,EAAE,MAAM,SAAA;AAAU,OACpB;AAAA,MACA;AAAA,QACE,uBAAA;AAAA,QACA,MAAA,CAAO,MAAM,OAAO,CAAA;AAAA,QACpB,eAAA;AAAA,QACA,KAAA,CAAM,KAAA;AAAA,QACN,MAAA,CAAO,MAAM,KAAK;AAAA;AACpB;AACF,GACF;AACF;AAQO,SAAS,oBAAoB,KAAA,EAGzB;AACT,EAAA,MAAM,MAAA,GAAS,WAAW,QAAQ,CAAA,CAC/B,OAAO,qBAAqB,CAAA,CAC5B,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CACpB,OAAO,IAAI,CAAA,CACX,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,aAAa,QAAQ,CAAC,CAAA,CAC/C,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB;AAQO,SAAS,qBAAqB,KAAA,EAK1B;AACT,EAAA,MAAM,MAAA,GAAS,UAAA,CAAW,QAAQ,CAAA,CAC/B,MAAA,CAAO,sBAAsB,CAAA,CAC7B,MAAA,CAAO,CAAA,EAAG,KAAA,CAAM,OAAO,CAAA,EAAA,EAAK,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK,KAAA,CAAM,SAAS,CAAA,EAAA,EAAK,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAE,CAAA,CAC7F,MAAA,CAAO,KAAK,CAAA;AACf,EAAA,OAAO,KAAK,MAAM,CAAA,CAAA;AACpB","file":"chunk-KA2AX5FH.js","sourcesContent":["/**\n * `PaymentResult.replayKey` is derived from the payment authorization alone,\n * never from the request id, so the same authorization replayed on another\n * request collides in the receipt store's reservation. The MPP provider uses\n * the EIP-3009 derivation.\n */\nimport { createHash } from 'node:crypto';\nimport { PERMIT2_ADDRESS } from '@x402/evm';\nimport { encodeAbiParameters, keccak256 } from 'viem';\n\nexport interface ReplayKeyInput {\n readonly chainId: number;\n readonly asset: `0x${string}`;\n readonly from: `0x${string}`;\n readonly nonce: `0x${string}`;\n}\n\nexport function computeReplayKey(input: ReplayKeyInput): string {\n const encoded = encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }],\n [BigInt(input.chainId), input.asset, input.from, input.nonce],\n );\n return keccak256(encoded);\n}\n\n/**\n * Identifies a Permit2 authorization by chain, Permit2 contract, owner and\n * nonce. Nonces span all tokens and spenders, so asset and resource are excluded.\n * The tag separates these keys from EIP-3009 in the receipt store's unique column.\n */\nexport function computePermit2ReplayKey(input: {\n readonly chainId: number;\n readonly owner: `0x${string}`;\n readonly nonce: string;\n}): string {\n return keccak256(\n encodeAbiParameters(\n [\n { type: 'string' },\n { type: 'uint256' },\n { type: 'address' },\n { type: 'address' },\n { type: 'uint256' },\n ],\n [\n 'x402/exact/permit2/v1',\n BigInt(input.chainId),\n PERMIT2_ADDRESS,\n input.owner,\n BigInt(input.nonce),\n ],\n ),\n );\n}\n\n/**\n * Identifies a Solana `exact` payment by network and SHA-256 of the signed\n * message bytes. Excludes signatures, including the facilitator's fee payer\n * slot, so altered signatures keep the same key. `messageHash` is the SDK's\n * base64 `transactionMessageHash`.\n */\nexport function computeSvmReplayKey(input: {\n readonly network: string;\n readonly messageHash: string;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/svm/v1\\0')\n .update(input.network)\n .update('\\0')\n .update(Buffer.from(input.messageHash, 'base64'))\n .digest('hex');\n return `0x${digest}`;\n}\n\n/**\n * Identifies a NEAR `exact` payment by network, sender, curve-prefixed public\n * key (`ed25519:...`) and delegate nonce. Nonces are scoped per access key,\n * excluding token, recipient, relayer and signature; another key of the same\n * sender has an independent nonce scope.\n */\nexport function computeNearReplayKey(input: {\n readonly network: string;\n readonly senderId: string;\n readonly publicKey: string;\n readonly nonce: bigint;\n}): string {\n const digest = createHash('sha256')\n .update('x402/exact/near/v1\\0')\n .update(`${input.network}\\0${input.senderId}\\0${input.publicKey}\\0${input.nonce.toString(10)}`)\n .digest('hex');\n return `0x${digest}`;\n}\n"]}