@tabai/sdk 0.2.3 → 0.2.5

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 (155) hide show
  1. package/README.md +12 -9
  2. package/dist/_shared/abi.d.ts.map +1 -1
  3. package/dist/_shared/abi.js +6 -3
  4. package/dist/_shared/abi.js.map +1 -1
  5. package/dist/_shared/chains.d.ts +4 -6
  6. package/dist/_shared/chains.d.ts.map +1 -1
  7. package/dist/_shared/chains.js +1 -2
  8. package/dist/_shared/chains.js.map +1 -1
  9. package/dist/_shared/keccak256.d.ts +6 -6
  10. package/dist/_shared/keccak256.js +6 -6
  11. package/dist/_shared/keccak256.js.map +1 -1
  12. package/dist/_shared/result.d.ts +5 -6
  13. package/dist/_shared/result.d.ts.map +1 -1
  14. package/dist/_shared/result.js +5 -6
  15. package/dist/_shared/result.js.map +1 -1
  16. package/dist/cli/client-config.d.ts +4 -5
  17. package/dist/cli/client-config.d.ts.map +1 -1
  18. package/dist/cli/client-config.js +4 -5
  19. package/dist/cli/client-config.js.map +1 -1
  20. package/dist/cli/connect.d.ts +1 -3
  21. package/dist/cli/connect.d.ts.map +1 -1
  22. package/dist/cli/connect.js +5 -3
  23. package/dist/cli/connect.js.map +1 -1
  24. package/dist/cli/doctor.d.ts +1 -3
  25. package/dist/cli/doctor.d.ts.map +1 -1
  26. package/dist/cli/doctor.js +1 -3
  27. package/dist/cli/doctor.js.map +1 -1
  28. package/dist/cli/index.d.ts +1 -1
  29. package/dist/cli/index.js +1 -1
  30. package/dist/cli/index.js.map +1 -1
  31. package/dist/cli/main.d.ts +1 -3
  32. package/dist/cli/main.d.ts.map +1 -1
  33. package/dist/cli/main.js +7 -6
  34. package/dist/cli/main.js.map +1 -1
  35. package/dist/errors.d.ts +2 -4
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +2 -4
  38. package/dist/errors.js.map +1 -1
  39. package/dist/http/client-402.d.ts +11 -13
  40. package/dist/http/client-402.d.ts.map +1 -1
  41. package/dist/http/client-402.js +12 -14
  42. package/dist/http/client-402.js.map +1 -1
  43. package/dist/http/headers.d.ts +9 -11
  44. package/dist/http/headers.d.ts.map +1 -1
  45. package/dist/http/headers.js +9 -11
  46. package/dist/http/headers.js.map +1 -1
  47. package/dist/http/index.d.ts +0 -2
  48. package/dist/http/index.d.ts.map +1 -1
  49. package/dist/http/index.js +0 -2
  50. package/dist/http/index.js.map +1 -1
  51. package/dist/http/metering-claim.d.ts +0 -2
  52. package/dist/http/metering-claim.d.ts.map +1 -1
  53. package/dist/http/metering-claim.js +0 -2
  54. package/dist/http/metering-claim.js.map +1 -1
  55. package/dist/index.d.ts +15 -12
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +15 -12
  58. package/dist/index.js.map +1 -1
  59. package/dist/logger.d.ts +1 -4
  60. package/dist/logger.d.ts.map +1 -1
  61. package/dist/logger.js +1 -4
  62. package/dist/logger.js.map +1 -1
  63. package/dist/mcp/index.d.ts +1 -1
  64. package/dist/mcp/index.js +1 -1
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/json-schema.d.ts +1 -3
  67. package/dist/mcp/json-schema.d.ts.map +1 -1
  68. package/dist/mcp/json-schema.js +1 -3
  69. package/dist/mcp/json-schema.js.map +1 -1
  70. package/dist/mcp/json.d.ts +0 -2
  71. package/dist/mcp/json.d.ts.map +1 -1
  72. package/dist/mcp/json.js +0 -2
  73. package/dist/mcp/json.js.map +1 -1
  74. package/dist/mcp/registry-client.d.ts +0 -2
  75. package/dist/mcp/registry-client.d.ts.map +1 -1
  76. package/dist/mcp/registry-client.js +3 -4
  77. package/dist/mcp/registry-client.js.map +1 -1
  78. package/dist/mcp/schemas.d.ts +10 -8
  79. package/dist/mcp/schemas.d.ts.map +1 -1
  80. package/dist/mcp/schemas.js +5 -7
  81. package/dist/mcp/schemas.js.map +1 -1
  82. package/dist/mcp/server.d.ts +0 -2
  83. package/dist/mcp/server.d.ts.map +1 -1
  84. package/dist/mcp/server.js +4 -7
  85. package/dist/mcp/server.js.map +1 -1
  86. package/dist/mcp/settings.d.ts +5 -1
  87. package/dist/mcp/settings.d.ts.map +1 -1
  88. package/dist/mcp/settings.js +28 -3
  89. package/dist/mcp/settings.js.map +1 -1
  90. package/dist/mcp/toolset.d.ts +2 -5
  91. package/dist/mcp/toolset.d.ts.map +1 -1
  92. package/dist/mcp/toolset.js +3 -6
  93. package/dist/mcp/toolset.js.map +1 -1
  94. package/dist/payments/config.d.ts +6 -8
  95. package/dist/payments/config.d.ts.map +1 -1
  96. package/dist/payments/config.js +5 -7
  97. package/dist/payments/config.js.map +1 -1
  98. package/dist/payments/index.d.ts +0 -2
  99. package/dist/payments/index.d.ts.map +1 -1
  100. package/dist/payments/index.js +0 -2
  101. package/dist/payments/index.js.map +1 -1
  102. package/dist/payments/registry.d.ts +11 -12
  103. package/dist/payments/registry.d.ts.map +1 -1
  104. package/dist/payments/registry.js +11 -12
  105. package/dist/payments/registry.js.map +1 -1
  106. package/dist/payments/strategy.d.ts +9 -5
  107. package/dist/payments/strategy.d.ts.map +1 -1
  108. package/dist/payments/strategy.js +9 -5
  109. package/dist/payments/strategy.js.map +1 -1
  110. package/dist/proxy/hooks.d.ts +3 -5
  111. package/dist/proxy/hooks.d.ts.map +1 -1
  112. package/dist/proxy/hooks.js +2 -4
  113. package/dist/proxy/hooks.js.map +1 -1
  114. package/dist/proxy/index.d.ts +2 -2
  115. package/dist/proxy/index.js +2 -2
  116. package/dist/proxy/index.js.map +1 -1
  117. package/dist/proxy/proxy.d.ts +3 -5
  118. package/dist/proxy/proxy.d.ts.map +1 -1
  119. package/dist/proxy/proxy.js +2 -4
  120. package/dist/proxy/proxy.js.map +1 -1
  121. package/dist/server/adapters/express.d.ts +0 -2
  122. package/dist/server/adapters/express.d.ts.map +1 -1
  123. package/dist/server/adapters/express.js +0 -2
  124. package/dist/server/adapters/express.js.map +1 -1
  125. package/dist/server/adapters/hono.d.ts +0 -2
  126. package/dist/server/adapters/hono.d.ts.map +1 -1
  127. package/dist/server/adapters/hono.js +0 -2
  128. package/dist/server/adapters/hono.js.map +1 -1
  129. package/dist/server/adapters/next.d.ts +0 -2
  130. package/dist/server/adapters/next.d.ts.map +1 -1
  131. package/dist/server/adapters/next.js +0 -2
  132. package/dist/server/adapters/next.js.map +1 -1
  133. package/dist/server/index.d.ts +5 -5
  134. package/dist/server/index.js +5 -5
  135. package/dist/server/index.js.map +1 -1
  136. package/dist/server/metering.d.ts +9 -11
  137. package/dist/server/metering.d.ts.map +1 -1
  138. package/dist/server/metering.js +6 -8
  139. package/dist/server/metering.js.map +1 -1
  140. package/dist/server/post-paid.d.ts +8 -10
  141. package/dist/server/post-paid.d.ts.map +1 -1
  142. package/dist/server/post-paid.js +7 -9
  143. package/dist/server/post-paid.js.map +1 -1
  144. package/dist/x402/client.d.ts +5 -6
  145. package/dist/x402/client.d.ts.map +1 -1
  146. package/dist/x402/client.js +6 -7
  147. package/dist/x402/client.js.map +1 -1
  148. package/dist/x402/server.d.ts +5 -5
  149. package/dist/x402/server.d.ts.map +1 -1
  150. package/dist/x402/server.js +2 -2
  151. package/dist/x402/server.js.map +1 -1
  152. package/dist/x402/wire.d.ts +1 -1
  153. package/dist/x402/wire.js +1 -1
  154. package/dist/x402/wire.js.map +1 -1
  155. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/x402/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAoC,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AACvE,OAAO,EAAqB,KAAK,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,MAAM,EAAE,MAAM,eAAe,CAAC;AAGvF,OAAO,EAAkB,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,cAAc,CA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AAe,GAAG,OAAO,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACxG,wCAAwC;IACxC,QAAQ,IAAI,SAAS,kBAAkB,EAAE,CAAC;CAC3C;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,SAAS,YAAY,GAAG,YAAY,EACtE,OAAO,EAAE,iBAAiB,CAAC,GAAG,CAAC,GAC9B,UAAU,CAAC,GAAG,CAAC,CA+IjB"}
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * ## The signing is hand-rolled, and here is the check on it
15
15
  *
16
- * `@x402/evm` is the reference client for this scheme and it is built on viem.
16
+ * `@x402/evm` is the official client for this scheme and it is built on viem.
17
17
  * This package signs with ethers, so pulling it in would ship a second EVM
18
18
  * library to sign one struct. The struct is small enough to state:
19
19
  *
@@ -23,11 +23,10 @@
23
23
  * - primary type `TransferWithAuthorization(address from, address to, uint256
24
24
  * value, uint256 validAfter, uint256 validBefore, bytes32 nonce)` (EIP-3009);
25
25
  * - `validAfter` `0`, `validBefore` now plus `maxTimeoutSeconds`, and a random
26
- * 32-byte `nonce`, exactly as the reference `createEIP3009Payload` builds them.
26
+ * 32-byte `nonce`, exactly as `@x402/evm`'s `createEIP3009Payload` builds them.
27
27
  *
28
- * The test suite recovers the signer from every signature this file produces,
29
- * and the reference client was run over the same authorization while this was
30
- * written: the two signatures are byte for byte the same.
28
+ * The test suite recovers the signer from every signature this file produces
29
+ * against that domain and struct, so a drift from the scheme fails a test.
31
30
  *
32
31
  * Specification: scheme_exact_evm.md section 1, x402-specification-v2.md section 5.2.
33
32
  */
@@ -74,7 +73,7 @@ export const TRANSFER_WITH_AUTHORIZATION_TYPES = {
74
73
  /**
75
74
  * Signs one `exact` requirement.
76
75
  *
77
- * The domain and the struct are exactly what the reference client signs, so
76
+ * The domain and the struct are exactly what `@x402/evm` signs, so
78
77
  * the facilitator's recovery lands on `authorization.from`. The requirement is
79
78
  * re-validated here rather than trusted, because it arrived over the network.
80
79
  */
@@ -134,7 +133,7 @@ export async function signExactPayment(options) {
134
133
  resource: options.required.resource,
135
134
  accepted,
136
135
  payload: { signature: signature.value, authorization },
137
- // Echoed unchanged, as the reference client does: the server advertised
136
+ // Echoed unchanged, as `@x402/evm` does: the server advertised
138
137
  // them and validates that what comes back carries at least what it sent.
139
138
  ...(options.required.extensions === undefined ? {} : { extensions: options.required.extensions }),
140
139
  };
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/x402/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAe,MAAM,QAAQ,CAAC;AACvE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAuC,MAAM,eAAe,CAAC;AAEvF,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,cAAc,EAAwC,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AAC1D,OAAO,EACL,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GAMvB,MAAM,WAAW,CAAC;AAmCnB,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,MAAoC;IAC1E,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC;IAC/C,IAAI,OAAO,MAAM,KAAK,UAAU;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,QAAQ,GAAG,MAAM,IAAI,CACzB,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAY,EACvC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACV,QAAQ,EAAE,UAAmB;Q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: sign an EIP-3009 authorization for an `exact` requirement\n * and repeat the request with it.\n *\n * ## Where this sits in Tab\n *\n * Tab never asks an Agent to prepay. This client exists for the two moments a\n * prepayment is the right answer anyway: an Agent with no headroom that would\n * rather pay for one call than settle a tab first, and a Service fronting an\n * x402 upstream that has to pay the upstream before it can meter the Agent.\n * In both, the payment is one call's worth, signed by whoever holds the key,\n * and nothing about the Open Tab changes.\n *\n * ## The signing is hand-rolled, and here is the check on it\n *\n * `@x402/evm` is the reference client for this scheme and it is built on viem.\n * This package signs with ethers, so pulling it in would ship a second EVM\n * library to sign one struct. The struct is small enough to state:\n *\n * - EIP-712 domain `{ name, version, chainId, verifyingContract }`, with `name`\n * and `version` from `requirements.extra`, `chainId` from the CAIP-2 network,\n * and `verifyingContract` the token (`scheme_exact_evm.md`, section 1);\n * - primary type `TransferWithAuthorization(address from, address to, uint256\n * value, uint256 validAfter, uint256 validBefore, bytes32 nonce)` (EIP-3009);\n * - `validAfter` `0`, `validBefore` now plus `maxTimeoutSeconds`, and a random\n * 32-byte `nonce`, exactly as the reference `createEIP3009Payload` builds them.\n *\n * The test suite recovers the signer from every signature this file produces,\n * and the reference client was run over the same authorization while this was\n * written: the two signatures are byte for byte the same.\n *\n * Specification: scheme_exact_evm.md section 1, x402-specification-v2.md section 5.2.\n */\n\nimport { getAddress, hexlify, randomBytes, type Signer } from \"ethers\";\nimport { causeOf, ok, wrap, type Address, type Hex, type Result } from \"../_shared/index.js\";\n\nimport { fail, upstreamError, validationError } from \"../errors.js\";\nimport { headerReaderOf, type HeaderReader, type HeaderRecord } from \"../http/headers.js\";\nimport { defaultLogger, type Logger } from \"../logger.js\";\nimport {\n X402_HEADER,\n X402_VERSION,\n chainIdOfNetwork,\n encodePaymentSignature,\n readPaymentRequired,\n readPaymentResponse,\n selectExactRequirement,\n type PaymentPayload,\n type PaymentRequired,\n type PaymentRequirements,\n type RequirementFilter,\n type SettleResponse,\n} from \"./wire.js\";\n\n/**\n * What signs an x402 payment.\n *\n * Structural rather than the `ethers` class, so a test double or any wallet\n * that can sign typed data satisfies it. An `ethers.Signer` does as it stands;\n * the assertion below fails to compile if that ever stops being true.\n */\nexport interface X402Signer {\n getAddress(): Promise<string>;\n signTypedData(\n domain: { name: string; version: string; chainId: bigint | number; verifyingContract: string },\n types: Record<string, readonly { name: string; type: string }[]>,\n value: Record<string, unknown>,\n ): Promise<string>;\n}\n\ntype Assert<T extends true> = T;\ntype SignerIsAccepted = Assert<Signer extends X402Signer ? true : false>;\nexport type X402SignerAcceptsEthersSigner = SignerIsAccepted;\n\n/**\n * A signer built only when a payment is about to be signed.\n *\n * Returning `undefined` means \"not available here\", the same answer a payment\n * strategy factory may give: the offer is declined and the `402` stands as the\n * credit decision it was. That is what keeps every read keyless: a config file\n * declares the factory, and nothing calls it until a prepayment is the answer.\n */\nexport type X402SignerFactory = () => X402Signer | undefined | Promise<X402Signer | undefined>;\n\n/** A signer, or a factory that may produce one. */\nexport type X402SignerSource = X402Signer | X402SignerFactory;\n\n/** Resolves a source. `ok(undefined)` is a factory declining; `err` is a factory that threw. */\nexport async function resolveX402Signer(source: X402SignerSource | undefined): Promise<Result<X402Signer | undefined>> {\n if (source === undefined) return ok(undefined);\n if (typeof source !== \"function\") return ok(source);\n const produced = await wrap(\n async () => (await source()) as unknown,\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNER_FACTORY_FAILED\",\n message: \"the x402 signer factory threw\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!produced.ok) return produced;\n if (produced.value === undefined || produced.value === null) return ok(undefined);\n const candidate = produced.value as Partial<X402Signer>;\n if (typeof candidate.getAddress !== \"function\" || typeof candidate.signTypedData !== \"function\") {\n return validationError(\"X402_SIGNER_INVALID\", \"the x402 signer factory returned something without getAddress() and signTypedData()\");\n }\n return ok(candidate as X402Signer);\n}\n\n/** The EIP-712 type of the struct EIP-3009 `transferWithAuthorization` verifies. */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/** The authorization as it goes on the wire: every number a decimal string. */\nexport interface Eip3009Authorization {\n readonly from: string;\n readonly to: string;\n readonly value: string;\n readonly validAfter: string;\n readonly validBefore: string;\n readonly nonce: Hex;\n}\n\nexport interface SignExactPaymentOptions {\n readonly signer: X402Signer;\n /** The server's `PaymentRequired`, echoed into the payload as `resource` and `extensions`. */\n readonly required: PaymentRequired;\n /** The entry of `required.accepts` being paid. */\n readonly accepted: PaymentRequirements;\n /** Seconds since the epoch. Defaults to the wall clock. */\n readonly now?: () => number;\n /** A 32-byte nonce. Defaults to random. A test passes a fixed one. */\n readonly nonce?: () => Hex;\n}\n\n/** What a signature is for, kept beside the payload so a receipt can be built without re-reading it. */\nexport interface SignedExactPayment {\n readonly payload: PaymentPayload;\n readonly authorization: Eip3009Authorization;\n readonly chainId: bigint;\n readonly payer: Address;\n}\n\n/**\n * Signs one `exact` requirement.\n *\n * The domain and the struct are exactly what the reference client signs, so\n * the facilitator's recovery lands on `authorization.from`. The requirement is\n * re-validated here rather than trusted, because it arrived over the network.\n */\nexport async function signExactPayment(options: SignExactPaymentOptions): Promise<Result<SignedExactPayment>> {\n const { accepted } = options;\n const chainId = chainIdOfNetwork(accepted.network);\n if (!chainId.ok) return chainId;\n const name = accepted.extra?.[\"name\"];\n const version = accepted.extra?.[\"version\"];\n if (typeof name !== \"string\" || typeof version !== \"string\") {\n return validationError(\n \"X402_DOMAIN_MISSING\",\n `the requirement for ${accepted.asset} carries no EIP-712 domain name and version in extra, so an EIP-3009 authorization cannot be signed for it`,\n { details: { asset: accepted.asset, network: accepted.network } },\n );\n }\n if (!/^[0-9]+$/.test(accepted.amount)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `amount \\`${accepted.amount}\\` is not a decimal integer of atomic units`);\n }\n\n const from = await wrap(\n async () => options.signer.getAddress(),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNER_UNAVAILABLE\",\n message: \"the x402 signer could not report its address\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!from.ok) return from;\n\n const checksummed = wrapAddresses(from.value, accepted.payTo, accepted.asset);\n if (!checksummed.ok) return checksummed;\n const [payer, payTo, asset] = checksummed.value;\n\n const nowSeconds = options.now === undefined ? Math.floor(Date.now() / 1000) : options.now();\n const authorization: Eip3009Authorization = {\n from: payer,\n to: payTo,\n value: accepted.amount,\n validAfter: \"0\",\n validBefore: (nowSeconds + Math.floor(accepted.maxTimeoutSeconds)).toString(10),\n nonce: options.nonce === undefined ? (hexlify(randomBytes(32)) as Hex) : options.nonce(),\n };\n\n const signature = await wrap(\n async () =>\n options.signer.signTypedData(\n { name, version, chainId: chainId.value, verifyingContract: asset },\n TRANSFER_WITH_AUTHORIZATION_TYPES,\n {\n from: authorization.from,\n to: authorization.to,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n },\n ),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNING_FAILED\",\n message: \"the x402 signer refused to sign the EIP-3009 authorization\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!signature.ok) return signature;\n\n const payload: PaymentPayload = {\n x402Version: X402_VERSION,\n resource: options.required.resource,\n accepted,\n payload: { signature: signature.value, authorization },\n // Echoed unchanged, as the reference client does: the server advertised\n // them and validates that what comes back carries at least what it sent.\n ...(options.required.extensions === undefined ? {} : { extensions: options.required.extensions }),\n };\n return ok({ payload, authorization, chainId: chainId.value, payer: payer.toLowerCase() as Address });\n}\n\n/** Checksums the three addresses a payload carries, or names the one that is not an address. */\nfunction wrapAddresses(from: string, payTo: string, asset: string): Result<[string, string, string]> {\n const checked: string[] = [];\n for (const [label, value] of [\n [\"signer address\", from],\n [\"payTo\", payTo],\n [\"asset\", asset],\n ] as const) {\n try {\n checked.push(getAddress(value));\n } catch {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `${label} \\`${value}\\` is not a 20-byte address`, {\n details: { field: label, value },\n });\n }\n }\n return ok(checked as [string, string, string]);\n}\n\n/** One payment this client made, as the facilitator reported it back. */\nexport interface X402PaymentReceipt {\n /** The settlement transaction hash. Empty when the server reported success without one. */\n readonly txHash: string;\n readonly network: string;\n readonly chainId: bigint;\n /** Atomic units of `asset`, as the requirement priced it. */\n readonly amount: bigint;\n readonly asset: Address;\n readonly payTo: Address;\n readonly payer: Address;\n /** The absolute URL the payment bought. */\n readonly url: string;\n readonly requirement: PaymentRequirements;\n readonly settlement: SettleResponse;\n readonly observedAt: number;\n}\n\n/** The little of a response this client reads. Structural, as in `client-402.ts`. */\nexport interface X402Response {\n readonly status: number;\n readonly headers: HeaderReader | HeaderRecord;\n readonly body?: unknown;\n readonly bodyUsed?: unknown;\n}\n\nexport interface X402FetchInit {\n readonly headers: Readonly<Record<string, string>>;\n readonly [option: string]: unknown;\n}\n\nexport type X402Fetch<Res extends X402Response> = (url: string, init: X402FetchInit) => Promise<Res>;\n\nexport interface X402ClientOptions<Res extends X402Response = X402Response> extends RequirementFilter {\n readonly signer: X402Signer;\n readonly fetchImpl?: X402Fetch<Res>;\n /**\n * Consulted after the server's `402` and before anything is signed. A refusal\n * stops the payment and is returned as the error. This is where a Service\n * fronting an upstream checks that the Agent it will meter has the headroom\n * before the Service's own funds move.\n */\n readonly authorise?: (requirement: PaymentRequirements, required: PaymentRequired) => Promise<Result<void>> | Result<void>;\n readonly onPayment?: (receipt: X402PaymentReceipt) => void;\n readonly logger?: Logger;\n /** Milliseconds since the epoch, for `observedAt`. Defaults to `Date.now`. */\n readonly now?: () => number;\n /** Seconds since the epoch, for `validBefore`. Defaults to the wall clock. */\n readonly nowSeconds?: () => number;\n readonly nonce?: () => Hex;\n}\n\n/** What one call did: the response, and the payment that bought it if one did. */\nexport interface X402FetchResult<Res extends X402Response = X402Response> {\n readonly response: Res;\n readonly payment?: X402PaymentReceipt;\n}\n\nexport interface X402Client<Res extends X402Response = X402Response> {\n /**\n * Sends the request; on a `402` carrying `PAYMENT-REQUIRED`, signs and sends\n * it once more with `PAYMENT-SIGNATURE`. Exactly once: a second `402` means\n * the payment was refused, and that is returned as an error naming why.\n */\n fetch(url: string, init?: X402FetchInit): Promise<Result<X402FetchResult<Res>>>;\n /**\n * Pays a `402` the caller already holds: the same second step, for a caller\n * that made the first request itself.\n */\n pay(url: string, init: X402FetchInit, required: PaymentRequired): Promise<Result<X402FetchResult<Res>>>;\n /** Every payment made, oldest first. */\n payments(): readonly X402PaymentReceipt[];\n}\n\n/**\n * Builds the client. Construction is total; every failure belongs to a call.\n */\nexport function createX402Client<Res extends X402Response = X402Response>(\n options: X402ClientOptions<Res>,\n): X402Client<Res> {\n const logger = options.logger ?? defaultLogger;\n const now = options.now ?? (() => Date.now());\n const history: X402PaymentReceipt[] = [];\n const filter: RequirementFilter = {\n ...(options.chainId === undefined ? {} : { chainId: options.chainId }),\n ...(options.asset === undefined ? {} : { asset: options.asset }),\n ...(options.maxAmount === undefined ? {} : { maxAmount: options.maxAmount }),\n };\n\n const send = async (url: string, init: X402FetchInit, attempt: 1 | 2): Promise<Result<Res>> => {\n const impl = options.fetchImpl ?? hostFetch<Res>();\n if (impl === undefined) {\n return upstreamError(\"FETCH_UNAVAILABLE\", \"this host has no global fetch; supply fetchImpl, or run on Node 20.10 or later\");\n }\n const sent = await wrap(\n async () => impl(url, init),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"FETCH_FAILED\",\n message: `the request to ${url} did not complete`,\n retryable: true,\n details: { url, attempt },\n cause: causeOf(error),\n }),\n );\n if (!sent.ok) return sent;\n if (!looksLikeResponse(sent.value)) {\n return upstreamError(\"FETCH_RESPONSE_INVALID\", `the fetch given to this client returned something that is not a response for ${url}`, {\n details: { url, attempt },\n });\n }\n return ok(sent.value);\n };\n\n const pay = async (url: string, init: X402FetchInit, required: PaymentRequired): Promise<Result<X402FetchResult<Res>>> => {\n const accepted = selectExactRequirement(required, filter);\n if (!accepted.ok) return accepted;\n\n if (options.authorise !== undefined) {\n const allowed = await wrap(\n async () => options.authorise?.(accepted.value, required),\n (error) => ({\n category: \"INTERNAL\" as const,\n code: \"X402_AUTHORISE_THREW\",\n message: \"the authorise hook threw, so nothing was signed\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!allowed.ok) return allowed;\n if (allowed.value !== undefined && !allowed.value.ok) return allowed.value;\n }\n\n if (!isReplayable(init[\"body\"])) {\n return validationError(\n \"REQUEST_BODY_NOT_REPLAYABLE\",\n `${url} asks for payment and the request body is a stream, which cannot be sent a second time; buffer the body before calling`,\n { details: { url } },\n );\n }\n\n const signed = await signExactPayment({\n signer: options.signer,\n required,\n accepted: accepted.value,\n ...(options.nowSeconds === undefined ? {} : { now: options.nowSeconds }),\n ...(options.nonce === undefined ? {} : { nonce: options.nonce }),\n });\n if (!signed.ok) return signed;\n\n const header = encodePaymentSignature(signed.value.payload);\n if (!header.ok) return header;\n\n const paid = await send(url, { ...init, headers: { ...init.headers, [X402_HEADER.paymentSignature]: header.value } }, 2);\n if (!paid.ok) return paid;\n const response = paid.value;\n\n const settlement = readPaymentResponse(headerReaderOf(response.headers));\n if (!settlement.ok) {\n discard(response, logger);\n return settlement;\n }\n\n if (response.status === 402) {\n discard(response, logger);\n const reason = settlement.value?.errorReason ?? readError(response.headers) ?? \"the server did not say why\";\n return fail(\"LIMIT\", \"X402_PAYMENT_REJECTED\", `${url} refused the signed payment: ${reason}`, {\n retryable: false,\n details: {\n url,\n reason,\n amount: accepted.value.amount,\n asset: accepted.value.asset.toLowerCase(),\n network: accepted.value.network,\n },\n });\n }\n\n const receipt: X402PaymentReceipt = {\n txHash: settlement.value?.transaction ?? \"\",\n network: accepted.value.network,\n chainId: signed.value.chainId,\n amount: BigInt(accepted.value.amount),\n asset: accepted.value.asset.toLowerCase() as Address,\n payTo: accepted.value.payTo.toLowerCase() as Address,\n payer: signed.value.payer,\n url,\n requirement: accepted.value,\n settlement: settlement.value ?? { success: response.status < 400, transaction: \"\", network: accepted.value.network },\n observedAt: now(),\n };\n history.push(receipt);\n if (options.onPayment !== undefined) {\n try {\n options.onPayment(receipt);\n } catch (error) {\n logger.warn(\"onPayment threw and the payment was recorded anyway\", { url, error: causeOf(error).message });\n }\n }\n return ok({ response, payment: receipt });\n };\n\n return {\n async fetch(url, init = { headers: {} }) {\n const first = await send(url, init, 1);\n if (!first.ok) return first;\n if (first.value.status !== 402) return ok({ response: first.value });\n\n const required = readPaymentRequired(headerReaderOf(first.value.headers));\n discard(first.value, logger);\n if (!required.ok) return required;\n if (required.value === undefined) {\n return fail(\"LIMIT\", \"X402_PAYMENT_REQUIRED_MISSING\", `${url} answered 402 without a ${X402_HEADER.paymentRequired} header, so there is nothing to pay`, {\n retryable: false,\n details: { url },\n });\n }\n return pay(url, init, required.value);\n },\n pay,\n payments: () => [...history],\n };\n}\n\n/** The `error` field of a `PAYMENT-REQUIRED` a refusal may carry, when it carries one. */\nfunction readError(headers: HeaderReader | HeaderRecord): string | undefined {\n const required = readPaymentRequired(headers);\n return required.ok ? required.value?.error : undefined;\n}\n\nfunction looksLikeResponse(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { status?: unknown; headers?: unknown };\n return typeof candidate.status === \"number\" && typeof candidate.headers === \"object\" && candidate.headers !== null;\n}\n\n/** A stream cannot be sent twice; everything else can. */\nfunction isReplayable(body: unknown): boolean {\n if (body === undefined || body === null || typeof body !== \"object\") return true;\n const candidate = body as { getReader?: unknown; [Symbol.asyncIterator]?: unknown };\n return typeof candidate.getReader !== \"function\" && typeof candidate[Symbol.asyncIterator] !== \"function\";\n}\n\n/** Releases a response that is not going out, so its connection does not wait for the collector. */\nfunction discard(response: X402Response, logger: Logger): void {\n const body = response.body as { cancel?: unknown } | null | undefined;\n if (body === null || body === undefined || typeof body.cancel !== \"function\" || response.bodyUsed === true) return;\n try {\n const cancelled = (body.cancel as () => unknown)();\n if (typeof (cancelled as { catch?: unknown })?.catch === \"function\") {\n (cancelled as Promise<unknown>).catch((error: unknown) => {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n });\n }\n } catch (error) {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n }\n}\n\nfunction hostFetch<Res extends X402Response>(): X402Fetch<Res> | undefined {\n const candidate = (globalThis as { fetch?: unknown }).fetch;\n return typeof candidate === \"function\" ? (candidate as X402Fetch<Res>) : undefined;\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/x402/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,WAAW,EAAe,MAAM,QAAQ,CAAC;AACvE,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAuC,MAAM,eAAe,CAAC;AAEvF,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,cAAc,EAAwC,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AAC1D,OAAO,EACL,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GAMvB,MAAM,WAAW,CAAC;AAmCnB,gGAAgG;AAChG,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,MAAoC;IAC1E,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC;IAC/C,IAAI,OAAO,MAAM,KAAK,UAAU;QAAE,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,QAAQ,GAAG,MAAM,IAAI,CACzB,K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5D,OAAO,OAAO,SAAS,KAAK,UAAU,CAAC,CAAC,CAAE,SAA4B,CAAC,CAAC,CAAC,SAAS,CAAC;AACrF,CAAC","sourcesContent":["/**\n * The x402 client: sign an EIP-3009 authorization for an `exact` requirement\n * and repeat the request with it.\n *\n * ## Where this sits in Tab\n *\n * Tab never asks an Agent to prepay. This client exists for the two moments a\n * prepayment is the right answer anyway: an Agent with no headroom that would\n * rather pay for one call than settle a tab first, and a Service fronting an\n * x402 upstream that has to pay the upstream before it can meter the Agent.\n * In both, the payment is one call's worth, signed by whoever holds the key,\n * and nothing about the Open Tab changes.\n *\n * ## The signing is hand-rolled, and here is the check on it\n *\n * `@x402/evm` is the official client for this scheme and it is built on viem.\n * This package signs with ethers, so pulling it in would ship a second EVM\n * library to sign one struct. The struct is small enough to state:\n *\n * - EIP-712 domain `{ name, version, chainId, verifyingContract }`, with `name`\n * and `version` from `requirements.extra`, `chainId` from the CAIP-2 network,\n * and `verifyingContract` the token (`scheme_exact_evm.md`, section 1);\n * - primary type `TransferWithAuthorization(address from, address to, uint256\n * value, uint256 validAfter, uint256 validBefore, bytes32 nonce)` (EIP-3009);\n * - `validAfter` `0`, `validBefore` now plus `maxTimeoutSeconds`, and a random\n * 32-byte `nonce`, exactly as `@x402/evm`'s `createEIP3009Payload` builds them.\n *\n * The test suite recovers the signer from every signature this file produces\n * against that domain and struct, so a drift from the scheme fails a test.\n *\n * Specification: scheme_exact_evm.md section 1, x402-specification-v2.md section 5.2.\n */\n\nimport { getAddress, hexlify, randomBytes, type Signer } from \"ethers\";\nimport { causeOf, ok, wrap, type Address, type Hex, type Result } from \"../_shared/index.js\";\n\nimport { fail, upstreamError, validationError } from \"../errors.js\";\nimport { headerReaderOf, type HeaderReader, type HeaderRecord } from \"../http/headers.js\";\nimport { defaultLogger, type Logger } from \"../logger.js\";\nimport {\n X402_HEADER,\n X402_VERSION,\n chainIdOfNetwork,\n encodePaymentSignature,\n readPaymentRequired,\n readPaymentResponse,\n selectExactRequirement,\n type PaymentPayload,\n type PaymentRequired,\n type PaymentRequirements,\n type RequirementFilter,\n type SettleResponse,\n} from \"./wire.js\";\n\n/**\n * What signs an x402 payment.\n *\n * Structural rather than the `ethers` class, so a test double or any wallet\n * that can sign typed data satisfies it. An `ethers.Signer` does as it stands;\n * the assertion below fails to compile if that ever stops being true.\n */\nexport interface X402Signer {\n getAddress(): Promise<string>;\n signTypedData(\n domain: { name: string; version: string; chainId: bigint | number; verifyingContract: string },\n types: Record<string, readonly { name: string; type: string }[]>,\n value: Record<string, unknown>,\n ): Promise<string>;\n}\n\ntype Assert<T extends true> = T;\ntype SignerIsAccepted = Assert<Signer extends X402Signer ? true : false>;\nexport type X402SignerAcceptsEthersSigner = SignerIsAccepted;\n\n/**\n * A signer built only when a payment is about to be signed.\n *\n * Returning `undefined` means \"not available here\", the same answer a payment\n * strategy factory may give: the offer is declined and the `402` stands as the\n * credit decision it was. That is what keeps every read keyless: a config file\n * declares the factory, and nothing calls it until a prepayment is the answer.\n */\nexport type X402SignerFactory = () => X402Signer | undefined | Promise<X402Signer | undefined>;\n\n/** A signer, or a factory that may produce one. */\nexport type X402SignerSource = X402Signer | X402SignerFactory;\n\n/** Resolves a source. `ok(undefined)` is a factory declining; `err` is a factory that threw. */\nexport async function resolveX402Signer(source: X402SignerSource | undefined): Promise<Result<X402Signer | undefined>> {\n if (source === undefined) return ok(undefined);\n if (typeof source !== \"function\") return ok(source);\n const produced = await wrap(\n async () => (await source()) as unknown,\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNER_FACTORY_FAILED\",\n message: \"the x402 signer factory threw\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!produced.ok) return produced;\n if (produced.value === undefined || produced.value === null) return ok(undefined);\n const candidate = produced.value as Partial<X402Signer>;\n if (typeof candidate.getAddress !== \"function\" || typeof candidate.signTypedData !== \"function\") {\n return validationError(\"X402_SIGNER_INVALID\", \"the x402 signer factory returned something without getAddress() and signTypedData()\");\n }\n return ok(candidate as X402Signer);\n}\n\n/** The EIP-712 type of the struct EIP-3009 `transferWithAuthorization` verifies. */\nexport const TRANSFER_WITH_AUTHORIZATION_TYPES = {\n TransferWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/** The authorization as it goes on the wire: every number a decimal string. */\nexport interface Eip3009Authorization {\n readonly from: string;\n readonly to: string;\n readonly value: string;\n readonly validAfter: string;\n readonly validBefore: string;\n readonly nonce: Hex;\n}\n\nexport interface SignExactPaymentOptions {\n readonly signer: X402Signer;\n /** The server's `PaymentRequired`, echoed into the payload as `resource` and `extensions`. */\n readonly required: PaymentRequired;\n /** The entry of `required.accepts` being paid. */\n readonly accepted: PaymentRequirements;\n /** Seconds since the epoch. Defaults to the wall clock. */\n readonly now?: () => number;\n /** A 32-byte nonce. Defaults to random. A test passes a fixed one. */\n readonly nonce?: () => Hex;\n}\n\n/** What a signature is for, kept beside the payload so a receipt can be built without re-reading it. */\nexport interface SignedExactPayment {\n readonly payload: PaymentPayload;\n readonly authorization: Eip3009Authorization;\n readonly chainId: bigint;\n readonly payer: Address;\n}\n\n/**\n * Signs one `exact` requirement.\n *\n * The domain and the struct are exactly what `@x402/evm` signs, so\n * the facilitator's recovery lands on `authorization.from`. The requirement is\n * re-validated here rather than trusted, because it arrived over the network.\n */\nexport async function signExactPayment(options: SignExactPaymentOptions): Promise<Result<SignedExactPayment>> {\n const { accepted } = options;\n const chainId = chainIdOfNetwork(accepted.network);\n if (!chainId.ok) return chainId;\n const name = accepted.extra?.[\"name\"];\n const version = accepted.extra?.[\"version\"];\n if (typeof name !== \"string\" || typeof version !== \"string\") {\n return validationError(\n \"X402_DOMAIN_MISSING\",\n `the requirement for ${accepted.asset} carries no EIP-712 domain name and version in extra, so an EIP-3009 authorization cannot be signed for it`,\n { details: { asset: accepted.asset, network: accepted.network } },\n );\n }\n if (!/^[0-9]+$/.test(accepted.amount)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `amount \\`${accepted.amount}\\` is not a decimal integer of atomic units`);\n }\n\n const from = await wrap(\n async () => options.signer.getAddress(),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNER_UNAVAILABLE\",\n message: \"the x402 signer could not report its address\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!from.ok) return from;\n\n const checksummed = wrapAddresses(from.value, accepted.payTo, accepted.asset);\n if (!checksummed.ok) return checksummed;\n const [payer, payTo, asset] = checksummed.value;\n\n const nowSeconds = options.now === undefined ? Math.floor(Date.now() / 1000) : options.now();\n const authorization: Eip3009Authorization = {\n from: payer,\n to: payTo,\n value: accepted.amount,\n validAfter: \"0\",\n validBefore: (nowSeconds + Math.floor(accepted.maxTimeoutSeconds)).toString(10),\n nonce: options.nonce === undefined ? (hexlify(randomBytes(32)) as Hex) : options.nonce(),\n };\n\n const signature = await wrap(\n async () =>\n options.signer.signTypedData(\n { name, version, chainId: chainId.value, verifyingContract: asset },\n TRANSFER_WITH_AUTHORIZATION_TYPES,\n {\n from: authorization.from,\n to: authorization.to,\n value: BigInt(authorization.value),\n validAfter: BigInt(authorization.validAfter),\n validBefore: BigInt(authorization.validBefore),\n nonce: authorization.nonce,\n },\n ),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"X402_SIGNING_FAILED\",\n message: \"the x402 signer refused to sign the EIP-3009 authorization\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!signature.ok) return signature;\n\n const payload: PaymentPayload = {\n x402Version: X402_VERSION,\n resource: options.required.resource,\n accepted,\n payload: { signature: signature.value, authorization },\n // Echoed unchanged, as `@x402/evm` does: the server advertised\n // them and validates that what comes back carries at least what it sent.\n ...(options.required.extensions === undefined ? {} : { extensions: options.required.extensions }),\n };\n return ok({ payload, authorization, chainId: chainId.value, payer: payer.toLowerCase() as Address });\n}\n\n/** Checksums the three addresses a payload carries, or names the one that is not an address. */\nfunction wrapAddresses(from: string, payTo: string, asset: string): Result<[string, string, string]> {\n const checked: string[] = [];\n for (const [label, value] of [\n [\"signer address\", from],\n [\"payTo\", payTo],\n [\"asset\", asset],\n ] as const) {\n try {\n checked.push(getAddress(value));\n } catch {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `${label} \\`${value}\\` is not a 20-byte address`, {\n details: { field: label, value },\n });\n }\n }\n return ok(checked as [string, string, string]);\n}\n\n/** One payment this client made, as the facilitator reported it back. */\nexport interface X402PaymentReceipt {\n /** The settlement transaction hash. Empty when the server reported success without one. */\n readonly txHash: string;\n readonly network: string;\n readonly chainId: bigint;\n /** Atomic units of `asset`, as the requirement priced it. */\n readonly amount: bigint;\n readonly asset: Address;\n readonly payTo: Address;\n readonly payer: Address;\n /** The absolute URL the payment bought. */\n readonly url: string;\n readonly requirement: PaymentRequirements;\n readonly settlement: SettleResponse;\n readonly observedAt: number;\n}\n\n/** The little of a response this client reads. Structural, as in `client-402.ts`. */\nexport interface X402Response {\n readonly status: number;\n readonly headers: HeaderReader | HeaderRecord;\n readonly body?: unknown;\n readonly bodyUsed?: unknown;\n}\n\nexport interface X402FetchInit {\n readonly headers: Readonly<Record<string, string>>;\n readonly [option: string]: unknown;\n}\n\nexport type X402Fetch<Res extends X402Response> = (url: string, init: X402FetchInit) => Promise<Res>;\n\nexport interface X402ClientOptions<Res extends X402Response = X402Response> extends RequirementFilter {\n readonly signer: X402Signer;\n readonly fetchImpl?: X402Fetch<Res>;\n /**\n * Consulted after the server's `402` and before anything is signed. A refusal\n * stops the payment and is returned as the error. This is where a Service\n * fronting an upstream checks that the Agent it will meter has the headroom\n * before the Service's own funds move.\n */\n readonly authorise?: (requirement: PaymentRequirements, required: PaymentRequired) => Promise<Result<void>> | Result<void>;\n readonly onPayment?: (receipt: X402PaymentReceipt) => void;\n readonly logger?: Logger;\n /** Milliseconds since the epoch, for `observedAt`. Defaults to `Date.now`. */\n readonly now?: () => number;\n /** Seconds since the epoch, for `validBefore`. Defaults to the wall clock. */\n readonly nowSeconds?: () => number;\n readonly nonce?: () => Hex;\n}\n\n/** What one call did: the response, and the payment that bought it if one did. */\nexport interface X402FetchResult<Res extends X402Response = X402Response> {\n readonly response: Res;\n readonly payment?: X402PaymentReceipt;\n}\n\nexport interface X402Client<Res extends X402Response = X402Response> {\n /**\n * Sends the request; on a `402` carrying `PAYMENT-REQUIRED`, signs and sends\n * it once more with `PAYMENT-SIGNATURE`. Exactly once: a second `402` means\n * the payment was refused, and that is returned as an error naming why.\n */\n fetch(url: string, init?: X402FetchInit): Promise<Result<X402FetchResult<Res>>>;\n /**\n * Pays a `402` the caller already holds: the same second step, for a caller\n * that made the first request itself.\n */\n pay(url: string, init: X402FetchInit, required: PaymentRequired): Promise<Result<X402FetchResult<Res>>>;\n /** Every payment made, oldest first. */\n payments(): readonly X402PaymentReceipt[];\n}\n\n/**\n * Builds the client. Construction is total; every failure belongs to a call.\n */\nexport function createX402Client<Res extends X402Response = X402Response>(\n options: X402ClientOptions<Res>,\n): X402Client<Res> {\n const logger = options.logger ?? defaultLogger;\n const now = options.now ?? (() => Date.now());\n const history: X402PaymentReceipt[] = [];\n const filter: RequirementFilter = {\n ...(options.chainId === undefined ? {} : { chainId: options.chainId }),\n ...(options.asset === undefined ? {} : { asset: options.asset }),\n ...(options.maxAmount === undefined ? {} : { maxAmount: options.maxAmount }),\n };\n\n const send = async (url: string, init: X402FetchInit, attempt: 1 | 2): Promise<Result<Res>> => {\n const impl = options.fetchImpl ?? hostFetch<Res>();\n if (impl === undefined) {\n return upstreamError(\"FETCH_UNAVAILABLE\", \"this host has no global fetch; supply fetchImpl, or run on Node 20.10 or later\");\n }\n const sent = await wrap(\n async () => impl(url, init),\n (error) => ({\n category: \"UPSTREAM\" as const,\n code: \"FETCH_FAILED\",\n message: `the request to ${url} did not complete`,\n retryable: true,\n details: { url, attempt },\n cause: causeOf(error),\n }),\n );\n if (!sent.ok) return sent;\n if (!looksLikeResponse(sent.value)) {\n return upstreamError(\"FETCH_RESPONSE_INVALID\", `the fetch given to this client returned something that is not a response for ${url}`, {\n details: { url, attempt },\n });\n }\n return ok(sent.value);\n };\n\n const pay = async (url: string, init: X402FetchInit, required: PaymentRequired): Promise<Result<X402FetchResult<Res>>> => {\n const accepted = selectExactRequirement(required, filter);\n if (!accepted.ok) return accepted;\n\n if (options.authorise !== undefined) {\n const allowed = await wrap(\n async () => options.authorise?.(accepted.value, required),\n (error) => ({\n category: \"INTERNAL\" as const,\n code: \"X402_AUTHORISE_THREW\",\n message: \"the authorise hook threw, so nothing was signed\",\n retryable: false,\n cause: causeOf(error),\n }),\n );\n if (!allowed.ok) return allowed;\n if (allowed.value !== undefined && !allowed.value.ok) return allowed.value;\n }\n\n if (!isReplayable(init[\"body\"])) {\n return validationError(\n \"REQUEST_BODY_NOT_REPLAYABLE\",\n `${url} asks for payment and the request body is a stream, which cannot be sent a second time; buffer the body before calling`,\n { details: { url } },\n );\n }\n\n const signed = await signExactPayment({\n signer: options.signer,\n required,\n accepted: accepted.value,\n ...(options.nowSeconds === undefined ? {} : { now: options.nowSeconds }),\n ...(options.nonce === undefined ? {} : { nonce: options.nonce }),\n });\n if (!signed.ok) return signed;\n\n const header = encodePaymentSignature(signed.value.payload);\n if (!header.ok) return header;\n\n const paid = await send(url, { ...init, headers: { ...init.headers, [X402_HEADER.paymentSignature]: header.value } }, 2);\n if (!paid.ok) return paid;\n const response = paid.value;\n\n const settlement = readPaymentResponse(headerReaderOf(response.headers));\n if (!settlement.ok) {\n discard(response, logger);\n return settlement;\n }\n\n if (response.status === 402) {\n discard(response, logger);\n const reason = settlement.value?.errorReason ?? readError(response.headers) ?? \"the server did not say why\";\n return fail(\"LIMIT\", \"X402_PAYMENT_REJECTED\", `${url} refused the signed payment: ${reason}`, {\n retryable: false,\n details: {\n url,\n reason,\n amount: accepted.value.amount,\n asset: accepted.value.asset.toLowerCase(),\n network: accepted.value.network,\n },\n });\n }\n\n const receipt: X402PaymentReceipt = {\n txHash: settlement.value?.transaction ?? \"\",\n network: accepted.value.network,\n chainId: signed.value.chainId,\n amount: BigInt(accepted.value.amount),\n asset: accepted.value.asset.toLowerCase() as Address,\n payTo: accepted.value.payTo.toLowerCase() as Address,\n payer: signed.value.payer,\n url,\n requirement: accepted.value,\n settlement: settlement.value ?? { success: response.status < 400, transaction: \"\", network: accepted.value.network },\n observedAt: now(),\n };\n history.push(receipt);\n if (options.onPayment !== undefined) {\n try {\n options.onPayment(receipt);\n } catch (error) {\n logger.warn(\"onPayment threw and the payment was recorded anyway\", { url, error: causeOf(error).message });\n }\n }\n return ok({ response, payment: receipt });\n };\n\n return {\n async fetch(url, init = { headers: {} }) {\n const first = await send(url, init, 1);\n if (!first.ok) return first;\n if (first.value.status !== 402) return ok({ response: first.value });\n\n const required = readPaymentRequired(headerReaderOf(first.value.headers));\n discard(first.value, logger);\n if (!required.ok) return required;\n if (required.value === undefined) {\n return fail(\"LIMIT\", \"X402_PAYMENT_REQUIRED_MISSING\", `${url} answered 402 without a ${X402_HEADER.paymentRequired} header, so there is nothing to pay`, {\n retryable: false,\n details: { url },\n });\n }\n return pay(url, init, required.value);\n },\n pay,\n payments: () => [...history],\n };\n}\n\n/** The `error` field of a `PAYMENT-REQUIRED` a refusal may carry, when it carries one. */\nfunction readError(headers: HeaderReader | HeaderRecord): string | undefined {\n const required = readPaymentRequired(headers);\n return required.ok ? required.value?.error : undefined;\n}\n\nfunction looksLikeResponse(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { status?: unknown; headers?: unknown };\n return typeof candidate.status === \"number\" && typeof candidate.headers === \"object\" && candidate.headers !== null;\n}\n\n/** A stream cannot be sent twice; everything else can. */\nfunction isReplayable(body: unknown): boolean {\n if (body === undefined || body === null || typeof body !== \"object\") return true;\n const candidate = body as { getReader?: unknown; [Symbol.asyncIterator]?: unknown };\n return typeof candidate.getReader !== \"function\" && typeof candidate[Symbol.asyncIterator] !== \"function\";\n}\n\n/** Releases a response that is not going out, so its connection does not wait for the collector. */\nfunction discard(response: X402Response, logger: Logger): void {\n const body = response.body as { cancel?: unknown } | null | undefined;\n if (body === null || body === undefined || typeof body.cancel !== \"function\" || response.bodyUsed === true) return;\n try {\n const cancelled = (body.cancel as () => unknown)();\n if (typeof (cancelled as { catch?: unknown })?.catch === \"function\") {\n (cancelled as Promise<unknown>).catch((error: unknown) => {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n });\n }\n } catch (error) {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n }\n}\n\nfunction hostFetch<Res extends X402Response>(): X402Fetch<Res> | undefined {\n const candidate = (globalThis as { fetch?: unknown }).fetch;\n return typeof candidate === \"function\" ? (candidate as X402Fetch<Res>) : undefined;\n}\n"]}
@@ -26,7 +26,7 @@
26
26
  * The facilitator client is `@x402/core`'s `HTTPFacilitatorClient`, wrapped so
27
27
  * a thrown `VerifyError` or `SettleError` comes back as a `Result` carrying the
28
28
  * facilitator's reason. Requirement construction and the request handling are
29
- * this package's own, because the reference server middleware gates every
29
+ * this package's own, because the official server middleware gates every
30
30
  * request on payment, which is the model Tab exists to replace.
31
31
  *
32
32
  * Specification: x402-specification-v2.md sections 5, 6.1 and 7, transports-v2/http.md.
@@ -43,18 +43,18 @@ export declare const DEFAULT_MAX_TIMEOUT_SECONDS = 300;
43
43
  /**
44
44
  * What verifies and settles payments.
45
45
  *
46
- * The reference interface, re-exported so a fake in a test and the HTTP client
47
- * in production are the same type. The methods throw, as the reference does;
46
+ * `@x402/core`'s interface, re-exported so a fake in a test and the HTTP client
47
+ * in production are the same type. The methods throw, as `@x402/core`'s do;
48
48
  * {@link verifyPayment} and {@link settlePayment} are the zero-throw doors.
49
49
  */
50
50
  export type X402FacilitatorClient = FacilitatorClient;
51
51
  export interface X402FacilitatorOptions {
52
52
  /** Defaults to {@link MONAD_FACILITATOR_URL}. */
53
53
  readonly url?: string;
54
- /** Per-request timeout. Defaults to the reference client's 90 seconds. */
54
+ /** Per-request timeout. Defaults to `@x402/core`'s 90 seconds. */
55
55
  readonly timeoutMs?: number;
56
56
  }
57
- /** The reference HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */
57
+ /** `@x402/core`'s HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */
58
58
  export declare function createX402Facilitator(options?: X402FacilitatorOptions): X402FacilitatorClient;
59
59
  export interface ExactRequirementOptions {
60
60
  readonly chainId: bigint;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/x402/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAyB,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAgC,KAAK,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AAGvG,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAC1D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAOL,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACxB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,WAAW,CAAC;AAEnB,oFAAoF;AACpF,eAAO,MAAM,qBAAqB,0CAA0C,CAAC;AAE7E,2EAA2E;AAC3E,eAAO,MAAM,2BAA2B,MAAM,CAAC;AAE/C;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,GAAG,iBAAiB,CAAC;AAEtD,MAAM,WAAW,sBAAsB;IACrC,iDAAiD;IACjD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,0EAA0E;IAC1E,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,4FAA4F;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uHAAuH;GACrH;IAAE,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAA;CAAE,CAAC;AAElG;;;;;GAKG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,cAAc,CAAC,CA8DlG;AAED,4EAA4E;AAC5E,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,eAAe,EAAE,KAAK,EAAE,QAAQ,EAAE,YAAY,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,GAAG,QAAQ,CAUjJ"}
@@ -26,7 +26,7 @@
26
26
  * The facilitator client is `@x402/core`'s `HTTPFacilitatorClient`, wrapped so
27
27
  * a thrown `VerifyError` or `SettleError` comes back as a `Result` carrying the
28
28
  * facilitator's reason. Requirement construction and the request handling are
29
- * this package's own, because the reference server middleware gates every
29
+ * this package's own, because the official server middleware gates every
30
30
  * request on payment, which is the model Tab exists to replace.
31
31
  *
32
32
  * Specification: x402-specification-v2.md sections 5, 6.1 and 7, transports-v2/http.md.
@@ -40,7 +40,7 @@ import { X402_HEADER, X402_SCHEME_EXACT, X402_VERSION, encodePaymentRequired, en
40
40
  export const MONAD_FACILITATOR_URL = "https://x402-facilitator.molandak.org";
41
41
  /** How long an authorization stays valid when the Service does not say. */
42
42
  export const DEFAULT_MAX_TIMEOUT_SECONDS = 300;
43
- /** The reference HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */
43
+ /** `@x402/core`'s HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */
44
44
  export function createX402Facilitator(options = {}) {
45
45
  return new HTTPFacilitatorClient({
46
46
  url: options.url ?? MONAD_FACILITATOR_URL,
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/x402/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;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CAAC;YAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvF,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,CAAC,KAAK,CAAC,uEAAuE,CAAC,CAAC;QACtF,MAAM,MAAM,GAAG,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAC7C,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;YAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC7E,OAAO,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,UAAU,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IACpH,CAAC;AACH,CAAC;AAED,SAAS,OAAO,CAAC,QAAkB,EAAE,MAAc;IACjD,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC3B,IAAI,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC,QAAQ;QAAE,OAAO;IAC/C,IAAI,CAAC;QACH,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,gDAAgD,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1H,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,gDAAgD,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IACjF,CAAC;AACH,CAAC","sourcesContent":["/**\n * The x402 server side: build what a `402` must carry, and take a signed\n * payment through a facilitator.\n *\n * ## The flow, and why the order is fixed\n *\n * x402's default `authorization` flow is verify, then resource, then settle:\n * the facilitator confirms the signature and the balance before the work is\n * done, and moves the funds only after the work succeeded. {@link handlePrepaidRequest}\n * runs exactly that. It never settles a payment for a response that was not a\n * delivery, for the same reason the post-paid plugin never meters one: an\n * Agent is not charged for a call that failed.\n *\n * ## What a Tab Service does with this\n *\n * A Tab Service delivers on credit and refuses on `LimitExceeded` alone. With\n * this module, that refusal can also carry a `PAYMENT-REQUIRED` naming the same\n * charge as an x402 `exact` requirement, so an Agent that has no headroom and\n * would rather not settle first can pay for the one call. When it does, the\n * call is prepaid in full, the facilitator moves the Asset to the Service's\n * Collection address, and nothing lands on the Open Tab, because nothing is\n * owed.\n *\n * ## Official and hand-rolled\n *\n * The facilitator client is `@x402/core`'s `HTTPFacilitatorClient`, wrapped so\n * a thrown `VerifyError` or `SettleError` comes back as a `Result` carrying the\n * facilitator's reason. Requirement construction and the request handling are\n * this package's own, because the reference server middleware gates every\n * request on payment, which is the model Tab exists to replace.\n *\n * Specification: x402-specification-v2.md sections 5, 6.1 and 7, transports-v2/http.md.\n */\n\nimport { HTTPFacilitatorClient, type FacilitatorClient } from \"@x402/core/server\";\nimport { causeOf, isAddress, ok, wrap, type Address, type Result, type TabError } from \"../_shared/index.js\";\n\nimport { fail, tabError, validationError } from \"../errors.js\";\nimport { defaultLogger, type Logger } from \"../logger.js\";\nimport type { AssetRef } from \"../payments/strategy.js\";\nimport {\n X402_HEADER,\n X402_SCHEME_EXACT,\n X402_VERSION,\n encodePaymentRequired,\n encodePaymentResponse,\n networkOf,\n type PaymentPayload,\n type PaymentRequired,\n type PaymentRequirements,\n type ResourceInfo,\n type SettleResponse,\n type SupportedResponse,\n type VerifyResponse,\n} from \"./wire.js\";\n\n/** Monad's facilitator, which settles `exact` and `upto` on Mainnet and Testnet. */\nexport const MONAD_FACILITATOR_URL = \"https://x402-facilitator.molandak.org\";\n\n/** How long an authorization stays valid when the Service does not say. */\nexport const DEFAULT_MAX_TIMEOUT_SECONDS = 300;\n\n/**\n * What verifies and settles payments.\n *\n * The reference interface, re-exported so a fake in a test and the HTTP client\n * in production are the same type. The methods throw, as the reference does;\n * {@link verifyPayment} and {@link settlePayment} are the zero-throw doors.\n */\nexport type X402FacilitatorClient = FacilitatorClient;\n\nexport interface X402FacilitatorOptions {\n /** Defaults to {@link MONAD_FACILITATOR_URL}. */\n readonly url?: string;\n /** Per-request timeout. Defaults to the reference client's 90 seconds. */\n readonly timeoutMs?: number;\n}\n\n/** The reference HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */\nexport function createX402Facilitator(options: X402FacilitatorOptions = {}): X402FacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.url ?? MONAD_FACILITATOR_URL,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n}\n\n/** The EIP-712 domain of the two USDC deployments Monad's facilitator settles. */\nconst KNOWN_DOMAINS: Readonly<Record<string, { readonly name: string; readonly version: string }>> = {\n USDC: { name: \"USDC\", version: \"2\" },\n // The Testnet mock's constructor names it `USDC` v2 to match Circle's; the\n // rail calls it `mUSDC` so the two are never confused on a page.\n MUSDC: { name: \"USDC\", version: \"2\" },\n};\n\nexport interface ExactRequirementOptions {\n readonly chainId: bigint;\n /** The token. `symbol` picks the EIP-712 domain when `extra` is not given. */\n readonly asset: Pick<AssetRef, \"address\" | \"symbol\">;\n /** Atomic units of the token. */\n readonly amount: bigint;\n /** Where the facilitator sends the funds: the Service's Collection address for the Asset. */\n readonly payTo: Address;\n readonly maxTimeoutSeconds?: number;\n /**\n * The requirement's `extra`. Must carry the token's EIP-712 domain `name` and\n * `version`, which EIP-3009 signing needs. Defaults to USDC's when the Asset's\n * symbol is `USDC`, and is required otherwise.\n */\n readonly extra?: Readonly<Record<string, unknown>>;\n}\n\n/** One `exact` requirement, EIP-3009, on an EVM chain. */\nexport function exactRequirementFor(options: ExactRequirementOptions): Result<PaymentRequirements> {\n if (typeof options.chainId !== \"bigint\" || options.chainId <= 0n) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"chainId must be a positive bigint\");\n }\n if (!isAddress(options.asset.address)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `asset \\`${String(options.asset.address)}\\` is not a 20-byte address`);\n }\n if (!isAddress(options.payTo)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `payTo \\`${String(options.payTo)}\\` is not a 20-byte address`);\n }\n if (typeof options.amount !== \"bigint\" || options.amount <= 0n) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"amount must be a positive bigint of atomic units, never a number\");\n }\n const timeout = options.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;\n if (!Number.isInteger(timeout) || timeout <= 0) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"maxTimeoutSeconds must be a positive integer\");\n }\n const extra = options.extra ?? KNOWN_DOMAINS[options.asset.symbol.toUpperCase()];\n if (extra === undefined || typeof extra[\"name\"] !== \"string\" || typeof extra[\"version\"] !== \"string\") {\n return validationError(\n \"X402_DOMAIN_MISSING\",\n `no EIP-712 domain is known for ${options.asset.symbol}; pass extra: { name, version } from the token contract`,\n { details: { asset: options.asset.address, symbol: options.asset.symbol } },\n );\n }\n return ok({\n scheme: X402_SCHEME_EXACT,\n network: networkOf(options.chainId),\n amount: options.amount.toString(10),\n asset: options.asset.address,\n payTo: options.payTo,\n maxTimeoutSeconds: timeout,\n extra: { ...extra },\n });\n}\n\nexport interface PaymentRequiredOptions {\n readonly resource: ResourceInfo;\n readonly accepts: readonly PaymentRequirements[];\n /** Why payment is being asked for, for a person reading the header. */\n readonly error?: string;\n}\n\n/** The object a `402` carries in `PAYMENT-REQUIRED`. */\nexport const paymentRequiredFor = (options: PaymentRequiredOptions): PaymentRequired => ({\n x402Version: X402_VERSION,\n ...(options.error === undefined ? {} : { error: options.error }),\n resource: options.resource,\n accepts: [...options.accepts],\n});\n\n/** The `PAYMENT-REQUIRED` header, ready to merge onto a response. */\nexport function paymentRequiredHeaders(required: PaymentRequired): Result<Record<string, string>> {\n const encoded = encodePaymentRequired(required);\n if (!encoded.ok) return encoded;\n return ok({ [X402_HEADER.paymentRequired]: encoded.value });\n}\n\n/** The `PAYMENT-RESPONSE` header, ready to merge onto a response. */\nexport function paymentResponseHeaders(settlement: SettleResponse): Result<Record<string, string>> {\n const encoded = encodePaymentResponse(settlement);\n if (!encoded.ok) return encoded;\n return ok({ [X402_HEADER.paymentResponse]: encoded.value });\n}\n\n/** What a thrown facilitator error carries, read without depending on its class. */\ninterface ThrownFacilitatorError {\n readonly invalidReason?: unknown;\n readonly errorReason?: unknown;\n readonly invalidMessage?: unknown;\n readonly errorMessage?: unknown;\n readonly payer?: unknown;\n readonly transaction?: unknown;\n readonly statusCode?: unknown;\n}\n\nconst facilitatorFailure = (what: \"verify\" | \"settle\") => (error: unknown): TabError => {\n const thrown = (typeof error === \"object\" && error !== null ? error : {}) as ThrownFacilitatorError;\n const reason = [thrown.invalidReason, thrown.errorReason].find((value) => typeof value === \"string\") as string | undefined;\n const detail = [thrown.invalidMessage, thrown.errorMessage].find((value) => typeof value === \"string\") as string | undefined;\n return tabError(\n reason === undefined ? \"UPSTREAM\" : \"LIMIT\",\n reason === undefined ? `X402_FACILITATOR_${what.toUpperCase()}_FAILED` : `X402_${what.toUpperCase()}_REJECTED`,\n reason === undefined\n ? `the facilitator could not ${what} the payment`\n : `the facilitator refused to ${what} the payment: ${reason}${detail === undefined ? \"\" : ` (${detail})`}`,\n {\n retryable: reason === undefined,\n details: {\n ...(reason === undefined ? {} : { reason }),\n ...(typeof thrown.payer === \"string\" ? { payer: thrown.payer } : {}),\n ...(typeof thrown.transaction === \"string\" && thrown.transaction.length > 0 ? { transaction: thrown.transaction } : {}),\n ...(typeof thrown.statusCode === \"number\" ? { statusCode: thrown.statusCode } : {}),\n },\n cause: causeOf(error),\n },\n );\n};\n\n/** `POST /verify`, as a `Result`. An invalid payment is a `LIMIT` error naming the facilitator's reason. */\nexport async function verifyPayment(\n facilitator: X402FacilitatorClient,\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n): Promise<Result<VerifyResponse>> {\n const verified = await wrap(async () => facilitator.verify(payload, requirements), facilitatorFailure(\"verify\"));\n if (!verified.ok) return verified;\n if (verified.value.isValid !== true) {\n const reason = verified.value.invalidReason ?? \"invalid_payload\";\n return fail(\"LIMIT\", \"X402_VERIFY_REJECTED\", `the facilitator refused to verify the payment: ${reason}`, {\n retryable: false,\n details: { reason, ...(verified.value.payer === undefined ? {} : { payer: verified.value.payer }) },\n });\n }\n return verified;\n}\n\n/** `POST /settle`, as a `Result`. A failed settlement carries the facilitator's reason and any broadcast hash. */\nexport async function settlePayment(\n facilitator: X402FacilitatorClient,\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n): Promise<Result<SettleResponse>> {\n const settled = await wrap(async () => facilitator.settle(payload, requirements), facilitatorFailure(\"settle\"));\n if (!settled.ok) return settled;\n if (settled.value.success !== true) {\n const reason = settled.value.errorReason ?? \"unexpected_settle_error\";\n return fail(\n reason === \"settlement_pending\" ? \"UNAVAILABLE\" : \"LIMIT\",\n \"X402_SETTLE_REJECTED\",\n `the facilitator did not settle the payment: ${reason}`,\n {\n retryable: reason === \"settlement_pending\",\n details: {\n reason,\n transaction: settled.value.transaction,\n network: settled.value.network,\n ...(settled.value.payer === undefined ? {} : { payer: settled.value.payer }),\n },\n },\n );\n }\n return settled;\n}\n\n/** `GET /supported`, as a `Result`. */\nexport const facilitatorSupports = (facilitator: X402FacilitatorClient): Promise<Result<SupportedResponse>> =>\n wrap(async () => facilitator.getSupported(), (error) =>\n tabError(\"UPSTREAM\", \"X402_FACILITATOR_UNREACHABLE\", \"the facilitator did not answer /supported\", {\n retryable: true,\n cause: causeOf(error),\n }),\n );\n\n/**\n * Checks that what the client says it accepted is what this server requires.\n *\n * The facilitator verifies the signature against the server's requirements, so\n * a mismatch would be caught there; catching it here saves the round trip and\n * names the field. `extra` and `maxTimeoutSeconds` are not compared: they are\n * the server's inputs to signing and the facilitator reads them from the\n * server's copy, never the client's.\n */\nexport function matchAccepted(accepted: PaymentRequirements, requirements: PaymentRequirements): Result<void> {\n const mismatches: string[] = [];\n if (accepted.scheme !== requirements.scheme) mismatches.push(`scheme ${accepted.scheme} is not ${requirements.scheme}`);\n if (accepted.network !== requirements.network) mismatches.push(`network ${accepted.network} is not ${requirements.network}`);\n if (accepted.asset.toLowerCase() !== requirements.asset.toLowerCase()) mismatches.push(`asset ${accepted.asset} is not ${requirements.asset}`);\n if (accepted.payTo.toLowerCase() !== requirements.payTo.toLowerCase()) mismatches.push(`payTo ${accepted.payTo} is not ${requirements.payTo}`);\n if (BigInt(accepted.amount) !== BigInt(requirements.amount)) mismatches.push(`amount ${accepted.amount} is not ${requirements.amount}`);\n if (mismatches.length === 0) return ok(undefined);\n return fail(\"LIMIT\", \"X402_ACCEPTED_MISMATCH\", `the signed payment does not match this call's requirement: ${mismatches.join(\", \")}`, {\n retryable: false,\n details: { mismatches: mismatches.join(\"; \") },\n });\n}\n\n/** The response, reduced to what the billability decision needs. */\nexport interface X402DeliveredResponse {\n readonly status: number;\n}\n\nexport interface PrepaidRequestOptions {\n readonly facilitator: X402FacilitatorClient;\n /** The decoded `PAYMENT-SIGNATURE`. */\n readonly payload: PaymentPayload;\n /** What this call costs, built by the server and never taken from the client. */\n readonly requirements: PaymentRequirements;\n readonly resource: ResourceInfo;\n /** The work. Runs only after the payment verified. */\n readonly deliver: () => Promise<Response> | Response;\n /** Whether a response is a delivery worth settling for. Defaults to `status < 400`. */\n readonly billable?: (response: X402DeliveredResponse) => boolean;\n readonly logger?: Logger;\n}\n\nexport type PrepaidOutcome =\n /** Verified, delivered, settled. The response carries `PAYMENT-RESPONSE`. */\n | { readonly kind: \"paid\"; readonly response: Response; readonly settlement: SettleResponse; readonly payer: string | undefined }\n /** The payment did not verify. The response is a `402` carrying `PAYMENT-REQUIRED` with the reason. */\n | { readonly kind: \"rejected\"; readonly response: Response; readonly error: TabError }\n /** The work was not a delivery, so nothing was settled and the handler's own response goes out. */\n | { readonly kind: \"not-delivered\"; readonly response: Response }\n /** The handler threw. Nothing was settled. */\n | { readonly kind: \"handler-failed\"; readonly thrown: unknown; readonly error: TabError }\n /** Delivered, but the facilitator would not settle. The response is a `402` carrying the failed `PAYMENT-RESPONSE`. */\n | { readonly kind: \"settlement-failed\"; readonly response: Response; readonly error: TabError };\n\n/**\n * Takes one prepaid request through verify, deliver, settle.\n *\n * Never throws and never rejects. A thrown handler is an outcome, not an\n * exception, so a host adapter can re-raise it the way its framework expects.\n */\nexport async function handlePrepaidRequest(options: PrepaidRequestOptions): Promise<PrepaidOutcome> {\n const logger = options.logger ?? defaultLogger;\n const billable = options.billable ?? ((response: X402DeliveredResponse) => response.status < 400);\n const required = paymentRequiredFor({ resource: options.resource, accepts: [options.requirements] });\n\n const rejected = (error: TabError): PrepaidOutcome => ({\n kind: \"rejected\",\n response: paymentRequiredResponse({ ...required, error: error.message }, error),\n error,\n });\n\n const matched = matchAccepted(options.payload.accepted, options.requirements);\n if (!matched.ok) return rejected(matched.error);\n\n const verified = await verifyPayment(options.facilitator, options.payload, options.requirements);\n if (!verified.ok) return rejected(verified.error);\n\n let response: Response;\n try {\n response = await options.deliver();\n } catch (thrown) {\n logger.debug(\"x402 prepaid call settled nothing because the handler failed\");\n return {\n kind: \"handler-failed\",\n thrown,\n error: tabError(\"INTERNAL\", \"HANDLER_FAILED\", \"the handler failed, so the verified payment was not settled\", {\n details: { settled: false },\n cause: causeOf(thrown),\n }),\n };\n }\n\n let deliverable: boolean;\n try {\n deliverable = billable(response) === true;\n } catch (thrown) {\n logger.error(\"x402 billable predicate threw and was read as not billable\", causeOf(thrown));\n deliverable = false;\n }\n if (!deliverable) return { kind: \"not-delivered\", response };\n\n const settled = await settlePayment(options.facilitator, options.payload, options.requirements);\n if (!settled.ok) {\n discard(response, logger);\n const failure: SettleResponse = {\n success: false,\n errorReason: String(settled.error.details?.[\"reason\"] ?? settled.error.code),\n transaction: String(settled.error.details?.[\"transaction\"] ?? \"\"),\n network: options.requirements.network,\n ...(typeof settled.error.details?.[\"payer\"] === \"string\" ? { payer: settled.error.details[\"payer\"] } : {}),\n };\n return { kind: \"settlement-failed\", response: settlementFailedResponse(failure, settled.error), error: settled.error };\n }\n\n const headers = paymentResponseHeaders(settled.value);\n if (!headers.ok) {\n // The funds moved and the work is delivered; a header that will not encode\n // costs the caller the receipt and nothing else.\n logger.error(\"x402 settlement succeeded but PAYMENT-RESPONSE would not encode\", { code: headers.error.code });\n return { kind: \"paid\", response, settlement: settled.value, payer: settled.value.payer };\n }\n return { kind: \"paid\", response: withHeaders(response, headers.value, logger), settlement: settled.value, payer: settled.value.payer };\n}\n\n/** A `402` carrying `PAYMENT-REQUIRED` and a JSON body naming the error. */\nexport function paymentRequiredResponse(required: PaymentRequired, error: TabError, extraHeaders: Readonly<Record<string, string>> = {}): Response {\n const encoded = paymentRequiredHeaders(required);\n return new Response(JSON.stringify({ ok: false, error }), {\n status: 402,\n headers: {\n ...extraHeaders,\n ...(encoded.ok ? encoded.value : {}),\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n });\n}\n\n/** A `402` carrying a failed `PAYMENT-RESPONSE`, as the HTTP transport specification shows. */\nfunction settlementFailedResponse(failure: SettleResponse, error: TabError): Response {\n const encoded = paymentResponseHeaders(failure);\n return new Response(JSON.stringify({ ok: false, error }), {\n status: 402,\n headers: { ...(encoded.ok ? encoded.value : {}), \"Content-Type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/** Puts headers on a response, copying it when its headers are immutable. */\nfunction withHeaders(response: Response, headers: Readonly<Record<string, string>>, logger: Logger): Response {\n try {\n for (const [name, value] of Object.entries(headers)) response.headers.set(name, value);\n return response;\n } catch {\n logger.debug(\"response headers were immutable, so PAYMENT-RESPONSE went onto a copy\");\n const merged = new Headers(response.headers);\n for (const [name, value] of Object.entries(headers)) merged.set(name, value);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers: merged });\n }\n}\n\nfunction discard(response: Response, logger: Logger): void {\n const body = response.body;\n if (body === null || response.bodyUsed) return;\n try {\n body.cancel().catch((error: unknown) => logger.debug(\"discarded response body could not be cancelled\", causeOf(error)));\n } catch (error) {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n }\n}\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/x402/server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,qBAAqB,EAA0B,MAAM,mBAAmB,CAAC;AAClF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,EAA4C,MAAM,eAAe,CAAC;AAEvG,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AAE1D,OAAO,EACL,WAAW,EACX,iBAAiB,EACjB,YAAY,EACZ,qBAAqB,EACrB,qBAAqB,EACrB,SAAS,GAQV,MAAM,WAAW,CAAC;AAEnB,oFAAoF;AACpF,MAAM,CAAC,MAAM,qBAAqB,GAAG,uCAAuC,CAAC;AAE7E,2EAA2E;AAC3E,MAAM,CAAC,MAAM,2BAA2B,GAAG,GAAG,CAAC;AAkB/C,6FAA6F;AAC7F,MAAM,UAAU,qBAAqB,CAAC,UAAkC,EAAE;IACxE,OAAO,IAAI,qBAAqB,CAAC;QAC/B,GAAG,EAAE,OAAO,CAAC,GAAG,IAAI,qBAAqB;QACzC,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC;KAC7E,CAAC,CAAC;AACL,CAAC;AAED,kFAAkF;AAClF,MAAM,aAAa,GAAkF;IACnG,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE;IACpC,2EAA2E;IAC3E,iEAAiE;IACjE,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,E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K,CAAC,CAAC,CAAC;IACjF,CAAC;AACH,CAAC","sourcesContent":["/**\n * The x402 server side: build what a `402` must carry, and take a signed\n * payment through a facilitator.\n *\n * ## The flow, and why the order is fixed\n *\n * x402's default `authorization` flow is verify, then resource, then settle:\n * the facilitator confirms the signature and the balance before the work is\n * done, and moves the funds only after the work succeeded. {@link handlePrepaidRequest}\n * runs exactly that. It never settles a payment for a response that was not a\n * delivery, for the same reason the post-paid plugin never meters one: an\n * Agent is not charged for a call that failed.\n *\n * ## What a Tab Service does with this\n *\n * A Tab Service delivers on credit and refuses on `LimitExceeded` alone. With\n * this module, that refusal can also carry a `PAYMENT-REQUIRED` naming the same\n * charge as an x402 `exact` requirement, so an Agent that has no headroom and\n * would rather not settle first can pay for the one call. When it does, the\n * call is prepaid in full, the facilitator moves the Asset to the Service's\n * Collection address, and nothing lands on the Open Tab, because nothing is\n * owed.\n *\n * ## Official and hand-rolled\n *\n * The facilitator client is `@x402/core`'s `HTTPFacilitatorClient`, wrapped so\n * a thrown `VerifyError` or `SettleError` comes back as a `Result` carrying the\n * facilitator's reason. Requirement construction and the request handling are\n * this package's own, because the official server middleware gates every\n * request on payment, which is the model Tab exists to replace.\n *\n * Specification: x402-specification-v2.md sections 5, 6.1 and 7, transports-v2/http.md.\n */\n\nimport { HTTPFacilitatorClient, type FacilitatorClient } from \"@x402/core/server\";\nimport { causeOf, isAddress, ok, wrap, type Address, type Result, type TabError } from \"../_shared/index.js\";\n\nimport { fail, tabError, validationError } from \"../errors.js\";\nimport { defaultLogger, type Logger } from \"../logger.js\";\nimport type { AssetRef } from \"../payments/strategy.js\";\nimport {\n X402_HEADER,\n X402_SCHEME_EXACT,\n X402_VERSION,\n encodePaymentRequired,\n encodePaymentResponse,\n networkOf,\n type PaymentPayload,\n type PaymentRequired,\n type PaymentRequirements,\n type ResourceInfo,\n type SettleResponse,\n type SupportedResponse,\n type VerifyResponse,\n} from \"./wire.js\";\n\n/** Monad's facilitator, which settles `exact` and `upto` on Mainnet and Testnet. */\nexport const MONAD_FACILITATOR_URL = \"https://x402-facilitator.molandak.org\";\n\n/** How long an authorization stays valid when the Service does not say. */\nexport const DEFAULT_MAX_TIMEOUT_SECONDS = 300;\n\n/**\n * What verifies and settles payments.\n *\n * `@x402/core`'s interface, re-exported so a fake in a test and the HTTP client\n * in production are the same type. The methods throw, as `@x402/core`'s do;\n * {@link verifyPayment} and {@link settlePayment} are the zero-throw doors.\n */\nexport type X402FacilitatorClient = FacilitatorClient;\n\nexport interface X402FacilitatorOptions {\n /** Defaults to {@link MONAD_FACILITATOR_URL}. */\n readonly url?: string;\n /** Per-request timeout. Defaults to `@x402/core`'s 90 seconds. */\n readonly timeoutMs?: number;\n}\n\n/** `@x402/core`'s HTTP client over a facilitator's `/verify`, `/settle` and `/supported`. */\nexport function createX402Facilitator(options: X402FacilitatorOptions = {}): X402FacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.url ?? MONAD_FACILITATOR_URL,\n ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),\n });\n}\n\n/** The EIP-712 domain of the two USDC deployments Monad's facilitator settles. */\nconst KNOWN_DOMAINS: Readonly<Record<string, { readonly name: string; readonly version: string }>> = {\n USDC: { name: \"USDC\", version: \"2\" },\n // The Testnet mock's constructor names it `USDC` v2 to match Circle's; the\n // rail calls it `mUSDC` so the two are never confused on a page.\n MUSDC: { name: \"USDC\", version: \"2\" },\n};\n\nexport interface ExactRequirementOptions {\n readonly chainId: bigint;\n /** The token. `symbol` picks the EIP-712 domain when `extra` is not given. */\n readonly asset: Pick<AssetRef, \"address\" | \"symbol\">;\n /** Atomic units of the token. */\n readonly amount: bigint;\n /** Where the facilitator sends the funds: the Service's Collection address for the Asset. */\n readonly payTo: Address;\n readonly maxTimeoutSeconds?: number;\n /**\n * The requirement's `extra`. Must carry the token's EIP-712 domain `name` and\n * `version`, which EIP-3009 signing needs. Defaults to USDC's when the Asset's\n * symbol is `USDC`, and is required otherwise.\n */\n readonly extra?: Readonly<Record<string, unknown>>;\n}\n\n/** One `exact` requirement, EIP-3009, on an EVM chain. */\nexport function exactRequirementFor(options: ExactRequirementOptions): Result<PaymentRequirements> {\n if (typeof options.chainId !== \"bigint\" || options.chainId <= 0n) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"chainId must be a positive bigint\");\n }\n if (!isAddress(options.asset.address)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `asset \\`${String(options.asset.address)}\\` is not a 20-byte address`);\n }\n if (!isAddress(options.payTo)) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", `payTo \\`${String(options.payTo)}\\` is not a 20-byte address`);\n }\n if (typeof options.amount !== \"bigint\" || options.amount <= 0n) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"amount must be a positive bigint of atomic units, never a number\");\n }\n const timeout = options.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;\n if (!Number.isInteger(timeout) || timeout <= 0) {\n return validationError(\"X402_REQUIREMENTS_INVALID\", \"maxTimeoutSeconds must be a positive integer\");\n }\n const extra = options.extra ?? KNOWN_DOMAINS[options.asset.symbol.toUpperCase()];\n if (extra === undefined || typeof extra[\"name\"] !== \"string\" || typeof extra[\"version\"] !== \"string\") {\n return validationError(\n \"X402_DOMAIN_MISSING\",\n `no EIP-712 domain is known for ${options.asset.symbol}; pass extra: { name, version } from the token contract`,\n { details: { asset: options.asset.address, symbol: options.asset.symbol } },\n );\n }\n return ok({\n scheme: X402_SCHEME_EXACT,\n network: networkOf(options.chainId),\n amount: options.amount.toString(10),\n asset: options.asset.address,\n payTo: options.payTo,\n maxTimeoutSeconds: timeout,\n extra: { ...extra },\n });\n}\n\nexport interface PaymentRequiredOptions {\n readonly resource: ResourceInfo;\n readonly accepts: readonly PaymentRequirements[];\n /** Why payment is being asked for, for a person reading the header. */\n readonly error?: string;\n}\n\n/** The object a `402` carries in `PAYMENT-REQUIRED`. */\nexport const paymentRequiredFor = (options: PaymentRequiredOptions): PaymentRequired => ({\n x402Version: X402_VERSION,\n ...(options.error === undefined ? {} : { error: options.error }),\n resource: options.resource,\n accepts: [...options.accepts],\n});\n\n/** The `PAYMENT-REQUIRED` header, ready to merge onto a response. */\nexport function paymentRequiredHeaders(required: PaymentRequired): Result<Record<string, string>> {\n const encoded = encodePaymentRequired(required);\n if (!encoded.ok) return encoded;\n return ok({ [X402_HEADER.paymentRequired]: encoded.value });\n}\n\n/** The `PAYMENT-RESPONSE` header, ready to merge onto a response. */\nexport function paymentResponseHeaders(settlement: SettleResponse): Result<Record<string, string>> {\n const encoded = encodePaymentResponse(settlement);\n if (!encoded.ok) return encoded;\n return ok({ [X402_HEADER.paymentResponse]: encoded.value });\n}\n\n/** What a thrown facilitator error carries, read without depending on its class. */\ninterface ThrownFacilitatorError {\n readonly invalidReason?: unknown;\n readonly errorReason?: unknown;\n readonly invalidMessage?: unknown;\n readonly errorMessage?: unknown;\n readonly payer?: unknown;\n readonly transaction?: unknown;\n readonly statusCode?: unknown;\n}\n\nconst facilitatorFailure = (what: \"verify\" | \"settle\") => (error: unknown): TabError => {\n const thrown = (typeof error === \"object\" && error !== null ? error : {}) as ThrownFacilitatorError;\n const reason = [thrown.invalidReason, thrown.errorReason].find((value) => typeof value === \"string\") as string | undefined;\n const detail = [thrown.invalidMessage, thrown.errorMessage].find((value) => typeof value === \"string\") as string | undefined;\n return tabError(\n reason === undefined ? \"UPSTREAM\" : \"LIMIT\",\n reason === undefined ? `X402_FACILITATOR_${what.toUpperCase()}_FAILED` : `X402_${what.toUpperCase()}_REJECTED`,\n reason === undefined\n ? `the facilitator could not ${what} the payment`\n : `the facilitator refused to ${what} the payment: ${reason}${detail === undefined ? \"\" : ` (${detail})`}`,\n {\n retryable: reason === undefined,\n details: {\n ...(reason === undefined ? {} : { reason }),\n ...(typeof thrown.payer === \"string\" ? { payer: thrown.payer } : {}),\n ...(typeof thrown.transaction === \"string\" && thrown.transaction.length > 0 ? { transaction: thrown.transaction } : {}),\n ...(typeof thrown.statusCode === \"number\" ? { statusCode: thrown.statusCode } : {}),\n },\n cause: causeOf(error),\n },\n );\n};\n\n/** `POST /verify`, as a `Result`. An invalid payment is a `LIMIT` error naming the facilitator's reason. */\nexport async function verifyPayment(\n facilitator: X402FacilitatorClient,\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n): Promise<Result<VerifyResponse>> {\n const verified = await wrap(async () => facilitator.verify(payload, requirements), facilitatorFailure(\"verify\"));\n if (!verified.ok) return verified;\n if (verified.value.isValid !== true) {\n const reason = verified.value.invalidReason ?? \"invalid_payload\";\n return fail(\"LIMIT\", \"X402_VERIFY_REJECTED\", `the facilitator refused to verify the payment: ${reason}`, {\n retryable: false,\n details: { reason, ...(verified.value.payer === undefined ? {} : { payer: verified.value.payer }) },\n });\n }\n return verified;\n}\n\n/** `POST /settle`, as a `Result`. A failed settlement carries the facilitator's reason and any broadcast hash. */\nexport async function settlePayment(\n facilitator: X402FacilitatorClient,\n payload: PaymentPayload,\n requirements: PaymentRequirements,\n): Promise<Result<SettleResponse>> {\n const settled = await wrap(async () => facilitator.settle(payload, requirements), facilitatorFailure(\"settle\"));\n if (!settled.ok) return settled;\n if (settled.value.success !== true) {\n const reason = settled.value.errorReason ?? \"unexpected_settle_error\";\n return fail(\n reason === \"settlement_pending\" ? \"UNAVAILABLE\" : \"LIMIT\",\n \"X402_SETTLE_REJECTED\",\n `the facilitator did not settle the payment: ${reason}`,\n {\n retryable: reason === \"settlement_pending\",\n details: {\n reason,\n transaction: settled.value.transaction,\n network: settled.value.network,\n ...(settled.value.payer === undefined ? {} : { payer: settled.value.payer }),\n },\n },\n );\n }\n return settled;\n}\n\n/** `GET /supported`, as a `Result`. */\nexport const facilitatorSupports = (facilitator: X402FacilitatorClient): Promise<Result<SupportedResponse>> =>\n wrap(async () => facilitator.getSupported(), (error) =>\n tabError(\"UPSTREAM\", \"X402_FACILITATOR_UNREACHABLE\", \"the facilitator did not answer /supported\", {\n retryable: true,\n cause: causeOf(error),\n }),\n );\n\n/**\n * Checks that what the client says it accepted is what this server requires.\n *\n * The facilitator verifies the signature against the server's requirements, so\n * a mismatch would be caught there; catching it here saves the round trip and\n * names the field. `extra` and `maxTimeoutSeconds` are not compared: they are\n * the server's inputs to signing and the facilitator reads them from the\n * server's copy, never the client's.\n */\nexport function matchAccepted(accepted: PaymentRequirements, requirements: PaymentRequirements): Result<void> {\n const mismatches: string[] = [];\n if (accepted.scheme !== requirements.scheme) mismatches.push(`scheme ${accepted.scheme} is not ${requirements.scheme}`);\n if (accepted.network !== requirements.network) mismatches.push(`network ${accepted.network} is not ${requirements.network}`);\n if (accepted.asset.toLowerCase() !== requirements.asset.toLowerCase()) mismatches.push(`asset ${accepted.asset} is not ${requirements.asset}`);\n if (accepted.payTo.toLowerCase() !== requirements.payTo.toLowerCase()) mismatches.push(`payTo ${accepted.payTo} is not ${requirements.payTo}`);\n if (BigInt(accepted.amount) !== BigInt(requirements.amount)) mismatches.push(`amount ${accepted.amount} is not ${requirements.amount}`);\n if (mismatches.length === 0) return ok(undefined);\n return fail(\"LIMIT\", \"X402_ACCEPTED_MISMATCH\", `the signed payment does not match this call's requirement: ${mismatches.join(\", \")}`, {\n retryable: false,\n details: { mismatches: mismatches.join(\"; \") },\n });\n}\n\n/** The response, reduced to what the billability decision needs. */\nexport interface X402DeliveredResponse {\n readonly status: number;\n}\n\nexport interface PrepaidRequestOptions {\n readonly facilitator: X402FacilitatorClient;\n /** The decoded `PAYMENT-SIGNATURE`. */\n readonly payload: PaymentPayload;\n /** What this call costs, built by the server and never taken from the client. */\n readonly requirements: PaymentRequirements;\n readonly resource: ResourceInfo;\n /** The work. Runs only after the payment verified. */\n readonly deliver: () => Promise<Response> | Response;\n /** Whether a response is a delivery worth settling for. Defaults to `status < 400`. */\n readonly billable?: (response: X402DeliveredResponse) => boolean;\n readonly logger?: Logger;\n}\n\nexport type PrepaidOutcome =\n /** Verified, delivered, settled. The response carries `PAYMENT-RESPONSE`. */\n | { readonly kind: \"paid\"; readonly response: Response; readonly settlement: SettleResponse; readonly payer: string | undefined }\n /** The payment did not verify. The response is a `402` carrying `PAYMENT-REQUIRED` with the reason. */\n | { readonly kind: \"rejected\"; readonly response: Response; readonly error: TabError }\n /** The work was not a delivery, so nothing was settled and the handler's own response goes out. */\n | { readonly kind: \"not-delivered\"; readonly response: Response }\n /** The handler threw. Nothing was settled. */\n | { readonly kind: \"handler-failed\"; readonly thrown: unknown; readonly error: TabError }\n /** Delivered, but the facilitator would not settle. The response is a `402` carrying the failed `PAYMENT-RESPONSE`. */\n | { readonly kind: \"settlement-failed\"; readonly response: Response; readonly error: TabError };\n\n/**\n * Takes one prepaid request through verify, deliver, settle.\n *\n * Never throws and never rejects. A thrown handler is an outcome, not an\n * exception, so a host adapter can re-raise it the way its framework expects.\n */\nexport async function handlePrepaidRequest(options: PrepaidRequestOptions): Promise<PrepaidOutcome> {\n const logger = options.logger ?? defaultLogger;\n const billable = options.billable ?? ((response: X402DeliveredResponse) => response.status < 400);\n const required = paymentRequiredFor({ resource: options.resource, accepts: [options.requirements] });\n\n const rejected = (error: TabError): PrepaidOutcome => ({\n kind: \"rejected\",\n response: paymentRequiredResponse({ ...required, error: error.message }, error),\n error,\n });\n\n const matched = matchAccepted(options.payload.accepted, options.requirements);\n if (!matched.ok) return rejected(matched.error);\n\n const verified = await verifyPayment(options.facilitator, options.payload, options.requirements);\n if (!verified.ok) return rejected(verified.error);\n\n let response: Response;\n try {\n response = await options.deliver();\n } catch (thrown) {\n logger.debug(\"x402 prepaid call settled nothing because the handler failed\");\n return {\n kind: \"handler-failed\",\n thrown,\n error: tabError(\"INTERNAL\", \"HANDLER_FAILED\", \"the handler failed, so the verified payment was not settled\", {\n details: { settled: false },\n cause: causeOf(thrown),\n }),\n };\n }\n\n let deliverable: boolean;\n try {\n deliverable = billable(response) === true;\n } catch (thrown) {\n logger.error(\"x402 billable predicate threw and was read as not billable\", causeOf(thrown));\n deliverable = false;\n }\n if (!deliverable) return { kind: \"not-delivered\", response };\n\n const settled = await settlePayment(options.facilitator, options.payload, options.requirements);\n if (!settled.ok) {\n discard(response, logger);\n const failure: SettleResponse = {\n success: false,\n errorReason: String(settled.error.details?.[\"reason\"] ?? settled.error.code),\n transaction: String(settled.error.details?.[\"transaction\"] ?? \"\"),\n network: options.requirements.network,\n ...(typeof settled.error.details?.[\"payer\"] === \"string\" ? { payer: settled.error.details[\"payer\"] } : {}),\n };\n return { kind: \"settlement-failed\", response: settlementFailedResponse(failure, settled.error), error: settled.error };\n }\n\n const headers = paymentResponseHeaders(settled.value);\n if (!headers.ok) {\n // The funds moved and the work is delivered; a header that will not encode\n // costs the caller the receipt and nothing else.\n logger.error(\"x402 settlement succeeded but PAYMENT-RESPONSE would not encode\", { code: headers.error.code });\n return { kind: \"paid\", response, settlement: settled.value, payer: settled.value.payer };\n }\n return { kind: \"paid\", response: withHeaders(response, headers.value, logger), settlement: settled.value, payer: settled.value.payer };\n}\n\n/** A `402` carrying `PAYMENT-REQUIRED` and a JSON body naming the error. */\nexport function paymentRequiredResponse(required: PaymentRequired, error: TabError, extraHeaders: Readonly<Record<string, string>> = {}): Response {\n const encoded = paymentRequiredHeaders(required);\n return new Response(JSON.stringify({ ok: false, error }), {\n status: 402,\n headers: {\n ...extraHeaders,\n ...(encoded.ok ? encoded.value : {}),\n \"Content-Type\": \"application/json; charset=utf-8\",\n },\n });\n}\n\n/** A `402` carrying a failed `PAYMENT-RESPONSE`, as the HTTP transport specification shows. */\nfunction settlementFailedResponse(failure: SettleResponse, error: TabError): Response {\n const encoded = paymentResponseHeaders(failure);\n return new Response(JSON.stringify({ ok: false, error }), {\n status: 402,\n headers: { ...(encoded.ok ? encoded.value : {}), \"Content-Type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/** Puts headers on a response, copying it when its headers are immutable. */\nfunction withHeaders(response: Response, headers: Readonly<Record<string, string>>, logger: Logger): Response {\n try {\n for (const [name, value] of Object.entries(headers)) response.headers.set(name, value);\n return response;\n } catch {\n logger.debug(\"response headers were immutable, so PAYMENT-RESPONSE went onto a copy\");\n const merged = new Headers(response.headers);\n for (const [name, value] of Object.entries(headers)) merged.set(name, value);\n return new Response(response.body, { status: response.status, statusText: response.statusText, headers: merged });\n }\n}\n\nfunction discard(response: Response, logger: Logger): void {\n const body = response.body;\n if (body === null || response.bodyUsed) return;\n try {\n body.cancel().catch((error: unknown) => logger.debug(\"discarded response body could not be cancelled\", causeOf(error)));\n } catch (error) {\n logger.debug(\"discarded response body could not be cancelled\", causeOf(error));\n }\n}\n"]}
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * ## What is official and what is not
14
14
  *
15
- * The types and the three header codecs come from `@x402/core`, the reference
15
+ * The types and the three header codecs come from `@x402/core`, the official
16
16
  * implementation, so a `PaymentRequired` built here is what an x402 client
17
17
  * elsewhere decodes and a `PaymentPayload` decoded here is what one sent. The
18
18
  * codecs throw on malformed input; every wrapper below turns that into a
package/dist/x402/wire.js CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * ## What is official and what is not
14
14
  *
15
- * The types and the three header codecs come from `@x402/core`, the reference
15
+ * The types and the three header codecs come from `@x402/core`, the official
16
16
  * implementation, so a `PaymentRequired` built here is what an x402 client
17
17
  * elsewhere decodes and a `PaymentPayload` decoded here is what one sent. The
18
18
  * codecs throw on malformed input; every wrapper below turns that into a