@devlab.group/agent-commerce 0.1.0-alpha.0 → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/x402.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/payments/x402/client.ts","../src/payments/x402/amount.ts","../src/payments/x402/chain.ts","../src/payments/x402/local-chain/accounts.ts","../src/payments/x402/dev-key-guard.ts","../src/payments/x402/payload.ts","../src/payments/x402/replay-key.ts","../src/payments/x402/provider.ts"],"names":["privateKeyToAccount","verify","getAddress","x402Verify","getNetworkId","settle","x402Settle"],"mappings":";;;;;;;;AAmCA,IAAM,iCAAA,GAAoC;AAAA,EACxC,yBAAA,EAA2B;AAAA,IACzB,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAU;AAAA,IAChC,EAAE,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,SAAA,EAAU;AAAA,IAC9B,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,SAAA,EAAU;AAAA,IACjC,EAAE,IAAA,EAAM,YAAA,EAAc,IAAA,EAAM,SAAA,EAAU;AAAA,IACtC,EAAE,IAAA,EAAM,aAAA,EAAe,IAAA,EAAM,SAAA,EAAU;AAAA,IACvC,EAAE,IAAA,EAAM,OAAA,EAAS,IAAA,EAAM,SAAA;AAAU;AAErC,CAAA;AAEA,IAAM,gCAAA,GAAmC,GAAA;AAGzC,eAAsB,mBAAmB,OAAA,EAAqD;AAC5F,EAAA,MAAM,YAAA,GAAe,yBAAA,CAA0B,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA;AACpE,EAAA,IACE,CAAC,YAAA,CAAa,KAAA,IACd,OAAO,aAAa,KAAA,CAAM,MAAM,CAAA,KAAM,QAAA,IACtC,OAAO,YAAA,CAAa,KAAA,CAAM,SAAS,MAAM,QAAA,EACzC;AACA,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF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;AAgBA,SAAS,2BAA2B,GAAA,EAAuB;AACzD,EAAA,IACE,GAAA,YAAe,gBAAA,IACf,GAAA,YAAe,YAAA,IACf,eAAe,qCAAA,EACf;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,MAAM,OAAA,GAAU,aAAA,CAAc,GAAG,CAAA,CAAE,WAAA,EAAY;AAC/C,EAAA,OACE,OAAA,CAAQ,SAAS,cAAc,CAAA,IAC/B,QAAQ,QAAA,CAAS,cAAc,CAAA,IAC/B,OAAA,CAAQ,QAAA,CAAS,WAAW,KAC5B,OAAA,CAAQ,QAAA,CAAS,WAAW,CAAA,IAC5B,OAAA,CAAQ,SAAS,WAAW,CAAA,IAC5B,OAAA,CAAQ,QAAA,CAAS,eAAe,CAAA;AAEpC;AAGA,SAAS,cAAc,GAAA,EAAsB;AAC3C,EAAA,IAAI,GAAA,YAAe,OAAO,OAAO,CAAA,EAAG,IAAI,IAAI,CAAA,EAAA,EAAK,IAAI,OAAO,CAAA,CAAA;AAC5D,EAAA,OAAO,OAAO,GAAG,CAAA;AACnB;AAQA,eAAe,iBACb,MAAA,EACkB;AAElB,EAAA,MAAM,UAAU,MAAA,CAAO,OAAA;AAIvB,EAAA,IAAI;AACF,IAAA,MAAM,QAAQ,EAAE,MAAA,EAAQ,kBAAkB,MAAA,EAAQ,IAAI,CAAA;AACtD,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"x402.js","sourcesContent":["/**\n * CLIENT-SIDE payment helper.\n *\n * This module is used by the demo buyer agent (`demo/agent`) and by the\n * payment E2E test suite to build and EIP-712-sign an x402 `exact`/EVM\n * payment authorisation, entirely on the buyer's side.\n *\n * The gateway NEVER calls this module and NEVER holds a buyer private key.\n * `buyerPrivateKey` here is always an Anvil well-known\n * development key (LOCAL DEVELOPMENT ONLY — DO NOT FUND) supplied by whoever\n * is driving the demo/test, not something the provider or gateway manages.\n */\n\nimport { getAddress, toHex } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { encodePayment } from 'x402/schemes';\nimport { getNetworkId } from 'x402/shared';\nimport { type PaymentPayload, PaymentRequirementsSchema } from 'x402/types';\n\nexport interface CreatePaymentProofOptions {\n /** Buyer's dev-only private key. LOCAL DEVELOPMENT ONLY — DO NOT FUND. */\n readonly buyerPrivateKey: `0x${string}`;\n readonly rpcUrl: string;\n /** One entry from PaymentRequiredEnvelope.payment.accepts, verbatim. */\n readonly accepts: Readonly<Record<string, unknown>>;\n /** Overrides used only by negative tests (wrong amount/recipient/nonce…). */\n readonly overrides?: {\n readonly value?: string;\n readonly payTo?: string;\n readonly nonce?: `0x${string}`;\n readonly validBefore?: number;\n readonly validAfter?: number;\n };\n}\n\nconst 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\nconst DEFAULT_VALID_AFTER_SKEW_SECONDS = 600; // 10 minutes in the past, matching x402's own client default.\n\n/** Returns the base64 `X-PAYMENT` value to send back to the gateway. */\nexport async function createPaymentProof(options: CreatePaymentProofOptions): Promise<string> {\n const requirements = PaymentRequirementsSchema.parse(options.accepts);\n if (\n !requirements.extra ||\n typeof requirements.extra['name'] !== 'string' ||\n typeof requirements.extra['version'] !== 'string'\n ) {\n throw new Error(\n 'createPaymentProof: payment requirement is missing extra.name/extra.version — cannot build the EIP-712 domain',\n );\n }\n\n const account = privateKeyToAccount(options.buyerPrivateKey);\n // `rpcUrl` is part of the frozen `CreatePaymentProofOptions` shape for\n // interface parity with other providers, but the `exact`/EVM scheme signs\n // fully offline: the chain id comes from the network name (matching what\n // the facilitator's `verify()`/`settle()` compute, and the\n // nonce is a fresh random value, not one read from chain state.\n void options.rpcUrl;\n const chainId = getNetworkId(requirements.network);\n\n const nonce = options.overrides?.nonce ?? randomNonce();\n const nowSeconds = Math.floor(Date.now() / 1000);\n const validAfter = options.overrides?.validAfter ?? nowSeconds - DEFAULT_VALID_AFTER_SKEW_SECONDS;\n const validBefore = options.overrides?.validBefore ?? nowSeconds + requirements.maxTimeoutSeconds;\n const to = getAddress((options.overrides?.payTo ?? requirements.payTo) as `0x${string}`);\n const value = BigInt(options.overrides?.value ?? requirements.maxAmountRequired);\n\n const signature = await account.signTypedData({\n domain: {\n name: requirements.extra['name'],\n version: requirements.extra['version'],\n chainId,\n verifyingContract: getAddress(requirements.asset as `0x${string}`),\n },\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message: {\n from: account.address,\n to,\n value,\n validAfter: BigInt(validAfter),\n validBefore: BigInt(validBefore),\n nonce,\n },\n });\n\n const payload: PaymentPayload = {\n x402Version: 1,\n scheme: 'exact',\n network: requirements.network,\n payload: {\n signature,\n authorization: {\n from: account.address,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n },\n },\n };\n\n return encodePayment(payload);\n}\n\nfunction randomNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return toHex(bytes);\n}\n","/**\n * Deterministic decimal <-> base-unit conversion.\n *\n * `DecimalAmount` (see src/core) is a decimal string in\n * *display* units (\"0.01\" USDC). x402 / EIP-3009 need base units (integer\n * string, e.g. \"10000\" for 0.01 USDC at 6 decimals). This conversion must\n * never go through a JS `number` — floating point cannot represent most\n * decimal fractions exactly, and a silently-rounded payment amount is a\n * security bug in a payment provider.\n *\n * viem's own `parseUnits` rounds silently when given more fractional digits\n * than `decimals` supports; we need a hard error instead (a merchant asking\n * for \"0.0000001\" against a 6-decimal asset is a configuration bug, not a\n * roundable amount), so this module implements its own strict parser.\n */\nimport { CommerceError } from '../../core/index.js';\n\nconst DECIMAL_STRING_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\n/**\n * Parses a canonical decimal display amount (e.g. \"0.01\") into base units\n * for an asset with the given number of decimals, without floating point.\n *\n * Throws `CommerceError('PAYMENT_INVALID')` if the string is not a plain\n * non-negative decimal, or if it carries more fractional digits than the\n * asset supports.\n */\nexport function parseCanonicalAmount(amount: string, decimals: number): bigint {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new CommerceError('INTERNAL_ERROR', `Invalid asset decimals: ${decimals}`);\n }\n if (!DECIMAL_STRING_PATTERN.test(amount)) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" is not a valid non-negative decimal string`,\n {\n details: { amount },\n },\n );\n }\n\n const [integerPart = '0', fractionPart = ''] = amount.split('.');\n\n if (fractionPart.length > decimals) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" has more precision than the asset supports (${decimals} decimals)`,\n { details: { amount, assetDecimals: decimals } },\n );\n }\n\n const paddedFraction = fractionPart.padEnd(decimals, '0');\n const combined = `${integerPart}${paddedFraction}`;\n // Strip leading zeros so BigInt doesn't choke on e.g. \"007\" — BigInt() is\n // fine with leading zeros in decimal strings, but normalise defensively.\n return BigInt(combined);\n}\n\n/**\n * Formats base units back into a canonical decimal display string.\n *\n * Exact (no rounding is possible going from integer base units to a wider\n * decimal representation), so this is safe to implement directly.\n */\nexport function formatCanonicalAmount(baseUnits: bigint, decimals: number): string {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new CommerceError('INTERNAL_ERROR', `Invalid asset decimals: ${decimals}`);\n }\n const negative = baseUnits < 0n;\n const abs = negative ? -baseUnits : baseUnits;\n const digits = abs.toString().padStart(decimals + 1, '0');\n const integerPart = digits.slice(0, digits.length - decimals) || '0';\n const fractionPart = digits.slice(digits.length - decimals).replace(/0+$/, '');\n const sign = negative ? '-' : '';\n return fractionPart.length > 0\n ? `${sign}${integerPart}.${fractionPart}`\n : `${sign}${integerPart}`;\n}\n","/**\n * Local deterministic chain wiring.\n *\n * The x402 SDK's own `createConnectedClient(network)` / `createSigner(...)`\n * helpers resolve RPC endpoints from a hard-coded table of public networks —\n * exactly what we must never touch: the tests must stay deterministic.\n * Instead we build plain viem clients pointed at `options.rpcUrl`,\n * using a custom `Chain` object whose id is 84532 so that x402's\n * `getNetworkId('base-sepolia')` (which returns 84532) matches the chain the\n * client is actually talking to.\n *\n * The `Local` prefix on everything here describes the *chain* these clients\n * are built for, not a test-only status: `provider.ts` calls\n * `createLocalPublicClient` and `createLocalFacilitatorClient` on the real\n * settlement path, for every payment. This is not demo scaffolding that a\n * production build could drop — v0.1 settles against the deterministic local\n * chain, so this file *is* the settlement transport. Supporting a public\n * network means making `buildLocalChain`'s hardcoded `LOCAL_CHAIN_ID` a\n * parameter, not bypassing this module.\n *\n * `dev-key-guard.ts` is the boundary that keeps that arrangement safe: it\n * refuses at provider construction if a dev key or dev `payTo` is pointed at\n * anything other than a loopback/private RPC.\n */\nimport {\n type Account,\n type Chain,\n type Client,\n createPublicClient,\n createWalletClient,\n http,\n type PublicActions,\n type PublicClient,\n publicActions,\n type Transport,\n type WalletActions,\n} from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\n/** A wallet client that can also read chain state — matches x402's `SignerWallet`. */\nexport type LocalFacilitatorClient = Client<\n Transport,\n Chain,\n Account,\n undefined,\n PublicActions<Transport, Chain, Account> & WalletActions<Chain, Account>\n>;\n\n/** x402's `getNetworkId('base-sepolia')`. Not a public testnet. */\nexport const LOCAL_CHAIN_ID = 84532;\n\nexport function buildLocalChain(rpcUrl: string): Chain {\n return {\n id: LOCAL_CHAIN_ID,\n name: 'agent-commerce-local',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: { http: [rpcUrl] },\n },\n } satisfies Chain;\n}\n\n/**\n * A viem `PublicClient` for the local chain — read-only, no signing capability.\n *\n * `timeoutMs`, when given, is passed straight to viem's `http()` transport,\n * which ties it to a real `AbortController` around the underlying `fetch`\n * (see viem's `utils/promise/withTimeout.js` — `signal: true`). That is a\n * genuine cancellation, unlike a bare `Promise.race` against a timer, which\n * only stops *waiting* for the request while the request itself keeps\n * running server-side. Omit it to keep viem's own default (10s).\n */\nexport function createLocalPublicClient(rpcUrl: string, timeoutMs?: number): PublicClient {\n return createPublicClient({\n chain: buildLocalChain(rpcUrl),\n transport: http(rpcUrl, timeoutMs !== undefined ? { timeout: timeoutMs } : undefined),\n });\n}\n\n/**\n * A viem `WalletClient` extended with public actions, for the local\n * facilitator signer only. x402's `settle()` calls `writeContract`,\n * `waitForTransactionReceipt` and `getCode` on this client — i.e. it needs\n * both `WalletActions` and `PublicActions`, matching x402's `SignerWallet`\n * type.\n *\n * LOCAL DEVELOPMENT ONLY — the private key behind this client must always be\n * an Anvil well-known development key, never a merchant or buyer key, and\n * never a production key of any kind.\n */\nexport function createLocalFacilitatorClient(\n rpcUrl: string,\n signerPrivateKey: `0x${string}`,\n): LocalFacilitatorClient {\n const chain = buildLocalChain(rpcUrl);\n const account = privateKeyToAccount(signerPrivateKey);\n return createWalletClient({\n account,\n chain,\n transport: http(rpcUrl),\n }).extend(publicActions);\n}\n","/**\n * Anvil's well-known development accounts.\n *\n * LOCAL DEVELOPMENT ONLY — DO NOT FUND. These addresses and private keys are\n * derived from Foundry's public, well-documented default test mnemonic\n * (\"test test test test test test test test test test test junk\") and are\n * known to everyone who has ever run `anvil`. Anyone who sends real value to\n * one of these addresses on a real network will lose it.\n *\n * Index layout used by the local demo chain (see docs/contracts.md):\n * 0 — deployer / local facilitator signer (pays gas, broadcasts settlement)\n * 1 — merchant settlement destination (`payTo`)\n * 2 — buyer (signs EIP-3009 authorisations; never held by the gateway)\n */\nexport interface AnvilWellKnownAccount {\n readonly address: `0x${string}`;\n readonly privateKey: `0x${string}`;\n}\n\n/** Fixed-length tuple (not a bare array) so indexing by the documented layout above is fully typed. */\nexport const ANVIL_WELL_KNOWN_ACCOUNTS: readonly [\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n AnvilWellKnownAccount,\n] = [\n {\n address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',\n privateKey: '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80',\n },\n {\n address: '0x70997970C51812dc3A010C7d01b50e0d17dc79C8',\n privateKey: '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',\n },\n {\n address: '0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC',\n privateKey: '0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a',\n },\n];\n\nexport const LOCAL_FACILITATOR_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[0];\nexport const LOCAL_MERCHANT_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[1];\nexport const LOCAL_BUYER_ACCOUNT = ANVIL_WELL_KNOWN_ACCOUNTS[2];\n\n/** Safe label used everywhere a dev key appears in output, logs or manifests. */\nexport const DEV_KEY_LABEL = 'LOCAL DEVELOPMENT ONLY - DO NOT FUND';\n","/**\n * Prevents a well-known Anvil development private key — or a well-known\n * Anvil development *address* — from ever being used against anything other\n * than a loopback/private/dev RPC. Two symmetric mistakes, both covered:\n * signing settlement with a dev key (`assertDevKeyIsLocalOnly`), and routing\n * settlement revenue to a dev address (`assertPayToIsNotDevAddress`). The\n * second is the more consequential of the two — a wrong key merely fails to\n * sign, a wrong payTo silently succeeds and gives the money away, since the\n * private key behind every well-known Anvil address is public (see in\n * the.\n *\n * Chain id alone cannot tell a real network from this project's local dev\n * chain: Base Sepolia's own chain id is 84532, the same id this project\n * deliberately reuses for the local chain so the unmodified x402\n * SDK's `getNetworkId('base-sepolia')` lines up with it. A dev key or dev\n * payTo pointed at a real RPC by a config mistake is instantly drainable —\n * this is checked once at provider construction, not per payment.\n */\nimport { CommerceError } from '../../core/index.js';\nimport { ANVIL_WELL_KNOWN_ACCOUNTS } from './local-chain/accounts.js';\n\nconst WELL_KNOWN_DEV_KEYS: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.privateKey.toLowerCase()),\n);\n\nconst WELL_KNOWN_DEV_ADDRESSES: ReadonlySet<string> = new Set(\n ANVIL_WELL_KNOWN_ACCOUNTS.map((a) => a.address.toLowerCase()),\n);\n\n/** `0x` + 64 hex chars — the only shape `privateKeyToAccount` accepts. */\nconst PRIVATE_KEY_SHAPE = /^0x[0-9a-fA-F]{64}$/;\n\nexport function isWellKnownDevKey(privateKey: string): boolean {\n return WELL_KNOWN_DEV_KEYS.has(privateKey.toLowerCase());\n}\n\nexport function isWellKnownDevAddress(address: string): boolean {\n return WELL_KNOWN_DEV_ADDRESSES.has(address.toLowerCase());\n}\n\n/**\n * True for loopback addresses, RFC1918 private ranges, and bare (dot-free)\n * hostnames — the shape of a docker-compose/k8s service name (e.g.\n * \"anvil\"), which a real public DNS name essentially never has.\n *\n * ASSUMPTION (the loosest edge of this guard, named explicitly per external\n *: every dot-free, colon-free hostname is treated as\n * private, with no exceptions. A single-label *public* hostname (no dots) is\n * essentially nonexistent in practice — ICANN does not delegate bare\n * gTLDs/TLDs as public A/AAAA records — but this function cannot tell \"no\n * dots because it's a compose service name\" from \"no dots because it's an\n * unusual real host\" if one somehow existed. If that assumption ever stops\n * holding, this is the line to revisit.\n */\nexport function isLikelyLocalOrPrivateHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (h === 'localhost' || h === '127.0.0.1' || h === '::1') return true;\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^192\\.168\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (/^172\\.(1[6-9]|2\\d|3[01])\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n if (!h.includes('.') && !h.includes(':')) return true; // bare hostname\n return false;\n}\n\nfunction parseHostnameOrThrow(rpcUrl: string): string {\n try {\n return new URL(rpcUrl).hostname;\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: rpcUrl \"${rpcUrl}\" is not a valid URL`,\n { cause },\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if a well-known dev key would sign against a non-local\n * RPC — or if `signerPrivateKey` isn't shaped like a private key at all.\n *\n * The shape check runs first and unconditionally. \"Not a key I recognise\"\n * (falls through `isWellKnownDevKey`, silently treated as someone's own real\n * facilitator key) and \"not a key at all\" (e.g. a truncated 63-char string)\n * must never share a code path: a malformed key that slips past this guard\n * only fails later, inside `settle()`, after the buyer's replayKey is already\n * reserved (see in the.\n */\nexport function assertDevKeyIsLocalOnly(rpcUrl: string, signerPrivateKey: string): void {\n if (!PRIVATE_KEY_SHAPE.test(signerPrivateKey)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is not a well-formed private key ' +\n '(expected \"0x\" followed by exactly 64 hex characters).',\n );\n }\n\n if (!isWellKnownDevKey(signerPrivateKey)) return; // a real facilitator key: not our business\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: facilitator.signerPrivateKey is a well-known Anvil development key, but rpcUrl ' +\n `\"${rpcUrl}\" does not look like a local/private chain. A public dev key must never sign against ` +\n 'a public network — it is instantly drainable and can grief real settlements via nonce exhaustion. ' +\n 'Use a real facilitator key for any non-local RPC, or point rpcUrl at your local/dev chain.',\n );\n }\n}\n\n/**\n * Throws CONFIG_INVALID if `payTo` (the settlement destination) is a\n * well-known Anvil development address and `rpcUrl` doesn't look\n * local/private.\n *\n * Mirrors `assertDevKeyIsLocalOnly`, but guards the *receiving* side of the\n * payment instead of the signing side, and — unlike the key guard — applies\n * regardless of facilitator mode: which account signs the settlement\n * transaction has no bearing on whether the destination address is one whose\n * private key is public knowledge. `agent-commerce init` defaults `payTo` to\n * a well-known Anvil address as a local-demo convenience; on a real network\n * that default routes every payment to an address anyone on earth can sweep.\n */\nexport function assertPayToIsNotDevAddress(rpcUrl: string, payTo: string): void {\n if (!isWellKnownDevAddress(payTo)) return; // not a dev address: not our business\n\n const hostname = parseHostnameOrThrow(rpcUrl);\n\n if (!isLikelyLocalOrPrivateHost(hostname)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" (${payTo}) is a well-known Anvil development address, but rpcUrl ` +\n `\"${rpcUrl}\" does not look like a local/private chain. The private key behind that address ` +\n 'is public knowledge, so any revenue settled to it is immediately spendable by anyone. Set ' +\n '\"payTo\" to your own merchant wallet for any non-local RPC, or point rpcUrl at your ' +\n 'local/dev chain.',\n );\n }\n}\n","/**\n * Decoding and validation for the base64 `X-PAYMENT` submission.\n *\n * A malformed payload (not base64, valid base64 but not JSON, valid JSON but\n * the wrong shape) must yield a `rejected` verification result, never a\n * thrown/crashed request — this module returns `undefined` on any failure so\n * callers can turn that into a typed rejection.\n */\nimport { type ExactEvmPayload, type PaymentPayload, PaymentPayloadSchema } from 'x402/types';\n\nexport function decodePaymentSubmission(payloadBase64: string): PaymentPayload | undefined {\n let json: unknown;\n try {\n const decoded = Buffer.from(payloadBase64, 'base64').toString('utf8');\n json = JSON.parse(decoded);\n } catch {\n return undefined;\n }\n\n const result = PaymentPayloadSchema.safeParse(json);\n return result.success ? result.data : undefined;\n}\n\n/** Narrows a decoded payload to the EVM `exact` scheme shape this provider supports. */\nexport function isExactEvmPayload(\n payload: PaymentPayload,\n): payload is PaymentPayload & { payload: ExactEvmPayload } {\n return (\n payload.scheme === 'exact' &&\n typeof payload.payload === 'object' &&\n payload.payload !== null &&\n 'authorization' in payload.payload &&\n 'signature' in payload.payload\n );\n}\n","/**\n * Replay-key derivation.\n *\n *Per docs/contracts.md, `PaymentResult.replayKey` MUST be\n * derived only from the payment authorisation (chain id, asset, payer,\n * nonce) — never from the request id — so that the same authorisation\n * replayed against a *different* request still collides in the gateway's\n * receipt-store reservation.\n */\nimport { encodeAbiParameters, keccak256 } from 'viem';\n\nexport interface ReplayKeyInput {\n readonly chainId: number;\n readonly asset: `0x${string}`;\n readonly from: `0x${string}`;\n readonly nonce: `0x${string}`;\n}\n\nexport function computeReplayKey(input: ReplayKeyInput): string {\n const encoded = encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }],\n [BigInt(input.chainId), input.asset, input.from, input.nonce],\n );\n return keccak256(encoded);\n}\n","/**\n * x402 payment provider — `exact` scheme, EVM, EIP-3009 `transferWithAuthorization`.\n *\n * Implements the frozen `PaymentProvider` interface (src/core/domain/payment.ts).\n * `verify()` never moves funds; only `settle()` does, and only after a\n * successful `verify()` (enforced by the gateway's execution pipeline, not by\n * this file, but this file never calls settle-like RPCs from verify()).\n *\n * The behaviour of x402@1.2.0 relied on here is verified, not assumed: see the\n * SDK-behaviour notes beside each call site below.\n */\n\nimport {\n ContractFunctionExecutionError,\n ContractFunctionRevertedError,\n getAddress,\n HttpRequestError,\n isAddress,\n TimeoutError,\n WaitForTransactionReceiptTimeoutError,\n} from 'viem';\nimport { settle as x402Settle, verify as x402Verify } from 'x402/facilitator';\nimport { getNetworkId } from 'x402/shared';\nimport type { PaymentRequirements } from 'x402/types';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type IdGenerator,\n type Logger,\n NOOP_LOGGER,\n type PaymentContext,\n type PaymentProvider,\n type PaymentRequirement,\n type PaymentResult,\n type PaymentSettlementContext,\n type PaymentVerificationContext,\n systemClock,\n} from '../../core/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { formatCanonicalAmount, parseCanonicalAmount } from './amount.js';\nimport {\n createLocalFacilitatorClient,\n createLocalPublicClient,\n LOCAL_CHAIN_ID,\n type LocalFacilitatorClient,\n} from './chain.js';\nimport { assertDevKeyIsLocalOnly, assertPayToIsNotDevAddress } from './dev-key-guard.js';\nimport { decodePaymentSubmission, isExactEvmPayload } from './payload.js';\nimport { computeReplayKey } from './replay-key.js';\n\nconst X402_PROTOCOL_VERSION = '1';\nconst DEFAULT_MAX_TIMEOUT_SECONDS = 60;\nconst DEFAULT_MIME_TYPE = 'application/json';\nconst HEALTH_TIMEOUT_MS = 4_000;\n\nexport interface X402ProviderOptions {\n /** x402 network name. Local deterministic chain uses 'base-sepolia'. */\n readonly network: string;\n /** RPC endpoint. Local chain: http://127.0.0.1:8545 */\n readonly rpcUrl: string;\n /** ERC-20 (EIP-3009) asset address used for settlement. */\n readonly asset: `0x${string}`;\n /** EIP-712 domain name of the asset, e.g. 'MockUSDC'. */\n readonly assetName: string;\n /** EIP-712 domain version of the asset, e.g. '2'. */\n readonly assetVersion: string;\n readonly assetDecimals: number;\n /** Merchant-controlled settlement destination. Never a gateway-owned wallet. */\n readonly payTo: `0x${string}`;\n readonly maxTimeoutSeconds?: number;\n /**\n * Local facilitator: signer broadcasts settlement on the dev chain only.\n * LOCAL DEVELOPMENT ONLY — DO NOT FUND.\n */\n readonly facilitator:\n | { readonly mode: 'local'; readonly signerPrivateKey: `0x${string}` }\n | { readonly mode: 'remote'; readonly url: string };\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst DEFAULT_IDS: IdGenerator = {\n next: (prefix?: string) => `${prefix ? `${prefix}_` : ''}${crypto.randomUUID()}`,\n};\n\nexport function createX402PaymentProvider(options: X402ProviderOptions): PaymentProvider {\n if (!isAddress(options.asset)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"asset\" is not a valid EVM address: ${options.asset}`,\n );\n }\n if (!isAddress(options.payTo)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" is not a valid EVM address: ${options.payTo}`,\n );\n }\n // Applies regardless of facilitator.mode — which account signs settlement\n // has no bearing on whether the destination address's private key is\n // public knowledge.\n assertPayToIsNotDevAddress(options.rpcUrl, options.payTo);\n if (!Number.isInteger(options.assetDecimals) || options.assetDecimals < 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"assetDecimals\" must be a non-negative integer`,\n );\n }\n // Constructed once, here, rather than inside settle(): assertDevKeyIsLocalOnly\n // above already proves the key is well-formed, so privateKeyToAccount is not\n // expected to throw — but if it somehow does (or the key/RPC combination is\n // otherwise unusable), that is a *configuration* problem, and a bad key\n // should fail the provider at startup, not on the first paying customer's\n // request (after their replayKey is already reserved — see in the\n //. This mirrors the other CONFIG_INVALID checks above,\n // which are all one-time, construction-time validation rather than\n // per-request checks.\n let facilitatorClient: LocalFacilitatorClient | undefined;\n if (options.facilitator.mode === 'local') {\n assertDevKeyIsLocalOnly(options.rpcUrl, options.facilitator.signerPrivateKey);\n try {\n facilitatorClient = createLocalFacilitatorClient(\n options.rpcUrl,\n options.facilitator.signerPrivateKey,\n );\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: could not construct a local facilitator signer from ' +\n 'facilitator.signerPrivateKey — it must be a valid 32-byte hex private key',\n { cause },\n );\n }\n }\n\n // Constructed once, alongside facilitatorClient and for the same reason:\n // viem's PublicClient is a stateless transport wrapper (every method call\n // issues its own fresh RPC request — there is no cached chain state to go\n // stale by reusing the object), so building a new one per verify() call was\n // pure allocation with no correctness benefit. Shared safely across\n // concurrent calls, same as facilitatorClient.\n const publicClient = createLocalPublicClient(options.rpcUrl);\n // A second, separate client for health() specifically, with a real\n // transport-level timeout (see createLocalPublicClient's doc comment) —\n // scoped to health() only so verify()'s existing timeout behaviour (and\n // its isProviderUnavailableError classification tests) is untouched.\n const healthPublicClient = createLocalPublicClient(options.rpcUrl, HEALTH_TIMEOUT_MS);\n\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? DEFAULT_IDS;\n const logger = options.logger ?? NOOP_LOGGER;\n const maxTimeoutSeconds = options.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;\n\n const descriptor: AdapterDescriptor = {\n name: 'x402',\n kind: 'payment',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: 'x402@1.2.0 scheme=exact family=evm',\n capabilities: ['exact-evm', 'local-facilitator', 'eip-3009'],\n status: 'stable',\n unsupported: ['svm', 'deferred scheme', 'remote facilitator'],\n };\n\n async function createRequirement(context: PaymentContext): Promise<PaymentRequirement> {\n const maxAmountRequired = parseCanonicalAmount(\n context.amount,\n options.assetDecimals,\n ).toString();\n\n const requirements: PaymentRequirements = {\n scheme: 'exact',\n // options.network is a canonical free-form string (frozen contract); the\n // x402 SDK's Network union is checked against the live chain in health()\n // and by verify()'s own network-mismatch guard.\n network: options.network as PaymentRequirements['network'],\n maxAmountRequired,\n // Descriptive metadata only: `resource` is not part of the EIP-3009\n // authorisation the buyer signs (`from`/`to`/`value`/`validAfter`/\n // `validBefore`/`nonce`), nothing verifies against it, and the replay\n // key is keyed on the authorisation rather than on this string. It is\n // still what a facilitator, wallet or buyer agent logs and shows, so it\n // carries `network` and `payTo` — both already public in this same\n // challenge — to stay unambiguous across the wider x402 ecosystem,\n // where the `agent-commerce` authority alone is not reserved to us.\n resource: `resource://agent-commerce/${encodeURIComponent(options.network)}/${options.payTo}/resources/${encodeURIComponent(context.resource.id)}`,\n description: context.resource.description ?? context.resource.name,\n mimeType: DEFAULT_MIME_TYPE,\n payTo: options.payTo,\n maxTimeoutSeconds,\n asset: options.asset,\n // REQUIRED.name/version explicitly means\n // the facilitator never needs an on-chain version() call to build the\n // EIP-712 domain, so verification stays deterministic even against a\n // token that has no on-chain version() (it doesn't matter here since\n // MockUSDC has one, but this is what makes the domain unambiguous).\n extra: { name: options.assetName, version: options.assetVersion },\n };\n\n const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString();\n\n return {\n id: ids.next('payreq'),\n requestId: context.requestId,\n resourceId: context.resource.id,\n provider: 'x402',\n amount: context.amount,\n currency: context.currency,\n destination: options.payTo,\n network: options.network,\n asset: options.asset,\n expiresAt,\n challenge: {\n provider: 'x402',\n version: X402_PROTOCOL_VERSION,\n accepts: [requirements as unknown as Record<string, unknown>],\n },\n };\n }\n\n /**\n * Verifies a payment submission against a payment requirement.\n *\n * Deliberately accepts overpayment: only `authorizedValue < maxRequired` is\n * rejected (`wrong_amount`), never `authorizedValue > maxRequired`. This\n * matches x402's own semantics — `maxAmountRequired` names a floor, not an\n * exact amount — and the settled `PaymentResult.amount` always records the\n * actual authorised value, so bookkeeping stays truthful to what really\n * moved rather than silently topping up or rejecting a generous buyer. Not\n * an oversight: see (\"noted, no action\").\n */\n async function verify(context: PaymentVerificationContext): Promise<PaymentResult> {\n const { requirement, submission } = context;\n\n const rejected = (reason: string): PaymentResult => ({\n status: 'rejected',\n provider: 'x402',\n amount: requirement.amount,\n currency: requirement.currency,\n ...(requirement.network !== undefined ? { network: requirement.network } : {}),\n ...(requirement.asset !== undefined ? { asset: requirement.asset } : {}),\n rejectionReason: reason,\n });\n\n if (requirement.provider !== 'x402' || requirement.challenge.provider !== 'x402') {\n return rejected('wrong_provider');\n }\n\n const requirements = requirement.challenge.accepts[0] as PaymentRequirements | undefined;\n if (!requirements) {\n return rejected('missing_payment_requirements');\n }\n\n // Defence in depth, not the real expiry: the pipeline calls\n // createRequirement() fresh on every request, so by the time verify()\n // runs this requirement is only ever seconds old — this check will\n // essentially never fire in the current flow. The actual expiry\n // enforcement is EIP-3009's validBefore, checked inside the x402 SDK\n // (x402Verify below, `validBefore < now + 6s` -> invalid). Kept because\n // it is cheap and correct, not because it is load-bearing (external\n //.\n if (\n requirement.expiresAt !== undefined &&\n Date.parse(requirement.expiresAt) < clock.now().getTime()\n ) {\n return rejected('requirement_expired');\n }\n\n // Defensive invariant: the requirement we're verifying against must still\n // describe *this* provider's configured asset. It always will in normal\n // operation (we generated it), but a corrupted/mismatched requirement\n // must never be allowed to authorise a transfer for a different asset.\n if (\n !isAddress(requirements.asset) ||\n getAddress(requirements.asset) !== getAddress(options.asset)\n ) {\n return rejected('wrong_asset');\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload) {\n return rejected('malformed_payment_payload');\n }\n if (!isExactEvmPayload(payload)) {\n return rejected('unsupported_scheme');\n }\n\n const { authorization } = payload.payload;\n\n if (!isAddress(authorization.from) || !isAddress(authorization.to)) {\n return rejected('malformed_payment_payload');\n }\n if (payload.network !== options.network) {\n return rejected('wrong_network');\n }\n if (getAddress(authorization.to) !== getAddress(options.payTo)) {\n return rejected('wrong_recipient');\n }\n let authorizedValue: bigint;\n let maxRequired: bigint;\n try {\n authorizedValue = BigInt(authorization.value);\n maxRequired = BigInt(requirements.maxAmountRequired);\n } catch {\n return rejected('malformed_payment_payload');\n }\n if (authorizedValue < maxRequired) {\n return rejected('wrong_amount'); // overpayment is allowed through — see the doc comment above\n }\n\n let sdkResult: Awaited<ReturnType<typeof x402Verify>>;\n try {\n // x402's own.d.mts bundles a rolled-up copy of viem's `Chain`/`Client`\n // type declarations rather than re-exporting viem's, so TS treats them\n // as nominally distinct from the ones `chain.ts` imports directly even\n // though they describe the same runtime object. Casting to the SDK's\n // own declared parameter type (rather than to `any`) keeps this\n // narrowly scoped to that mismatch.\n sdkResult = await x402Verify(\n publicClient as Parameters<typeof x402Verify>[0],\n payload,\n requirements,\n );\n } catch (err) {\n if (isProviderUnavailableError(err)) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: RPC unreachable during verify()',\n {\n cause: err,\n },\n );\n }\n logger.warn({ err: describeError(err) }, 'x402 verify(): unexpected SDK error');\n return rejected('unexpected_verify_error');\n }\n\n if (!sdkResult.isValid) {\n return rejected(sdkResult.invalidReason ?? 'invalid_payment');\n }\n\n // Derived from the verified authorisation's own network, per\n // docs/contracts.md — never a provider-instance constant, so the key\n // stays correct the moment there is more than one chain id in play.\n const replayKey = computeReplayKey({\n chainId: getNetworkId(payload.network),\n asset: getAddress(requirements.asset),\n from: getAddress(authorization.from),\n nonce: authorization.nonce as `0x${string}`,\n });\n\n return {\n status: 'verified',\n provider: 'x402',\n payer: getAddress(authorization.from),\n payee: getAddress(authorization.to),\n amount: formatCanonicalAmount(authorizedValue, options.assetDecimals),\n currency: requirement.currency,\n network: payload.network,\n asset: getAddress(requirements.asset),\n replayKey,\n };\n }\n\n async function settle(context: PaymentSettlementContext): Promise<PaymentResult> {\n const { requirement, submission, verification } = context;\n\n if (verification.status !== 'verified') {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() called without a successful verify()',\n );\n }\n\n if (options.facilitator.mode !== 'local' || facilitatorClient === undefined) {\n throw new CommerceError(\n 'PROTOCOL_UNSUPPORTED',\n 'x402 provider: remote facilitator settlement is not implemented in v0.1.0-alpha; ' +\n 'only { mode: \"local\" } is supported',\n );\n }\n\n const requirements = requirement.challenge.accepts[0] as PaymentRequirements | undefined;\n if (!requirements) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() found no payment requirements to settle against',\n );\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload || !isExactEvmPayload(payload)) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() received an undecodable payment payload',\n );\n }\n\n // x402's settle() broadcasts (writeContract) then confirms\n // (waitForTransactionReceipt) on this client, but only returns the\n // transaction hash to us on success — if confirmation times out, the hash\n // never leaves the SDK. Intercept waitForTransactionReceipt on a per-call\n // wrapper (never mutate the shared client — settle() can run concurrently)\n // so the hash survives onto PAYMENT_PROVIDER_UNAVAILABLE's details even\n // when the SDK throws before returning it. See.\n let broadcastTxHash: `0x${string}` | undefined;\n const settlementClient: LocalFacilitatorClient = {\n ...facilitatorClient,\n waitForTransactionReceipt: (\n args: Parameters<LocalFacilitatorClient['waitForTransactionReceipt']>[0],\n ) => {\n broadcastTxHash = args.hash;\n return facilitatorClient.waitForTransactionReceipt(args);\n },\n };\n\n let sdkResult: Awaited<ReturnType<typeof x402Settle>>;\n try {\n sdkResult = await x402Settle(\n settlementClient as Parameters<typeof x402Settle>[0],\n payload,\n requirements,\n );\n } catch (err) {\n if (isProviderUnavailableError(err)) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: RPC unreachable during settle()',\n {\n cause: err,\n ...(broadcastTxHash !== undefined\n ? { details: { transactionHash: broadcastTxHash } }\n : {}),\n },\n );\n }\n const rejectionReason = isOnChainRevertError(err)\n ? 'transaction_reverted'\n : 'unexpected_settle_error';\n logger.warn(\n { err: describeError(err), rejectionReason },\n 'x402 settle(): settlement transaction failed',\n );\n return {\n status: 'rejected',\n provider: 'x402',\n amount: verification.amount,\n currency: requirement.currency,\n ...(verification.network !== undefined ? { network: verification.network } : {}),\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n rejectionReason,\n };\n }\n\n if (!sdkResult.success) {\n return {\n status: 'rejected',\n provider: 'x402',\n amount: verification.amount,\n currency: requirement.currency,\n network: sdkResult.network,\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(sdkResult.payer !== undefined ? { payer: sdkResult.payer } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n rejectionReason: sdkResult.errorReason ?? 'settlement_failed',\n };\n }\n\n return {\n status: 'settled',\n provider: 'x402',\n externalReference: sdkResult.transaction,\n ...(sdkResult.payer !== undefined ? { payer: sdkResult.payer } : {}),\n payee: requirements.payTo,\n amount: verification.amount,\n currency: requirement.currency,\n network: sdkResult.network,\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n settledAt: clock.nowIso(),\n };\n }\n\n async function computeHealth(): Promise<AdapterHealth> {\n const startedAt = clock.monotonicMs();\n const checkedAt = clock.nowIso();\n\n try {\n const chainId = await healthPublicClient.getChainId();\n if (chainId !== LOCAL_CHAIN_ID) {\n return {\n status: 'fail',\n detail: `RPC at ${options.rpcUrl} reports chain id ${chainId}, expected ${LOCAL_CHAIN_ID}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n const code = await healthPublicClient.getCode({ address: options.asset });\n if (!code || code === '0x') {\n return {\n status: 'fail',\n detail: `No contract code found at configured asset address ${options.asset}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n if (options.facilitator.mode === 'remote') {\n return {\n status: 'warn',\n detail:\n 'RPC and asset are reachable; remote facilitator mode is not implemented in v0.1.0-alpha',\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n // Chain id alone cannot prove this is a dev chain: real Base Sepolia\n // reports the same id (84532) by this project's own design (\n //). Probe an Anvil-only RPC method — present only on a real\n // Anvil node — before trusting a well-known dev key against it.\n const isAnvil = await probeIsAnvilNode(healthPublicClient);\n if (!isAnvil) {\n return {\n status: 'fail',\n detail:\n `RPC at ${options.rpcUrl} reports chain id ${LOCAL_CHAIN_ID} but does not answer ` +\n '\"anvil_nodeInfo\" — it does not look like a local Anvil dev node. Refusing to treat it ' +\n 'as safe for a local-facilitator dev key.',\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n return {\n status: 'pass',\n detail:\n `RPC ${options.rpcUrl} reachable, chain id ${LOCAL_CHAIN_ID}, asset ${options.asset} has ` +\n 'code, confirmed Anvil dev node',\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n return {\n status: 'fail',\n detail: `x402 health check failed: ${describeError(err)}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n\n // /ready has no auth, no cache and no\n // rate limit, and called computeHealth() — 3 live RPC calls — on every\n // single request; measured 3x amplification of billed upstream calls\n // under an unauthenticated flood. Memoise behind a short TTL and collapse\n // concurrent callers onto one in-flight probe, so N requests within the\n // window produce at most one round-trip instead of N.\n //\n // 5s: short enough that a readiness probe (Kubernetes' own default\n // `periodSeconds` is 10s) never observes data older than its own poll\n // interval, long enough to fully decouple RPC call volume from HTTP\n // request volume — which is the property that closes the amplification,\n // not the exact number of seconds.\n //\n // pass and fail are cached for the same TTL, deliberately: a shorter TTL\n // for fail would re-introduce the amplification exactly when an upstream\n // outage makes every call expensive/slow, which is the worst possible time\n // to remove the cache's protection. 5s of recovery latency after the RPC\n // comes back is an acceptable trade — it is already within the noise of a\n // single health probe's own round-trip time, and well inside a normal\n // probe's own poll interval.\n //\n // This only memoises this provider's own RPC probe. `core` separately\n // memoises the whole /ready aggregation (src/gateway/readiness.ts)\n // — a second, independent layer at a different scope; the two compose\n // without conflict since neither assumes anything about the other's TTL.\n //\n // Does not affect `doctor`'s deployment-mismatch cross-check: that reads\n // asset/network/payTo straight from `/.well-known/agent-commerce` (static\n // provider config, echoed live, never cached), not from health().\n const HEALTH_CACHE_MS = 5_000;\n let cachedHealth: { at: number; value: AdapterHealth } | undefined;\n let inFlightHealth: Promise<AdapterHealth> | undefined;\n\n async function health(): Promise<AdapterHealth> {\n const now = clock.monotonicMs();\n if (cachedHealth && now - cachedHealth.at < HEALTH_CACHE_MS) {\n return cachedHealth.value;\n }\n if (inFlightHealth) return inFlightHealth;\n\n inFlightHealth = computeHealth()\n .then((value) => {\n cachedHealth = { at: clock.monotonicMs(), value };\n return value;\n })\n .finally(() => {\n inFlightHealth = undefined;\n });\n return inFlightHealth;\n }\n\n return {\n name: 'x402',\n descriptor,\n createRequirement,\n verify,\n settle,\n health,\n };\n}\n\nfunction isOnChainRevertError(err: unknown): boolean {\n return (\n err instanceof ContractFunctionRevertedError || err instanceof ContractFunctionExecutionError\n );\n}\n\n/**\n * `instanceof` checks first — these are the real error classes the pinned\n * viem@2.55.18 HTTP transport throws (see viem's `utils/rpc/http.js`, which\n * wraps every fetch failure, including connection-refused, in\n * `HttpRequestError` unless it is already a `TimeoutError`), plus the error\n * `waitForTransactionReceipt` itself throws when it gives up polling for a\n * receipt — precisely the \"broadcast succeeded, confirmation didn't\" case\n * this classification exists to catch. Substring matching\n * is kept only as a fallback for shapes not covered by a typed viem class\n * (e.g. a raw Node/undici error surfacing through some other path) — pinning\n * behaviour to message text is brittle across viem/undici upgrades, so the\n * instanceof checks should be preferred and grown over time as more real\n * failure shapes are seen.\n */\nfunction isProviderUnavailableError(err: unknown): boolean {\n if (\n err instanceof HttpRequestError ||\n err instanceof TimeoutError ||\n err instanceof WaitForTransactionReceiptTimeoutError\n ) {\n return true;\n }\n const message = describeError(err).toLowerCase();\n return (\n message.includes('econnrefused') ||\n message.includes('fetch failed') ||\n message.includes('enotfound') ||\n message.includes('etimedout') ||\n message.includes('timed out') ||\n message.includes('network error')\n );\n}\n\n/** Never includes secrets: only error class name + message, never raw payloads or keys. */\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return `${err.name}: ${err.message}`;\n return String(err);\n}\n\n/**\n * True only when the RPC answers Anvil's own `anvil_nodeInfo` method — a\n * real network (including real Base Sepolia, which shares chain id 84532\n * with this project's local chain by design) returns a JSON-RPC \"method\n * not found\" error instead. Never throws.\n */\nasync function probeIsAnvilNode(\n client: ReturnType<typeof createLocalPublicClient>,\n): Promise<boolean> {\n // Anvil-only method: not part of viem's typed PublicRpcSchema, hence the cast.\n const request = client.request as unknown as (args: {\n method: string;\n params: unknown[];\n }) => Promise<unknown>;\n try {\n await request({ method: 'anvil_nodeInfo', params: [] });\n return true;\n } catch {\n return false;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/payments/x402/chain.ts","../src/payments/x402/client.ts","../src/payments/x402/amount.ts","../src/payments/x402/facilitator.ts","../src/payments/x402/payload.ts","../src/payments/x402/replay-key.ts","../src/payments/x402/provider.ts"],"names":["privateKeyToAccount","X402_VERSION","getAddress"],"mappings":";;;;;;;;;;;AAoDO,IAAM,cAAA,GAAiB,KAAA;AAcvB,SAAS,iBAAiB,OAAA,EAAqC;AACpE,EAAA,MAAM,KAAA,GAAQ,gBAAA,CAAiB,IAAA,CAAK,OAAO,CAAA;AAC3C,EAAA,IAAI,CAAC,KAAA,GAAQ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AO,OAAA;AAIvB,EAAA,IAAI;AACF,IAAA,MAAM,QAAQ,EAAE,MAAA,EAAQ,kBAAkB,MAAA,EAAQ,IAAI,CAAA;AACtD,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"x402.js","sourcesContent":["/**\n * Local deterministic chain wiring.\n *\n * The x402 SDK resolves RPC endpoints for public networks from its own\n * tables — exactly what we must never touch: the tests must stay\n * deterministic. Instead we build plain viem clients pointed at\n * `options.rpcUrl`, using a custom `Chain` object whose id is 84532, the\n * chain id carried by the CAIP-2 network identifier the gateway advertises\n * (`eip155:84532`).\n *\n * The `Local` prefix on everything here describes the *chain* these clients\n * are built for, not a test-only status: `provider.ts` calls\n * `createLocalPublicClient` and `createLocalFacilitatorClient` on the real\n * settlement path, for every payment. This is not demo scaffolding that a\n * production build could drop — v0.1 settles against the deterministic local\n * chain, so this file *is* the settlement transport. Supporting a public\n * network means making `buildLocalChain`'s hardcoded `LOCAL_CHAIN_ID` a\n * parameter, not bypassing this module.\n *\n * `dev-key-guard.ts` is the boundary that keeps that arrangement safe: it\n * refuses at provider construction if a dev key or dev `payTo` is pointed at\n * anything other than a loopback/private RPC.\n */\nimport {\n type Account,\n type Chain,\n type Client,\n createPublicClient,\n createWalletClient,\n http,\n type PublicActions,\n type PublicClient,\n publicActions,\n type Transport,\n type WalletActions,\n} from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\n\n/** A wallet client that can also read chain state — matches x402's `SignerWallet`. */\nexport type LocalFacilitatorClient = Client<\n Transport,\n Chain,\n Account,\n undefined,\n PublicActions<Transport, Chain, Account> & WalletActions<Chain, Account>\n>;\n\n/**\n * Chain id of the local deterministic dev chain. Shared with the public Base\n * Sepolia testnet, which is why nothing may infer \"this is a public network\"\n * from the id alone — `provider.ts` probes for a real Anvil node instead.\n */\nexport const LOCAL_CHAIN_ID = 84532;\n\n/** CAIP-2 identifier the local dev chain is advertised under. */\nexport const LOCAL_NETWORK = `eip155:${LOCAL_CHAIN_ID}`;\n\n/**\n * Chain id carried by a CAIP-2 `eip155` network identifier.\n *\n * x402 v2 identifies networks as CAIP-2 strings rather than the v1 name table,\n * so the chain id a signature is bound to is read straight off the wire value\n * instead of looked up. Returns `undefined` for anything that is not an\n * `eip155` identifier — a caller must never fall back to a default chain id,\n * because the chain id is part of the EIP-712 domain a buyer signed.\n */\nexport function chainIdFromCaip2(network: string): number | undefined {\n const match = /^eip155:(\\d+)$/.exec(network);\n if (!match?.[1]) return undefined;\n const chainId = Number(match[1]);\n return Number.isSafeInteger(chainId) && chainId > 0 ? chainId : undefined;\n}\n\nexport function buildLocalChain(rpcUrl: string): Chain {\n return {\n id: LOCAL_CHAIN_ID,\n name: 'agent-commerce-local',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n rpcUrls: {\n default: { http: [rpcUrl] },\n },\n } satisfies Chain;\n}\n\n/**\n * A viem `PublicClient` for the local chain — read-only, no signing capability.\n *\n * `timeoutMs`, when given, is passed straight to viem's `http()` transport,\n * which ties it to a real `AbortController` around the underlying `fetch`\n * (see viem's `utils/promise/withTimeout.js` — `signal: true`). That is a\n * genuine cancellation, unlike a bare `Promise.race` against a timer, which\n * only stops *waiting* for the request while the request itself keeps\n * running server-side. Omit it to keep viem's own default (10s).\n */\nexport function createLocalPublicClient(rpcUrl: string, timeoutMs?: number): PublicClient {\n return createPublicClient({\n chain: buildLocalChain(rpcUrl),\n transport: http(rpcUrl, timeoutMs !== undefined ? { timeout: timeoutMs } : undefined),\n });\n}\n\n/**\n * A viem `WalletClient` extended with public actions, for the local\n * facilitator signer only. x402's `settle()` calls `writeContract`,\n * `waitForTransactionReceipt` and `getCode` on this client — i.e. it needs\n * both `WalletActions` and `PublicActions`, matching x402's `SignerWallet`\n * type.\n *\n * LOCAL DEVELOPMENT ONLY — the private key behind this client must always be\n * an Anvil well-known development key, never a merchant or buyer key, and\n * never a production key of any kind.\n */\nexport function createLocalFacilitatorClient(\n rpcUrl: string,\n signerPrivateKey: `0x${string}`,\n): LocalFacilitatorClient {\n const chain = buildLocalChain(rpcUrl);\n const account = privateKeyToAccount(signerPrivateKey);\n return createWalletClient({\n account,\n chain,\n transport: http(rpcUrl),\n }).extend(publicActions);\n}\n","/**\n * CLIENT-SIDE payment helper.\n *\n * This module is used by the demo buyer agent (`demo/agent`) and by the\n * payment E2E test suite to build and EIP-712-sign an x402 v2 `exact`/EVM\n * payment authorisation, entirely on the buyer's side.\n *\n * The gateway NEVER calls this module and NEVER holds a buyer private key.\n * `buyerPrivateKey` here is always an Anvil well-known\n * development key (LOCAL DEVELOPMENT ONLY — DO NOT FUND) supplied by whoever\n * is driving the demo/test, not something the provider or gateway manages.\n *\n * It signs the EIP-712 authorisation directly rather than going through the\n * SDK's `x402Client`, for one reason: `overrides`. The negative payment tests\n * need authorisations that are deliberately wrong — wrong recipient, short\n * amount, reused nonce, expired window — and a conforming client will not\n * produce those. Interop with a real SDK client is proved separately, by a\n * test that pays the gateway using `x402Client` itself.\n */\n\nimport { PaymentRequirementsV2Schema } from '@x402/core/schemas';\nimport type { PaymentPayload, PaymentRequirements } from '@x402/core/types';\nimport { getAddress, toHex } from 'viem';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { chainIdFromCaip2 } from './chain.js';\n\nexport interface CreatePaymentProofOptions {\n /** Buyer's dev-only private key. LOCAL DEVELOPMENT ONLY — DO NOT FUND. */\n readonly buyerPrivateKey: `0x${string}`;\n readonly rpcUrl: string;\n /** One entry from PaymentRequiredEnvelope.payment.accepts, verbatim. */\n readonly accepts: Readonly<Record<string, unknown>>;\n /** Overrides used only by negative tests (wrong amount/recipient/nonce…). */\n readonly overrides?: {\n readonly value?: string;\n readonly payTo?: string;\n readonly nonce?: `0x${string}`;\n readonly validBefore?: number;\n readonly validAfter?: number;\n };\n}\n\nconst X402_VERSION = 2;\n\nconst 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/** Returns the base64 `PAYMENT-SIGNATURE` value to send back to the gateway. */\nexport async function createPaymentProof(options: CreatePaymentProofOptions): Promise<string> {\n const requirements = PaymentRequirementsV2Schema.parse(options.accepts);\n if (\n !requirements.extra ||\n typeof requirements.extra['name'] !== 'string' ||\n typeof requirements.extra['version'] !== 'string'\n ) {\n throw new Error(\n 'createPaymentProof: payment requirement is missing extra.name/extra.version — cannot build the EIP-712 domain',\n );\n }\n\n const chainId = chainIdFromCaip2(requirements.network);\n if (chainId === undefined) {\n throw new Error(\n `createPaymentProof: network \"${requirements.network}\" is not a CAIP-2 eip155 identifier — cannot determine the chain id to sign against`,\n );\n }\n\n const account = privateKeyToAccount(options.buyerPrivateKey);\n // `rpcUrl` is part of the frozen `CreatePaymentProofOptions` shape for\n // interface parity with other providers, but the `exact`/EVM scheme signs\n // fully offline: the chain id comes from the CAIP-2 network identifier\n // (matching what the facilitator's verify()/settle() compute), and the\n // nonce is a fresh random value, not one read from chain state.\n void options.rpcUrl;\n\n const nonce = options.overrides?.nonce ?? randomNonce();\n const nowSeconds = Math.floor(Date.now() / 1000);\n // 0, matching the SDK's own v2 client: `validAfter` exists to delay an\n // authorisation, and nothing here wants one delayed. A backdated value would\n // only paper over clock skew that `validBefore` has to tolerate anyway.\n const validAfter = options.overrides?.validAfter ?? 0;\n const validBefore = options.overrides?.validBefore ?? nowSeconds + requirements.maxTimeoutSeconds;\n const to = getAddress((options.overrides?.payTo ?? requirements.payTo) as `0x${string}`);\n const value = BigInt(options.overrides?.value ?? requirements.amount);\n\n const signature = await account.signTypedData({\n domain: {\n name: requirements.extra['name'],\n version: requirements.extra['version'],\n chainId,\n verifyingContract: getAddress(requirements.asset as `0x${string}`),\n },\n types: TRANSFER_WITH_AUTHORIZATION_TYPES,\n primaryType: 'TransferWithAuthorization',\n message: {\n from: account.address,\n to,\n value,\n validAfter: BigInt(validAfter),\n validBefore: BigInt(validBefore),\n nonce,\n },\n });\n\n // v2 carries the selected requirement back to the server as `accepted`\n // rather than repeating scheme/network at the top level. The server treats\n // that echo as untrusted and verifies against its own copy; it is on the\n // wire so a stateless facilitator knows which offer was taken.\n const payload: PaymentPayload = {\n x402Version: X402_VERSION,\n accepted: requirements as PaymentRequirements,\n payload: {\n signature,\n authorization: {\n from: account.address,\n to,\n value: value.toString(),\n validAfter: validAfter.toString(),\n validBefore: validBefore.toString(),\n nonce,\n },\n },\n };\n\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');\n}\n\nfunction randomNonce(): `0x${string}` {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return toHex(bytes);\n}\n","/**\n * Deterministic decimal <-> base-unit conversion.\n *\n * `DecimalAmount` (see src/core) is a decimal string in\n * *display* units (\"0.01\" USDC). x402 / EIP-3009 need base units (integer\n * string, e.g. \"10000\" for 0.01 USDC at 6 decimals). This conversion must\n * never go through a JS `number` — floating point cannot represent most\n * decimal fractions exactly, and a silently-rounded payment amount is a\n * security bug in a payment provider.\n *\n * viem's own `parseUnits` rounds silently when given more fractional digits\n * than `decimals` supports; we need a hard error instead (a merchant asking\n * for \"0.0000001\" against a 6-decimal asset is a configuration bug, not a\n * roundable amount), so this module implements its own strict parser.\n */\nimport { CommerceError } from '../../core/index.js';\n\nconst DECIMAL_STRING_PATTERN = /^\\d+(?:\\.\\d+)?$/;\n\n/**\n * Parses a canonical decimal display amount (e.g. \"0.01\") into base units\n * for an asset with the given number of decimals, without floating point.\n *\n * Throws `CommerceError('PAYMENT_INVALID')` if the string is not a plain\n * non-negative decimal, or if it carries more fractional digits than the\n * asset supports.\n */\nexport function parseCanonicalAmount(amount: string, decimals: number): bigint {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new CommerceError('INTERNAL_ERROR', `Invalid asset decimals: ${decimals}`);\n }\n if (!DECIMAL_STRING_PATTERN.test(amount)) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" is not a valid non-negative decimal string`,\n {\n details: { amount },\n },\n );\n }\n\n const [integerPart = '0', fractionPart = ''] = amount.split('.');\n\n if (fractionPart.length > decimals) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n `Amount \"${amount}\" has more precision than the asset supports (${decimals} decimals)`,\n { details: { amount, assetDecimals: decimals } },\n );\n }\n\n const paddedFraction = fractionPart.padEnd(decimals, '0');\n const combined = `${integerPart}${paddedFraction}`;\n // Strip leading zeros so BigInt doesn't choke on e.g. \"007\" — BigInt() is\n // fine with leading zeros in decimal strings, but normalise defensively.\n return BigInt(combined);\n}\n\n/**\n * Formats base units back into a canonical decimal display string.\n *\n * Exact (no rounding is possible going from integer base units to a wider\n * decimal representation), so this is safe to implement directly.\n */\nexport function formatCanonicalAmount(baseUnits: bigint, decimals: number): string {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new CommerceError('INTERNAL_ERROR', `Invalid asset decimals: ${decimals}`);\n }\n const negative = baseUnits < 0n;\n const abs = negative ? -baseUnits : baseUnits;\n const digits = abs.toString().padStart(decimals + 1, '0');\n const integerPart = digits.slice(0, digits.length - decimals) || '0';\n const fractionPart = digits.slice(digits.length - decimals).replace(/0+$/, '');\n const sign = negative ? '-' : '';\n return fractionPart.length > 0\n ? `${sign}${integerPart}.${fractionPart}`\n : `${sign}${integerPart}`;\n}\n","/**\n * The facilitator seam.\n *\n * A facilitator is whatever verifies an authorisation and broadcasts the\n * transfer. This gateway supports two, behind one interface:\n *\n * local the SDK's in-process `x402Facilitator` signing against a dev node\n * remote an HTTP facilitator, with or without a credential\n *\n * Both are the SDK's own `FacilitatorClient` contract underneath, so neither\n * is a bespoke reimplementation of the protocol — the local one is the same\n * code a hosted facilitator runs, pointed at the local chain.\n *\n * A *session* is opened per verify/settle call rather than reused, because\n * `transportFailed()` has to be scoped to one request: two concurrent\n * payments must not see each other's transport failures. The cost is an\n * object literal against an RPC or HTTP round-trip.\n */\nimport { x402Facilitator } from '@x402/core/facilitator';\nimport { FacilitatorResponseError, HTTPFacilitatorClient } from '@x402/core/http';\nimport type {\n Network,\n PaymentPayload,\n PaymentRequirements,\n SettleResponse,\n VerifyResponse,\n} from '@x402/core/types';\nimport { toFacilitatorEvmSigner } from '@x402/evm';\nimport { registerExactEvmScheme } from '@x402/evm/exact/facilitator';\nimport type { LocalFacilitatorClient } from './chain.js';\nimport type { FacilitatorAuth } from './guardrails.js';\n\n/** One verify or one settle, with its own transport-failure flag. */\nexport interface FacilitatorSession {\n verify(payload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;\n settle(payload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;\n /**\n * True when the call failed to reach the facilitator (or the chain behind\n * it) rather than producing a verdict.\n *\n * The SDK's `exact`/EVM scheme catches its own RPC errors and reports them\n * as an ordinary verification failure — an unreachable node comes back as\n * `invalid_exact_evm_signature`. Fail-closed still holds, but the buyer is\n * told their signature is bad and the attempt is recorded as their fault,\n * when nothing about their payment was ever checked. This flag is how the\n * provider tells \"we looked and it was wrong\" apart from \"we could not\n * look\".\n */\n transportFailed(): boolean;\n}\n\nexport interface SupportedKind {\n readonly x402Version: number;\n readonly scheme: string;\n readonly network: string;\n}\n\nexport interface FacilitatorBinding {\n readonly kind: 'local' | 'remote';\n /** Human-readable, never a credential. */\n readonly describe: string;\n open(): FacilitatorSession;\n /** What the facilitator says it can settle. Used by health(), not by the payment path. */\n supported(): Promise<readonly SupportedKind[]>;\n}\n\n/** Bounds every receipt wait the in-process facilitator performs. */\nexport const SETTLEMENT_CONFIRMATION_TIMEOUT_MS = 60_000;\n\n/**\n * An in-process `x402Facilitator` with the `exact`/EVM scheme registered\n * against exactly one network.\n *\n * One network, not the `eip155:*` wildcard the SDK would otherwise derive: a\n * payload naming some other chain must find no facilitator at all rather than\n * reaching a scheme that would then have to reject it.\n */\nexport function createLocalFacilitatorBinding(\n client: LocalFacilitatorClient,\n network: string,\n isTransportError: (err: unknown) => boolean,\n): FacilitatorBinding {\n const build = (): { facilitator: x402Facilitator; failed: () => boolean } => {\n let failed = false;\n const watch = <T>(promise: Promise<T>): Promise<T> =>\n promise.catch((err: unknown) => {\n if (isTransportError(err)) failed = true;\n throw err;\n });\n\n // Exactly the `FacilitatorEvmSigner` surface, so the wrapper covers every\n // call the SDK can make. `toFacilitatorEvmSigner` wants a flat `address`,\n // which viem carries on `client.account` instead.\n const signer = {\n address: client.account.address,\n readContract: (args: Parameters<LocalFacilitatorClient['readContract']>[0]) =>\n watch(client.readContract(args)),\n verifyTypedData: (args: Parameters<LocalFacilitatorClient['verifyTypedData']>[0]) =>\n watch(client.verifyTypedData(args)),\n writeContract: (args: Parameters<LocalFacilitatorClient['writeContract']>[0]) =>\n watch(client.writeContract(args)),\n sendTransaction: (args: Parameters<LocalFacilitatorClient['sendTransaction']>[0]) =>\n watch(client.sendTransaction(args)),\n waitForTransactionReceipt: (\n args: Parameters<LocalFacilitatorClient['waitForTransactionReceipt']>[0],\n ) => watch(client.waitForTransactionReceipt(args)),\n getCode: (args: Parameters<LocalFacilitatorClient['getCode']>[0]) =>\n watch(client.getCode(args)),\n } as unknown as Parameters<typeof toFacilitatorEvmSigner>[0];\n\n // `confirmationTimeoutMs` is what turns a lost receipt wait into\n // `settlement_pending` + the broadcast hash instead of a discarded broadcast.\n const facilitator = registerExactEvmScheme(new x402Facilitator(), {\n signer: toFacilitatorEvmSigner(signer, {\n confirmationTimeoutMs: SETTLEMENT_CONFIRMATION_TIMEOUT_MS,\n }),\n networks: network as Network,\n });\n\n return { facilitator, failed: () => failed };\n };\n\n return {\n kind: 'local',\n describe: 'local (in-process)',\n open(): FacilitatorSession {\n const { facilitator, failed } = build();\n return {\n verify: (payload, requirements) => facilitator.verify(payload, requirements),\n settle: (payload, requirements) => facilitator.settle(payload, requirements),\n transportFailed: failed,\n };\n },\n async supported(): Promise<readonly SupportedKind[]> {\n return build().facilitator.getSupported().kinds;\n },\n };\n}\n\nexport interface RemoteFacilitatorOptions {\n readonly url: string;\n readonly auth: FacilitatorAuth;\n readonly timeoutMs?: number;\n}\n\n/**\n * An HTTP facilitator.\n *\n * Auth headers are produced per request by the SDK client and never logged,\n * never echoed into `/.well-known`, and never included in `describe`.\n */\nexport function createRemoteFacilitatorBinding(\n options: RemoteFacilitatorOptions,\n isTransportError: (err: unknown) => boolean,\n): FacilitatorBinding {\n const auth = options.auth;\n const createAuthHeaders =\n auth.type === 'bearer'\n ? async (): Promise<Record<string, Record<string, string>>> => {\n // The SDK requires a path-keyed object; a flat headers object throws\n // rather than silently dropping auth on every request.\n const headers = { Authorization: `Bearer ${auth.token}` };\n return { verify: headers, settle: headers, supported: headers };\n }\n : undefined;\n\n const client = new HTTPFacilitatorClient({\n url: options.url,\n timeoutMs: options.timeoutMs ?? SETTLEMENT_CONFIRMATION_TIMEOUT_MS,\n ...(createAuthHeaders ? { createAuthHeaders } : {}),\n });\n\n return {\n kind: 'remote',\n describe: `remote ${new URL(options.url).origin} (auth=${auth.type})`,\n open(): FacilitatorSession {\n let failed = false;\n const watch = async <T>(call: () => Promise<T>): Promise<T> => {\n try {\n return await call();\n } catch (err) {\n // A facilitator that timed out or answered with something\n // unparseable produced no verdict. Treating either as a payment\n // failure would blame the buyer for the facilitator being down —\n // and for settle(), a timeout is explicitly indeterminate: the\n // transfer may have gone through after we stopped waiting.\n if (err instanceof FacilitatorResponseError || isTransportError(err)) failed = true;\n throw err;\n }\n };\n return {\n verify: (payload, requirements) => watch(() => client.verify(payload, requirements)),\n settle: (payload, requirements) => watch(() => client.settle(payload, requirements)),\n transportFailed: () => failed,\n };\n },\n async supported(): Promise<readonly SupportedKind[]> {\n const response = await client.getSupported();\n return response.kinds as readonly SupportedKind[];\n },\n };\n}\n","/**\n * Decoding and validation for the base64 `PAYMENT-SIGNATURE` submission.\n *\n * A malformed payload (not base64, valid base64 but not JSON, valid JSON but\n * the wrong shape) must yield a `rejected` verification result, never a\n * thrown/crashed request — this module returns `undefined` on any failure so\n * callers can turn that into a typed rejection. That is why it parses the\n * schema itself rather than calling the SDK's `decodePaymentSignatureHeader`,\n * which throws.\n */\nimport { PaymentPayloadV2Schema } from '@x402/core/schemas';\nimport type { PaymentPayload } from '@x402/core/types';\nimport { type ExactEIP3009Payload, isEIP3009Payload } from '@x402/evm';\n\nexport function decodePaymentSubmission(payloadBase64: string): PaymentPayload | undefined {\n let json: unknown;\n try {\n const decoded = Buffer.from(payloadBase64, 'base64').toString('utf8');\n json = JSON.parse(decoded);\n } catch {\n return undefined;\n }\n\n const result = PaymentPayloadV2Schema.safeParse(json);\n return result.success ? (result.data as PaymentPayload) : undefined;\n}\n\n/**\n * Narrows a decoded payload to the EIP-3009 `exact`/EVM shape this provider\n * settles.\n *\n * x402 v2's `exact` scheme on EVM has two asset-transfer methods — EIP-3009\n * `transferWithAuthorization` and Permit2. Only the first is supported here,\n * and the challenge says so (`extra.assetTransferMethod`), so a Permit2\n * payload arriving anyway is rejected rather than handed to the SDK: the\n * Permit2 proxy is not deployed on the local chain and a failure there would\n * surface as an opaque settlement revert instead of a clear rejection.\n */\nexport function isExactEvmPayload(\n payload: PaymentPayload,\n): payload is PaymentPayload & { payload: ExactEIP3009Payload } {\n return (\n payload.accepted.scheme === 'exact' &&\n typeof payload.payload === 'object' &&\n payload.payload !== null &&\n isEIP3009Payload(payload.payload as ExactEIP3009Payload) &&\n typeof (payload.payload as ExactEIP3009Payload).signature === 'string'\n );\n}\n","/**\n * Replay-key derivation.\n *\n *Per docs/contracts.md, `PaymentResult.replayKey` MUST be\n * derived only from the payment authorisation (chain id, asset, payer,\n * nonce) — never from the request id — so that the same authorisation\n * replayed against a *different* request still collides in the gateway's\n * receipt-store reservation.\n */\nimport { encodeAbiParameters, keccak256 } from 'viem';\n\nexport interface ReplayKeyInput {\n readonly chainId: number;\n readonly asset: `0x${string}`;\n readonly from: `0x${string}`;\n readonly nonce: `0x${string}`;\n}\n\nexport function computeReplayKey(input: ReplayKeyInput): string {\n const encoded = encodeAbiParameters(\n [{ type: 'uint256' }, { type: 'address' }, { type: 'address' }, { type: 'bytes32' }],\n [BigInt(input.chainId), input.asset, input.from, input.nonce],\n );\n return keccak256(encoded);\n}\n","/**\n * x402 payment provider — protocol version 2, `exact` scheme, EVM,\n * EIP-3009 `transferWithAuthorization`.\n *\n * Implements the frozen `PaymentProvider` interface (src/core/domain/payment.ts).\n * `verify()` never moves funds; only `settle()` does, and only after a\n * successful `verify()` (enforced by the gateway's execution pipeline, not by\n * this file, but this file never calls settle-like RPCs from verify()).\n *\n * Verification and settlement run through the SDK's own `x402Facilitator`\n * with the `exact`/EVM scheme registered against a single CAIP-2 network. The\n * facilitator is in-process — it is the same code a hosted facilitator runs,\n * pointed at the local dev chain — so there is no network hop and no third\n * party in the settlement path.\n *\n * The SDK behaviour relied on here is verified, not assumed: see the notes\n * beside each call site below.\n */\n\nimport type {\n Network,\n PaymentRequired,\n PaymentRequirements,\n SettleResponse,\n VerifyResponse,\n} from '@x402/core/types';\nimport {\n ContractFunctionExecutionError,\n ContractFunctionRevertedError,\n getAddress,\n HttpRequestError,\n isAddress,\n TimeoutError,\n WaitForTransactionReceiptTimeoutError,\n} from 'viem';\nimport {\n type AdapterDescriptor,\n type AdapterHealth,\n type Clock,\n CommerceError,\n type IdGenerator,\n type Logger,\n NOOP_LOGGER,\n type PaymentContext,\n type PaymentProvider,\n type PaymentRequirement,\n type PaymentResult,\n type PaymentSettlementContext,\n type PaymentVerificationContext,\n systemClock,\n} from '../../core/index.js';\nimport { PACKAGE_VERSION } from '../../version.js';\nimport { formatCanonicalAmount, parseCanonicalAmount } from './amount.js';\nimport {\n chainIdFromCaip2,\n createLocalFacilitatorClient,\n createLocalPublicClient,\n type LocalFacilitatorClient,\n} from './chain.js';\nimport { assertDevKeyIsLocalOnly, assertPayToIsNotDevAddress } from './dev-key-guard.js';\nimport {\n createLocalFacilitatorBinding,\n createRemoteFacilitatorBinding,\n type FacilitatorBinding,\n} from './facilitator.js';\nimport { resolveX402Deployment, type X402FacilitatorConfig } from './guardrails.js';\nimport { describeDeploymentMode } from './networks.js';\nimport { decodePaymentSubmission, isExactEvmPayload } from './payload.js';\nimport { computeReplayKey } from './replay-key.js';\n\nconst X402_VERSION = 2;\nconst X402_PROTOCOL_VERSION = String(X402_VERSION);\nconst DEFAULT_MAX_TIMEOUT_SECONDS = 60;\nconst DEFAULT_MIME_TYPE = 'application/json';\nconst HEALTH_TIMEOUT_MS = 4_000;\n/** `SettleResponse.errorReason` the SDK uses for \"broadcast, not confirmed\". */\nconst SETTLEMENT_PENDING_REASON = 'settlement_pending';\n\nexport interface X402ProviderOptions {\n /**\n * CAIP-2 network identifier, e.g. `eip155:84532`. The chain id it carries is\n * part of the EIP-712 domain the buyer signs, so it is read from this value\n * rather than defaulted.\n */\n readonly network: string;\n /** RPC endpoint. Local chain: http://127.0.0.1:8545 */\n readonly rpcUrl: string;\n /** ERC-20 (EIP-3009) asset address used for settlement. */\n readonly asset: `0x${string}`;\n /** EIP-712 domain name of the asset, e.g. 'MockUSDC'. */\n readonly assetName: string;\n /** EIP-712 domain version of the asset, e.g. '2'. */\n readonly assetVersion: string;\n readonly assetDecimals: number;\n /** Merchant-controlled settlement destination. Never a gateway-owned wallet. */\n readonly payTo: `0x${string}`;\n readonly maxTimeoutSeconds?: number;\n /**\n * Which facilitator verifies and broadcasts.\n *\n * `local` runs the facilitator in this process against the dev chain, and\n * its `signerPrivateKey` must be an Anvil well-known key — LOCAL DEVELOPMENT\n * ONLY — DO NOT FUND. `remote` calls an HTTP facilitator, and this gateway\n * then holds no signing key at all.\n */\n readonly facilitator: X402FacilitatorConfig;\n /**\n * Required to be `true` before anything settles on a mainnet. Never a\n * default — see `guardrails.ts`.\n */\n readonly allowMainnet?: boolean;\n readonly logger?: Logger;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n}\n\nconst DEFAULT_IDS: IdGenerator = {\n next: (prefix?: string) => `${prefix ? `${prefix}_` : ''}${crypto.randomUUID()}`,\n};\n\nexport function createX402PaymentProvider(options: X402ProviderOptions): PaymentProvider {\n if (!isAddress(options.asset)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"asset\" is not a valid EVM address: ${options.asset}`,\n );\n }\n if (!isAddress(options.payTo)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"payTo\" is not a valid EVM address: ${options.payTo}`,\n );\n }\n // Applies regardless of facilitator.mode — which account signs settlement\n // has no bearing on whether the destination address's private key is\n // public knowledge. `resolveX402Deployment` below covers the other half of\n // the same question: a dev payTo on any non-local *deployment*, where the\n // RPC host says nothing about where the money lands.\n assertPayToIsNotDevAddress(options.rpcUrl, options.payTo);\n if (!Number.isInteger(options.assetDecimals) || options.assetDecimals < 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `x402 provider: \"assetDecimals\" must be a non-negative integer`,\n );\n }\n // The chain id is not a display detail: it is signed into the buyer's\n // EIP-712 domain, so a network identifier we cannot resolve one from is a\n // startup failure, never a request-time default. `resolveX402Deployment`\n // also decides what this deployment *is* — local, testnet or mainnet — and\n // refuses every combination that could move real money by accident.\n const { profile, mode } = resolveX402Deployment({\n network: options.network,\n payTo: options.payTo,\n asset: options.asset,\n facilitator: options.facilitator,\n ...(options.allowMainnet !== undefined ? { allowMainnet: options.allowMainnet } : {}),\n });\n const network = options.network as Network;\n // Constructed once, here, rather than inside settle(): assertDevKeyIsLocalOnly\n // above already proves the key is well-formed, so privateKeyToAccount is not\n // expected to throw — but if it somehow does (or the key/RPC combination is\n // otherwise unusable), that is a *configuration* problem, and a bad key\n // should fail the provider at startup, not on the first paying customer's\n // request, after their replayKey is already reserved. This mirrors the other\n // CONFIG_INVALID checks above, which are all one-time, construction-time\n // validation rather than per-request checks.\n let binding: FacilitatorBinding;\n if (options.facilitator.mode === 'local') {\n assertDevKeyIsLocalOnly(options.rpcUrl, options.facilitator.signerPrivateKey);\n let client: LocalFacilitatorClient;\n try {\n client = createLocalFacilitatorClient(\n options.rpcUrl,\n options.facilitator.signerPrivateKey as `0x${string}`,\n );\n } catch (cause) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n 'x402 provider: could not construct a local facilitator signer from ' +\n 'facilitator.signerPrivateKey — it must be a valid 32-byte hex private key',\n { cause },\n );\n }\n binding = createLocalFacilitatorBinding(client, network, isProviderUnavailableError);\n } else {\n binding = createRemoteFacilitatorBinding(\n { url: options.facilitator.url, auth: options.facilitator.auth },\n isProviderUnavailableError,\n );\n }\n\n // health()'s own read-only client, with a real transport-level timeout (see\n // createLocalPublicClient's doc comment). Verification and settlement read\n // the chain through the facilitator signer instead, so this is the only\n // public client the provider builds.\n const healthPublicClient = createLocalPublicClient(options.rpcUrl, HEALTH_TIMEOUT_MS);\n\n const clock = options.clock ?? systemClock;\n const ids = options.ids ?? DEFAULT_IDS;\n const logger = options.logger ?? NOOP_LOGGER;\n const maxTimeoutSeconds = options.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;\n\n const descriptor: AdapterDescriptor = {\n name: 'x402',\n kind: 'payment',\n implementationVersion: PACKAGE_VERSION,\n supportedSpec: `x402/v${X402_VERSION} scheme=exact family=eip155`,\n capabilities: [\n 'exact-evm',\n `${binding.kind}-facilitator`,\n 'eip-3009',\n 'caip-2',\n `mode=${mode}`,\n ],\n status: 'stable',\n unsupported: [\n 'svm',\n 'permit2',\n 'upto scheme',\n 'per-request signed facilitator credentials (e.g. CDP JWT)',\n ],\n };\n\n async function createRequirement(context: PaymentContext): Promise<PaymentRequirement> {\n const amount = parseCanonicalAmount(context.amount, options.assetDecimals).toString();\n\n const requirements: PaymentRequirements = {\n scheme: 'exact',\n network,\n asset: options.asset,\n amount,\n payTo: options.payTo,\n maxTimeoutSeconds,\n // `name`/`version` are what let a buyer and the facilitator build the\n // same EIP-712 domain without an on-chain `version()` call, so\n // verification stays deterministic against a token that has none.\n //\n // `assetTransferMethod` is stated rather than left to default: x402 v2's\n // `exact`/EVM scheme also has a Permit2 path, and a client that picked it\n // would produce a payload this provider cannot settle. Declaring the one\n // supported method turns that into a client-side non-choice instead of a\n // server-side rejection.\n extra: {\n name: options.assetName,\n version: options.assetVersion,\n assetTransferMethod: 'eip3009',\n },\n };\n\n // The v2 challenge document, verbatim on the wire: the HTTP adapter\n // base64-encodes this into `PAYMENT-REQUIRED`, and MCP passes it through\n // in the payment-required envelope. Built once, here, so both surfaces\n // describe the same challenge rather than each assembling their own.\n //\n // `resource.url` is descriptive metadata: nothing in the EIP-3009\n // authorisation (`from`/`to`/`value`/`validAfter`/`validBefore`/`nonce`)\n // covers it, nothing verifies against it, and the replay key is keyed on\n // the authorisation instead. It still carries `network` and `payTo` —\n // both already public in this same challenge — because the\n // `agent-commerce` authority is not reserved to us across the wider x402\n // ecosystem, so the pair is what keeps it unambiguous.\n const envelope: PaymentRequired = {\n x402Version: X402_VERSION,\n resource: {\n url: `resource://agent-commerce/${encodeURIComponent(options.network)}/${options.payTo}/resources/${encodeURIComponent(context.resource.id)}`,\n description: context.resource.description ?? context.resource.name,\n mimeType: DEFAULT_MIME_TYPE,\n },\n accepts: [requirements],\n };\n\n const expiresAt = new Date(clock.now().getTime() + maxTimeoutSeconds * 1000).toISOString();\n\n return {\n id: ids.next('payreq'),\n requestId: context.requestId,\n resourceId: context.resource.id,\n provider: 'x402',\n amount: context.amount,\n currency: context.currency,\n destination: options.payTo,\n network: options.network,\n asset: options.asset,\n expiresAt,\n challenge: {\n provider: 'x402',\n version: X402_PROTOCOL_VERSION,\n accepts: [requirements as unknown as Record<string, unknown>],\n envelope: envelope as unknown as Record<string, unknown>,\n },\n };\n }\n\n /**\n * Verifies a payment submission against a payment requirement.\n *\n * Every check below runs against *our* requirement — the one this provider\n * built and the pipeline held onto — never against `payload.accepted`, the\n * copy of the requirements the client echoes back. That echo is attacker\n * data; the SDK's scheme facilitator likewise takes the requirements as an\n * explicit argument rather than reading them off the payload.\n *\n * Deliberately accepts overpayment: only `authorizedValue < required` is\n * rejected (`wrong_amount`), never `authorizedValue > required`. This\n * matches x402's own semantics — the requirement's `amount` names a floor,\n * not an exact amount — and the settled `PaymentResult.amount` always\n * records the actual authorised value, so bookkeeping stays truthful to what\n * really moved rather than silently topping up or rejecting a generous\n * buyer.\n */\n async function verify(context: PaymentVerificationContext): Promise<PaymentResult> {\n const { requirement, submission } = context;\n\n const rejected = (reason: string): PaymentResult => ({\n status: 'rejected',\n provider: 'x402',\n amount: requirement.amount,\n currency: requirement.currency,\n ...(requirement.network !== undefined ? { network: requirement.network } : {}),\n ...(requirement.asset !== undefined ? { asset: requirement.asset } : {}),\n rejectionReason: reason,\n });\n\n if (requirement.provider !== 'x402' || requirement.challenge.provider !== 'x402') {\n return rejected('wrong_provider');\n }\n\n const requirements = requirement.challenge.accepts[0] as PaymentRequirements | undefined;\n if (!requirements) {\n return rejected('missing_payment_requirements');\n }\n\n // Defence in depth, not the real expiry: the pipeline calls\n // createRequirement() fresh on every request, so by the time verify()\n // runs this requirement is only ever seconds old — this check will\n // essentially never fire in the current flow. The actual expiry\n // enforcement is EIP-3009's validBefore, checked inside the SDK's scheme\n // facilitator. Kept because it is cheap and correct, not because it is\n // load-bearing.\n if (\n requirement.expiresAt !== undefined &&\n Date.parse(requirement.expiresAt) < clock.now().getTime()\n ) {\n return rejected('requirement_expired');\n }\n\n // Defensive invariant: the requirement we're verifying against must still\n // describe *this* provider's configured asset. It always will in normal\n // operation (we generated it), but a corrupted/mismatched requirement\n // must never be allowed to authorise a transfer for a different asset.\n if (\n !isAddress(requirements.asset) ||\n getAddress(requirements.asset) !== getAddress(options.asset)\n ) {\n return rejected('wrong_asset');\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload) {\n return rejected('malformed_payment_payload');\n }\n if (payload.x402Version !== X402_VERSION) {\n return rejected('unsupported_x402_version');\n }\n if (!isExactEvmPayload(payload)) {\n return rejected('unsupported_scheme');\n }\n\n const { authorization } = payload.payload;\n\n if (!isAddress(authorization.from) || !isAddress(authorization.to)) {\n return rejected('malformed_payment_payload');\n }\n // The network the buyer signed for is `accepted.network` — it is what the\n // scheme derives the EIP-712 chain id from — so a mismatch here means the\n // signature is bound to a different chain than the one we settle on.\n if (payload.accepted.network !== options.network) {\n return rejected('wrong_network');\n }\n if (getAddress(authorization.to) !== getAddress(options.payTo)) {\n return rejected('wrong_recipient');\n }\n let authorizedValue: bigint;\n let required: bigint;\n try {\n authorizedValue = BigInt(authorization.value);\n required = BigInt(requirements.amount);\n } catch {\n return rejected('malformed_payment_payload');\n }\n if (authorizedValue < required) {\n return rejected('wrong_amount'); // overpayment is allowed through — see the doc comment above\n }\n\n const scope = binding.open();\n let sdkResult: VerifyResponse;\n try {\n sdkResult = await scope.verify(payload, requirements);\n } catch (err) {\n if (isProviderUnavailableError(err) || scope.transportFailed()) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${binding.kind} facilitator unreachable during verify()`,\n {\n cause: err,\n },\n );\n }\n logger.warn({ err: describeError(err) }, 'x402 verify(): unexpected SDK error');\n return rejected('unexpected_verify_error');\n }\n\n if (!sdkResult.isValid) {\n // An RPC that never answered is not a payment that failed a check.\n if (scope.transportFailed()) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${binding.kind} facilitator unreachable during verify()`,\n { details: { reportedReason: sdkResult.invalidReason ?? 'invalid_payment' } },\n );\n }\n return rejected(sdkResult.invalidReason ?? 'invalid_payment');\n }\n\n // Derived from the chain id the authorisation is actually bound to, never\n // from a provider-instance constant, so the key stays correct the moment\n // there is more than one chain id in play.\n const payloadChainId = chainIdFromCaip2(payload.accepted.network);\n if (payloadChainId === undefined) {\n return rejected('wrong_network');\n }\n const replayKey = computeReplayKey({\n chainId: payloadChainId,\n asset: getAddress(requirements.asset),\n from: getAddress(authorization.from),\n nonce: authorization.nonce,\n });\n\n return {\n status: 'verified',\n provider: 'x402',\n payer: getAddress(authorization.from),\n payee: getAddress(authorization.to),\n amount: formatCanonicalAmount(authorizedValue, options.assetDecimals),\n currency: requirement.currency,\n network: payload.accepted.network,\n asset: getAddress(requirements.asset),\n replayKey,\n };\n }\n\n async function settle(context: PaymentSettlementContext): Promise<PaymentResult> {\n const { requirement, submission, verification } = context;\n\n if (verification.status !== 'verified') {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() called without a successful verify()',\n );\n }\n\n const requirements = requirement.challenge.accepts[0] as PaymentRequirements | undefined;\n if (!requirements) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() found no payment requirements to settle against',\n );\n }\n\n const payload = decodePaymentSubmission(submission.payload);\n if (!payload || !isExactEvmPayload(payload)) {\n throw new CommerceError(\n 'PAYMENT_INVALID',\n 'x402 provider: settle() received an undecodable payment payload',\n );\n }\n\n const rejectedSettlement = (rejectionReason: string): PaymentResult => ({\n status: 'rejected',\n provider: 'x402',\n amount: verification.amount,\n currency: requirement.currency,\n ...(verification.network !== undefined ? { network: verification.network } : {}),\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n rejectionReason,\n });\n\n const scope = binding.open();\n let sdkResult: SettleResponse;\n try {\n sdkResult = await scope.settle(payload, requirements);\n } catch (err) {\n if (isProviderUnavailableError(err) || scope.transportFailed()) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `x402 provider: ${binding.kind} facilitator unreachable during settle()`,\n { cause: err },\n );\n }\n const rejectionReason = isOnChainRevertError(err)\n ? 'transaction_reverted'\n : 'unexpected_settle_error';\n logger.warn(\n { err: describeError(err), rejectionReason },\n 'x402 settle(): settlement transaction failed',\n );\n return rejectedSettlement(rejectionReason);\n }\n\n if (!sdkResult.success) {\n // \"Broadcast, never confirmed\" is not \"did not happen\": the transfer may\n // already be on-chain, so it surfaces as an *unavailable* provider\n // carrying the hash, letting the pipeline record\n // the attempt `settlement-uncertain` rather than `failed` and the payer\n // is told which transaction to check. Everything else is a real\n // rejection.\n if (sdkResult.errorReason === SETTLEMENT_PENDING_REASON || scope.transportFailed()) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'x402 provider: settlement was broadcast but could not be confirmed',\n {\n ...(sdkResult.transaction\n ? { details: { transactionHash: sdkResult.transaction } }\n : {}),\n },\n );\n }\n return {\n ...rejectedSettlement(sdkResult.errorReason ?? 'settlement_failed'),\n network: sdkResult.network,\n ...(sdkResult.payer !== undefined ? { payer: sdkResult.payer } : {}),\n };\n }\n\n return {\n status: 'settled',\n provider: 'x402',\n externalReference: sdkResult.transaction,\n ...(sdkResult.payer !== undefined ? { payer: sdkResult.payer } : {}),\n payee: requirements.payTo,\n amount: verification.amount,\n currency: requirement.currency,\n network: sdkResult.network,\n ...(verification.asset !== undefined ? { asset: verification.asset } : {}),\n ...(verification.replayKey !== undefined ? { replayKey: verification.replayKey } : {}),\n settledAt: clock.nowIso(),\n };\n }\n\n async function computeHealth(): Promise<AdapterHealth> {\n const startedAt = clock.monotonicMs();\n const checkedAt = clock.nowIso();\n\n try {\n const chainId = await healthPublicClient.getChainId();\n if (chainId !== profile.chainId) {\n return {\n status: 'fail',\n detail: `RPC at ${options.rpcUrl} reports chain id ${chainId}, expected ${profile.chainId} (${profile.displayName})`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n const code = await healthPublicClient.getCode({ address: options.asset });\n if (!code || code === '0x') {\n return {\n status: 'fail',\n detail: `No contract code found at configured asset address ${options.asset}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n if (binding.kind === 'remote') {\n // \"Reachable\" is not the question — \"will it settle *this*\" is. A\n // facilitator that is up but does not carry our scheme on our network\n // fails every payment, and does it after the buyer has signed.\n const kinds = await binding.supported();\n const supportsUs = kinds.some(\n (kind) =>\n kind.x402Version === X402_VERSION &&\n kind.scheme === 'exact' &&\n kind.network === options.network,\n );\n if (!supportsUs) {\n return {\n status: 'fail',\n detail:\n `Facilitator ${binding.describe} does not advertise x402 v${X402_VERSION} scheme=exact ` +\n `on ${options.network} (${profile.displayName}); no payment on this deployment can settle`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(mode)} — RPC ${options.rpcUrl} reachable, chain id ` +\n `${profile.chainId} (${profile.displayName}), asset ${options.asset} has code, ` +\n `facilitator ${binding.describe} supports exact/${options.network}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n // Chain id alone cannot prove this is a dev chain: real Base Sepolia\n // reports the same id (84532) as this project's local chain, by design.\n // Probe an Anvil-only RPC method — present only on a real Anvil node —\n // before trusting a well-known dev key against it.\n const isAnvil = await probeIsAnvilNode(healthPublicClient);\n if (!isAnvil) {\n return {\n status: 'fail',\n detail:\n `RPC at ${options.rpcUrl} reports chain id ${profile.chainId} but does not answer ` +\n '\"anvil_nodeInfo\" — it does not look like a local Anvil dev node. Refusing to treat it ' +\n 'as safe for a local-facilitator dev key.',\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n\n return {\n status: 'pass',\n detail:\n `${describeDeploymentMode(mode)} — RPC ${options.rpcUrl} reachable, chain id ` +\n `${profile.chainId}, asset ${options.asset} has code, confirmed Anvil dev node`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n } catch (err) {\n return {\n status: 'fail',\n detail: `x402 health check failed: ${describeError(err)}`,\n checkedAt,\n durationMs: clock.monotonicMs() - startedAt,\n };\n }\n }\n\n // /ready has no auth, no cache and no\n // rate limit, and called computeHealth() — 3 live RPC calls — on every\n // single request; measured 3x amplification of billed upstream calls\n // under an unauthenticated flood. Memoise behind a short TTL and collapse\n // concurrent callers onto one in-flight probe, so N requests within the\n // window produce at most one round-trip instead of N.\n //\n // 5s: short enough that a readiness probe (Kubernetes' own default\n // `periodSeconds` is 10s) never observes data older than its own poll\n // interval, long enough to fully decouple RPC call volume from HTTP\n // request volume — which is the property that closes the amplification,\n // not the exact number of seconds.\n //\n // pass and fail are cached for the same TTL, deliberately: a shorter TTL\n // for fail would re-introduce the amplification exactly when an upstream\n // outage makes every call expensive/slow, which is the worst possible time\n // to remove the cache's protection. 5s of recovery latency after the RPC\n // comes back is an acceptable trade — it is already within the noise of a\n // single health probe's own round-trip time, and well inside a normal\n // probe's own poll interval.\n //\n // This only memoises this provider's own RPC probe. `core` separately\n // memoises the whole /ready aggregation (src/gateway/readiness.ts)\n // — a second, independent layer at a different scope; the two compose\n // without conflict since neither assumes anything about the other's TTL.\n //\n // Does not affect `doctor`'s deployment-mismatch cross-check: that reads\n // asset/network/payTo straight from `/.well-known/agent-commerce` (static\n // provider config, echoed live, never cached), not from health().\n const HEALTH_CACHE_MS = 5_000;\n let cachedHealth: { at: number; value: AdapterHealth } | undefined;\n let inFlightHealth: Promise<AdapterHealth> | undefined;\n\n async function health(): Promise<AdapterHealth> {\n const now = clock.monotonicMs();\n if (cachedHealth && now - cachedHealth.at < HEALTH_CACHE_MS) {\n return cachedHealth.value;\n }\n if (inFlightHealth) return inFlightHealth;\n\n inFlightHealth = computeHealth()\n .then((value) => {\n cachedHealth = { at: clock.monotonicMs(), value };\n return value;\n })\n .finally(() => {\n inFlightHealth = undefined;\n });\n return inFlightHealth;\n }\n\n return {\n name: 'x402',\n descriptor,\n createRequirement,\n verify,\n settle,\n health,\n };\n}\n\nfunction isOnChainRevertError(err: unknown): boolean {\n return (\n err instanceof ContractFunctionRevertedError || err instanceof ContractFunctionExecutionError\n );\n}\n\n/**\n * `instanceof` checks first — these are the real error classes the pinned\n * viem@2.55.18 HTTP transport throws (see viem's `utils/rpc/http.js`, which\n * wraps every fetch failure, including connection-refused, in\n * `HttpRequestError` unless it is already a `TimeoutError`), plus the error\n * `waitForTransactionReceipt` itself throws when it gives up polling for a\n * receipt — precisely the \"broadcast succeeded, confirmation didn't\" case\n * this classification exists to catch. Substring matching\n * is kept only as a fallback for shapes not covered by a typed viem class\n * (e.g. a raw Node/undici error surfacing through some other path) — pinning\n * behaviour to message text is brittle across viem/undici upgrades, so the\n * instanceof checks should be preferred and grown over time as more real\n * failure shapes are seen.\n */\nfunction isProviderUnavailableError(err: unknown): boolean {\n if (\n err instanceof HttpRequestError ||\n err instanceof TimeoutError ||\n err instanceof WaitForTransactionReceiptTimeoutError\n ) {\n return true;\n }\n const message = describeError(err).toLowerCase();\n return (\n message.includes('econnrefused') ||\n message.includes('fetch failed') ||\n message.includes('enotfound') ||\n message.includes('etimedout') ||\n message.includes('timed out') ||\n message.includes('network error')\n );\n}\n\n/** Never includes secrets: only error class name + message, never raw payloads or keys. */\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return `${err.name}: ${err.message}`;\n return String(err);\n}\n\n/**\n * True only when the RPC answers Anvil's own `anvil_nodeInfo` method — a\n * real network (including real Base Sepolia, which shares chain id 84532\n * with this project's local chain by design) returns a JSON-RPC \"method\n * not found\" error instead. Never throws.\n */\nasync function probeIsAnvilNode(\n client: ReturnType<typeof createLocalPublicClient>,\n): Promise<boolean> {\n // Anvil-only method: not part of viem's typed PublicRpcSchema, hence the cast.\n const request = client.request as unknown as (args: {\n method: string;\n params: unknown[];\n }) => Promise<unknown>;\n try {\n await request({ method: 'anvil_nodeInfo', params: [] });\n return true;\n } catch {\n return false;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devlab.group/agent-commerce",
3
- "version": "0.1.0-alpha.0",
3
+ "version": "0.2.0-beta.0",
4
4
  "description": "Open-source, self-hosted, non-custodial commerce and payment orchestration gateway for AI agents.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -9,7 +9,7 @@
9
9
  "npm": ">=10"
10
10
  },
11
11
  "bin": {
12
- "agent-commerce": "./dist/cli/index.js"
12
+ "agent-commerce": "dist/cli/index.js"
13
13
  },
14
14
  "exports": {
15
15
  ".": {
@@ -65,6 +65,7 @@
65
65
  "test:watch": "vitest",
66
66
  "test:coverage": "vitest run --coverage",
67
67
  "test:e2e": "vitest run --config vitest.e2e.config.ts",
68
+ "test:testnet": "vitest run --config vitest.testnet.config.ts",
68
69
  "check:contract": "node scripts/contract-surface.mjs",
69
70
  "check:metadata": "node scripts/check-package-metadata.mjs",
70
71
  "verify": "npm run check:contract && npm run lint && npm run typecheck && npm test",
@@ -81,7 +82,7 @@
81
82
  "demo:agent": "tsx demo/agent/src/main.ts",
82
83
  "demo:up": "docker compose up --build",
83
84
  "demo:down": "docker compose down -v",
84
- "test:cli:dist": "node dist/cli/index.js --help && node dist/cli/index.js --version",
85
+ "test:cli:dist": "node dist/cli/index.js --help && node dist/cli/index.js --version && node dist/cli/index.js version | grep -q '@x402/core' && node dist/cli/index.js version | head -1 >/dev/null",
85
86
  "pack:dry": "npm pack --dry-run"
86
87
  },
87
88
  "dependencies": {
@@ -96,14 +97,18 @@
96
97
  },
97
98
  "peerDependencies": {
98
99
  "@modelcontextprotocol/sdk": "1.30.0",
99
- "x402": "1.2.0",
100
+ "@x402/core": "2.23.0",
101
+ "@x402/evm": "2.23.0",
100
102
  "viem": "2.55.18"
101
103
  },
102
104
  "peerDependenciesMeta": {
103
105
  "@modelcontextprotocol/sdk": {
104
106
  "optional": true
105
107
  },
106
- "x402": {
108
+ "@x402/core": {
109
+ "optional": true
110
+ },
111
+ "@x402/evm": {
107
112
  "optional": true
108
113
  },
109
114
  "viem": {
@@ -119,6 +124,8 @@
119
124
  "@types/react-dom": "19.2.4",
120
125
  "@vitejs/plugin-react": "6.0.5",
121
126
  "@vitest/coverage-v8": "4.1.10",
127
+ "@x402/core": "2.23.0",
128
+ "@x402/evm": "2.23.0",
122
129
  "pino-pretty": "13.1.2",
123
130
  "react": "19.0.8",
124
131
  "react-dom": "19.0.8",
@@ -127,8 +134,7 @@
127
134
  "typescript": "5.9.3",
128
135
  "viem": "2.55.18",
129
136
  "vite": "8.2.1",
130
- "vitest": "4.1.10",
131
- "x402": "1.2.0"
137
+ "vitest": "4.1.10"
132
138
  },
133
139
  "overrides": {
134
140
  "zod": "3.25.76"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/domain/event.ts","../src/core/domain/resource.ts","../src/core/domain/wire.ts","../src/core/errors/codes.ts","../src/core/errors/commerce-error.ts","../src/core/interfaces/logger.ts","../src/core/interfaces/protocol-adapter.ts","../src/core/interfaces/runtime.ts","../src/version.ts"],"names":[],"mappings":";;;AASO,IAAM,oBAAA,GAAuB;AAAA,EAClC,qBAAA;AAAA,EACA,oBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,gBAAA;AAAA,EACA;AACF;;;ACSO,IAAM,0BAAA,GAA6B;;;ACXnC,IAAM,mBAAA,GAAsB;AAG5B,IAAM,cAAA,GAAiB;AAGvB,IAAM,uBAAA,GAA0B;AAchC,IAAM,yBAAA,GAA4B;AA6DlC,SAAS,kBAAkB,OAAA,EAA4C;AAC5E,EAAA,MAAM,IAAI,OAAA,CAAQ,OAAA;AAClB,EAAA,OAAO;AAAA,IACL,WAAW,OAAA,CAAQ,SAAA;AAAA,IACnB,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,SAAA,EAAW,QAAQ,OAAA,CAAQ,EAAA;AAAA,IAC3B,WAAA,EAAa,QAAQ,OAAA,CAAQ,WAAA;AAAA,IAC7B,GAAI,MAAM,MAAA,GACN;AAAA,MACE,OAAA,EAAS;AAAA,QACP,QAAQ,CAAA,CAAE,MAAA;AAAA,QACV,QAAQ,CAAA,CAAE,MAAA;AAAA,QACV,UAAU,CAAA,CAAE,QAAA;AAAA,QACZ,GAAI,EAAE,iBAAA,KAAsB,MAAA,GACxB,EAAE,iBAAA,EAAmB,CAAA,CAAE,iBAAA,EAAkB,GACzC,EAAC;AAAA,QACL,GAAI,EAAE,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EA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IAAI,IAAA,IAAO,WAAA,EAAY;AAAA,EACrC,WAAA,EAAa,MAAM,WAAA,CAAY,GAAA;AACjC;ACOO,IAAM,eAAA,GACmC,eAAA","file":"chunk-CZ6ZDAYD.js","sourcesContent":["/**\n * Canonical commerce events.\n *\n * FROZEN CONTRACT. Every event in a single flow shares one `requestId` so that\n * logs, payment attempts, backend calls and receipts are correlatable\n *.\n */\nimport type { IsoTimestamp } from './common.js';\n\nexport const COMMERCE_EVENT_TYPES = [\n 'resource.discovered',\n 'resource.requested',\n 'payment.required',\n 'payment.rejected',\n 'payment.verified',\n 'payment.settled',\n 'backend.called',\n 'backend.failed',\n 'resource.delivered',\n] as const;\n\nexport type CommerceEventType = (typeof COMMERCE_EVENT_TYPES)[number];\n\nexport interface CommerceEvent {\n readonly id: string;\n readonly type: CommerceEventType;\n readonly requestId: string;\n readonly resourceId?: string;\n readonly at: IsoTimestamp;\n /** Protocol adapter that originated the request, e.g. 'mcp' or 'http'. */\n readonly adapter?: string;\n readonly paymentProvider?: string;\n readonly durationMs?: number;\n readonly status?: 'ok' | 'error';\n /** Non-secret, structured detail. Must never contain keys, headers or proofs. */\n readonly data?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Sink for canonical events.\n *\n * Implementations must be non-throwing from the caller's perspective: an event\n * sink failure must never fail an otherwise successful commerce flow.\n */\nexport interface EventSink {\n emit(event: CommerceEvent): Promise<void>;\n}\n","/**\n * Canonical resource model.\n *\n * FROZEN CONTRACT.\n */\nimport type { DecimalAmount, JsonSchema, PaymentMethodName, ProtocolName } from './common.js';\n\n/** HTTP methods a backend handler may use. */\nexport type BackendMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * Describes how the gateway calls the merchant's existing backend.\n *\n * Backend URLs are administrator-controlled configuration only. User- or\n * agent-controlled backend URLs are forbidden (see docs/security.md, SSRF).\n * Secret header values must come from `${ENV_VAR}` placeholders resolved by\n * the config loader, never from plaintext configuration.\n */\nexport interface BackendHandler {\n readonly type: 'http';\n readonly method: BackendMethod;\n readonly url: string;\n readonly headers?: Readonly<Record<string, string>>;\n /** Hard upper bound on the backend call. Defaults to DEFAULT_BACKEND_TIMEOUT_MS. */\n readonly timeoutMs?: number;\n}\n\n/** Default backend timeout when a resource does not specify one. */\nexport const DEFAULT_BACKEND_TIMEOUT_MS = 10_000;\n\n/**\n * Canonical pricing.\n *\n * `dynamic` exists in the type system for forward compatibility but is\n * REJECTED by config validation in v0.1.0-alpha.\n */\nexport type Pricing =\n | { readonly type: 'free' }\n | {\n readonly type: 'fixed';\n readonly amount: DecimalAmount;\n readonly currency: string;\n }\n | {\n readonly type: 'dynamic';\n readonly resolver: string;\n };\n\n/**\n * A merchant capability exposed to agents.\n *\n * The canonical resource is the single source of truth: protocol adapters map\n * it outward, they never define their own parallel notion of a resource.\n */\nexport interface CommerceResource {\n readonly id: string;\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly handler: BackendHandler;\n readonly pricing: Pricing;\n readonly exposedVia: readonly ProtocolName[];\n readonly paymentMethods: readonly PaymentMethodName[];\n}\n\n/** Read-only view of every configured resource. */\nexport interface ResourceRegistry {\n get(id: string): CommerceResource | undefined;\n list(): readonly CommerceResource[];\n /** Resources exposed through a given protocol surface. */\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[];\n has(id: string): boolean;\n}\n","/**\n * Gateway-defined wire envelopes.\n *\n * FROZEN CONTRACT. These are the *only* representations of \"payment required\"\n * and \"error\" that leave the gateway, whichever protocol carries them. The HTTP\n * routes, the MCP adapter and the demo buyer agent all use these helpers so the\n * three can never drift apart.\n */\n\nimport type { CommerceError, CommerceErrorCode } from '../errors/index.js';\nimport type { DecimalAmount, IsoTimestamp, PaymentMethodName } from './common.js';\nimport type { DeliveredOutcome, PaymentRequiredOutcome } from './request.js';\n\n/**\n * Reserved input property carrying a payment proof on protocols that have no\n * header channel (MCP tool calls). Over HTTP the `X-PAYMENT` header is used.\n */\nexport const PAYMENT_INPUT_FIELD = '_payment';\n\n/** HTTP header carrying the payment proof. */\nexport const PAYMENT_HEADER = 'x-payment';\n\n/** HTTP response header carrying the settlement reference. */\nexport const PAYMENT_RESPONSE_HEADER = 'x-payment-response';\n\n/**\n * Key under which a protocol adapter attaches a {@link DeliverySummary} to its\n * result metadata — MCP's `CallToolResult._meta`, and anywhere else a protocol\n * offers an out-of-band metadata channel.\n *\n * Frozen deliberately. The bug this whole mechanism exists to fix was two\n * surfaces disagreeing about what a payer gets back; a key name enforced only\n * by one side's tests would reintroduce exactly that drift. Producer and\n * consumer both import this constant.\n *\n * Follows MCP's `<namespace>/<name>` convention for `_meta` keys.\n */\nexport const DELIVERY_SUMMARY_META_KEY = 'agent-commerce/delivery';\n\nexport interface PaymentRequiredEnvelope {\n readonly status: 'payment-required';\n readonly code: 'PAYMENT_REQUIRED';\n readonly requestId: string;\n readonly resourceId: string;\n readonly message: string;\n readonly payment: {\n readonly provider: PaymentMethodName;\n readonly version: string;\n readonly amount: DecimalAmount;\n readonly currency: string;\n readonly destination: string;\n readonly network?: string;\n readonly asset?: string;\n readonly expiresAt?: IsoTimestamp;\n /** Provider-native requirement objects, passed through verbatim. */\n readonly accepts: readonly Readonly<Record<string, unknown>>[];\n };\n}\n\nexport interface ErrorEnvelope {\n readonly status: 'error';\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * What a buyer learns about their own completed purchase.\n *\n * A payer is entitled to the record of their own transaction — the request it\n * belonged to, whether it settled, and the settlement reference they can check\n * on-chain. They are NOT entitled to the merchant's ledger, which is why\n * `/api/receipts` is an operator route behind `server.adminToken`.\n *\n * Before this existed the two surfaces disagreed: HTTP callers received a\n * settlement summary in `X-PAYMENT-RESPONSE` while MCP callers received\n * nothing, so an MCP buyer's only route to their own receipt was the merchant's\n * ledger. Both surfaces now emit this same shape.\n */\nexport interface DeliverySummary {\n readonly requestId: string;\n readonly resourceId: string;\n readonly receiptId: string;\n readonly deliveredAt: IsoTimestamp;\n readonly payment?: {\n readonly status: 'verified' | 'settled' | 'rejected';\n readonly amount: DecimalAmount;\n readonly currency: string;\n /** Settlement reference, e.g. an on-chain transaction hash. */\n readonly externalReference?: string;\n readonly network?: string;\n };\n}\n\n/** Build the payer-facing summary of a delivered outcome. */\nexport function toDeliverySummary(outcome: DeliveredOutcome): DeliverySummary {\n const p = outcome.payment;\n return {\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n receiptId: outcome.receipt.id,\n deliveredAt: outcome.receipt.deliveredAt,\n ...(p !== undefined\n ? {\n payment: {\n status: p.status,\n amount: p.amount,\n currency: p.currency,\n ...(p.externalReference !== undefined\n ? { externalReference: p.externalReference }\n : {}),\n ...(p.network !== undefined ? { network: p.network } : {}),\n },\n }\n : {}),\n };\n}\n\nexport function toPaymentRequiredEnvelope(\n outcome: PaymentRequiredOutcome,\n): PaymentRequiredEnvelope {\n const r = outcome.requirement;\n return {\n status: 'payment-required',\n code: 'PAYMENT_REQUIRED',\n requestId: outcome.requestId,\n resourceId: outcome.resourceId,\n message: `Payment of ${r.amount} ${r.currency} is required for resource \"${outcome.resourceId}\". Retry with a ${r.provider} payment proof.`,\n payment: {\n provider: r.provider,\n version: r.challenge.version,\n amount: r.amount,\n currency: r.currency,\n destination: r.destination,\n ...(r.network !== undefined ? { network: r.network } : {}),\n ...(r.asset !== undefined ? { asset: r.asset } : {}),\n ...(r.expiresAt !== undefined ? { expiresAt: r.expiresAt } : {}),\n accepts: r.challenge.accepts,\n },\n };\n}\n\nexport function toErrorEnvelope(error: CommerceError): ErrorEnvelope {\n const info = error.toInfo();\n return {\n status: 'error',\n code: info.code,\n message: info.message,\n retryable: info.retryable,\n ...(info.requestId !== undefined ? { requestId: info.requestId } : {}),\n ...(info.resourceId !== undefined ? { resourceId: info.resourceId } : {}),\n ...(info.details !== undefined ? { details: info.details } : {}),\n };\n}\n\nexport function isPaymentRequiredEnvelope(value: unknown): value is PaymentRequiredEnvelope {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as PaymentRequiredEnvelope).status === 'payment-required' &&\n typeof (value as PaymentRequiredEnvelope).payment === 'object'\n );\n}\n","/**\n * Typed domain error codes.\n *\n * FROZEN CONTRACT. Protocol adapters map these codes into their own response\n * format. Never throw a bare string or untyped Error across a package boundary.\n */\nexport const COMMERCE_ERROR_CODES = [\n 'CONFIG_INVALID',\n 'RESOURCE_NOT_FOUND',\n 'INPUT_INVALID',\n 'PAYMENT_REQUIRED',\n 'PAYMENT_INVALID',\n 'PAYMENT_REPLAYED',\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'PAYMENT_SETTLEMENT_FAILED',\n 'BACKEND_TIMEOUT',\n 'BACKEND_ERROR',\n 'PROTOCOL_UNSUPPORTED',\n 'GATEWAY_BUSY',\n 'STORAGE_ERROR',\n 'INTERNAL_ERROR',\n] as const;\n\nexport type CommerceErrorCode = (typeof COMMERCE_ERROR_CODES)[number];\n\n/**\n * Canonical HTTP status for each error code.\n *\n * Paid resources fail closed: every payment failure maps to a 4xx/5xx status\n * and never to a successful delivery.\n */\nexport const COMMERCE_ERROR_HTTP_STATUS: Readonly<Record<CommerceErrorCode, number>> = {\n CONFIG_INVALID: 500,\n RESOURCE_NOT_FOUND: 404,\n INPUT_INVALID: 400,\n PAYMENT_REQUIRED: 402,\n PAYMENT_INVALID: 402,\n PAYMENT_REPLAYED: 409,\n PAYMENT_PROVIDER_UNAVAILABLE: 503,\n PAYMENT_SETTLEMENT_FAILED: 502,\n BACKEND_TIMEOUT: 504,\n BACKEND_ERROR: 502,\n PROTOCOL_UNSUPPORTED: 501,\n GATEWAY_BUSY: 503,\n STORAGE_ERROR: 500,\n INTERNAL_ERROR: 500,\n};\n\n/** Codes for which a client may reasonably retry the same request. */\nexport const RETRYABLE_ERROR_CODES: ReadonlySet<CommerceErrorCode> = new Set([\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'BACKEND_TIMEOUT',\n // Load shedding is transient by definition: the caller should back off and\n // try again. Before this code existed the MCP adapter's queue-full path threw\n // PROTOCOL_UNSUPPORTED — HTTP 501, retryable:false — so an agent framework\n // keyed on the machine-readable flag (which exists precisely so clients need\n // not parse prose) would read a momentary throttle as a permanent capability\n // gap and stop calling the tool.\n 'GATEWAY_BUSY',\n]);\n","/**\n * The single error type crossing package boundaries.\n *\n * FROZEN CONTRACT.\n */\nimport {\n COMMERCE_ERROR_HTTP_STATUS,\n type CommerceErrorCode,\n RETRYABLE_ERROR_CODES,\n} from './codes.js';\n\nexport interface CommerceErrorOptions {\n /** Structured, non-secret detail safe to return to a client. */\n readonly details?: Readonly<Record<string, unknown>>;\n readonly cause?: unknown;\n readonly requestId?: string;\n readonly resourceId?: string;\n /** Override the default HTTP status for this code. */\n readonly httpStatus?: number;\n}\n\n/** Serialisable wire form of a CommerceError. */\nexport interface CommerceErrorInfo {\n readonly code: CommerceErrorCode;\n readonly message: string;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly requestId?: string;\n readonly resourceId?: string;\n readonly details?: Readonly<Record<string, unknown>>;\n}\n\nexport class CommerceError extends Error {\n readonly code: CommerceErrorCode;\n readonly httpStatus: number;\n readonly retryable: boolean;\n readonly details?: Readonly<Record<string, unknown>>;\n readonly requestId?: string;\n readonly resourceId?: string;\n\n constructor(code: CommerceErrorCode, message: string, options: CommerceErrorOptions = {}) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'CommerceError';\n this.code = code;\n this.httpStatus = options.httpStatus ?? COMMERCE_ERROR_HTTP_STATUS[code];\n this.retryable = RETRYABLE_ERROR_CODES.has(code);\n if (options.details !== undefined) this.details = options.details;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.resourceId !== undefined) this.resourceId = options.resourceId;\n Error.captureStackTrace?.(this, CommerceError);\n }\n\n /** Non-secret, client-safe representation. */\n toInfo(): CommerceErrorInfo {\n return {\n code: this.code,\n message: this.message,\n httpStatus: this.httpStatus,\n retryable: this.retryable,\n ...(this.requestId !== undefined ? { requestId: this.requestId } : {}),\n ...(this.resourceId !== undefined ? { resourceId: this.resourceId } : {}),\n ...(this.details !== undefined ? { details: this.details } : {}),\n };\n }\n}\n\nexport function isCommerceError(value: unknown): value is CommerceError {\n return value instanceof CommerceError;\n}\n\n/**\n * Normalise any thrown value into a CommerceError.\n *\n * Used at package boundaries so an unexpected failure never escapes untyped.\n *\n * SECURITY — do not \"improve\" this by propagating `value.message`.\n * `CommerceError.message` is client-visible: it is serialised by `toInfo()`\n * and `toErrorEnvelope()` and returned over HTTP and MCP. An arbitrary thrown\n * Error's message routinely carries internal detail — database connection\n * strings, internal hostnames, filesystem paths, backend URLs. Copying it into\n * a client-facing field turns every unexpected exception into an information\n * disclosure.\n *\n * The original value is preserved on `cause`, which is never serialised, so\n * logs and diagnostics keep the full detail while clients get only the\n * caller's deliberate, reviewed `fallbackMessage`.\n *\n * A caller that *wants* a specific client-facing message passes one:\n * toCommerceError(err, 'BACKEND_ERROR', 'Backend call failed')\n */\nexport function toCommerceError(\n value: unknown,\n fallbackCode: CommerceErrorCode = 'INTERNAL_ERROR',\n fallbackMessage = 'Unexpected internal error',\n): CommerceError {\n if (isCommerceError(value)) return value;\n return new CommerceError(fallbackCode, fallbackMessage, { cause: value });\n}\n","/**\n * Minimal structural logger interface.\n *\n * Core must not depend on pino directly; the gateway injects a pino instance\n * that satisfies this shape. Never log secrets: private keys, seed phrases,\n * Authorization headers or payment authorisation payloads.\n */\nexport interface Logger {\n debug(obj: Record<string, unknown>, msg?: string): void;\n info(obj: Record<string, unknown>, msg?: string): void;\n warn(obj: Record<string, unknown>, msg?: string): void;\n error(obj: Record<string, unknown>, msg?: string): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n/** A logger that discards everything. Useful in unit tests. */\nexport const NOOP_LOGGER: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n child: () => NOOP_LOGGER,\n};\n","/**\n * Protocol adapter boundary.\n *\n * FROZEN CONTRACT. An adapter translates a protocol's wire format into a\n * `CanonicalRequest`, hands it to the execution pipeline and maps the outcome\n * back. It must not call merchant backends, implement payment logic, or hold\n * its own copy of the canonical model.\n *\n * Adapter isolation: a failure while starting or serving one adapter must not\n * prevent the others from operating.\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AdapterDescriptor, AdapterHealth, ProtocolName } from '../domain/common.js';\nimport type { EventSink } from '../domain/event.js';\nimport type { ExecutionPipeline } from '../domain/request.js';\nimport type { ResourceRegistry } from '../domain/resource.js';\nimport type { Logger } from './logger.js';\nimport type { Clock, IdGenerator } from './runtime.js';\n\n/** Everything an adapter is given. Nothing else is available to it. */\nexport interface ProtocolAdapterContext {\n readonly pipeline: ExecutionPipeline;\n readonly resources: ResourceRegistry;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /** Externally reachable base URL of the gateway, from config. */\n readonly publicBaseUrl: string;\n}\n\nexport interface ProtocolAdapter {\n readonly name: ProtocolName;\n readonly descriptor: AdapterDescriptor;\n\n start(context: ProtocolAdapterContext): Promise<void>;\n health(): Promise<AdapterHealth>;\n stop(): Promise<void>;\n}\n\n/**\n * A protocol adapter served over HTTP.\n *\n * The gateway mounts `handleHttp` at `mountPath` using raw Node request and\n * response objects, so adapters stay independent of the HTTP framework.\n *\n * GUARANTEE — the request body is **unconsumed**.\n *\n * `req` is handed over with its stream unread: the gateway suppresses every\n * body parser on this mount, so an adapter whose SDK reads the body itself\n * (MCP's Streamable HTTP transport does) can do so. The adapter owns reading,\n * size-limiting beyond the gateway's own cap, and parsing.\n *\n * This is load-bearing and easy to break silently. Fastify pre-registers\n * exact-match parsers for `application/json` and `text/plain` and prefers them\n * over a `'*'` wildcard, so registering only a wildcard no-op leaves the\n * built-in JSON parser draining the body first — the adapter then reads an\n * empty stream and every request fails to parse. That exact regression shipped\n * once and no unit test caught it, because adapter conformance suites drive\n * `handleHttp` over a bare `node:http` server and never traverse the gateway.\n *\n * Any change to how adapters are mounted must be covered by a test that POSTs\n * a real JSON body through the real gateway and asserts the adapter received\n * it intact.\n */\nexport interface HttpProtocolAdapter extends ProtocolAdapter {\n /** Path prefix the gateway mounts this adapter at, e.g. '/mcp'. */\n readonly mountPath: string;\n handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void>;\n}\n\nexport function isHttpProtocolAdapter(adapter: ProtocolAdapter): adapter is HttpProtocolAdapter {\n return typeof (adapter as HttpProtocolAdapter).handleHttp === 'function';\n}\n","/**\n * Injected runtime primitives.\n *\n * Everything non-deterministic (time, ids) is injected so tests can be exact.\n */\nimport type { IsoTimestamp } from '../domain/common.js';\n\nexport interface Clock {\n now(): Date;\n nowIso(): IsoTimestamp;\n /** Milliseconds since an arbitrary origin; use for durations only. */\n monotonicMs(): number;\n}\n\nexport interface IdGenerator {\n /** Opaque, collision-resistant identifier. */\n next(prefix?: string): string;\n}\n\nexport const systemClock: Clock = {\n now: () => new Date(),\n nowIso: () => new Date().toISOString(),\n monotonicMs: () => performance.now(),\n};\n","/**\n * The package version, resolved once for the whole package.\n *\n * Two paths, deliberately:\n *\n * - **Development** reads the root manifest, so the number is always live.\n * - **The published bundle cannot.** tsup collapses `src/**` into\n * `dist/index.js` and `dist/cli/index.js`, so any `require('../../package.json')`\n * written against a source path resolves from the wrong depth once bundled —\n * which is exactly how this broke during the single-package refactor, and how\n * it earlier produced a CLI reporting `v0.0.0-unknown`. The build injects\n * `__OAC_PACKAGE_VERSION__` instead (see tsup.config.ts).\n *\n * `typeof` on an undeclared identifier is safe in JS, so the dev path is\n * unaffected by the constant not existing.\n */\nimport { createRequire } from 'node:module';\n\ndeclare const __OAC_PACKAGE_VERSION__: string | undefined;\n\nfunction readFromManifest(): string {\n try {\n const require = createRequire(import.meta.url);\n // src/version.ts -> repository root\n return (require('../package.json') as { version?: string }).version ?? '0.0.0-unknown';\n } catch {\n return '0.0.0-unknown';\n }\n}\n\nexport const PACKAGE_VERSION: string =\n typeof __OAC_PACKAGE_VERSION__ === 'string' ? __OAC_PACKAGE_VERSION__ : readFromManifest();\n"]}