@devlab.group/agent-commerce 0.1.0-alpha.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.
@@ -0,0 +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;AAAA,EACF;AAEA,EAAA,MAAM,OA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uB;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"]}
package/package.json ADDED
@@ -0,0 +1,136 @@
1
+ {
2
+ "name": "@devlab.group/agent-commerce",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Open-source, self-hosted, non-custodial commerce and payment orchestration gateway for AI agents.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22",
9
+ "npm": ">=10"
10
+ },
11
+ "bin": {
12
+ "agent-commerce": "./dist/cli/index.js"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./mcp": {
20
+ "types": "./dist/mcp.d.ts",
21
+ "import": "./dist/mcp.js"
22
+ },
23
+ "./x402": {
24
+ "types": "./dist/x402.d.ts",
25
+ "import": "./dist/x402.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/devlab-group/agent-commerce.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/devlab-group/agent-commerce/issues"
43
+ },
44
+ "homepage": "https://github.com/devlab-group/agent-commerce#readme",
45
+ "keywords": [
46
+ "ai-agents",
47
+ "agentic-commerce",
48
+ "mcp",
49
+ "x402",
50
+ "payments",
51
+ "web3",
52
+ "commerce",
53
+ "ai",
54
+ "cli"
55
+ ],
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "prepack": "npm run build",
59
+ "prepublishOnly": "npm run build && npm run verify && npm run test:cli:dist",
60
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p demo/dashboard/tsconfig.json",
61
+ "lint": "biome check .",
62
+ "lint:fix": "biome check --write .",
63
+ "format": "biome format --write .",
64
+ "test": "vitest run",
65
+ "test:watch": "vitest",
66
+ "test:coverage": "vitest run --coverage",
67
+ "test:e2e": "vitest run --config vitest.e2e.config.ts",
68
+ "check:contract": "node scripts/contract-surface.mjs",
69
+ "check:metadata": "node scripts/check-package-metadata.mjs",
70
+ "verify": "npm run check:contract && npm run lint && npm run typecheck && npm test",
71
+ "agent-commerce": "tsx src/cli/index.ts",
72
+ "doctor": "tsx src/cli/index.ts doctor",
73
+ "chain:start": "tsx scripts/chain/start-anvil.ts",
74
+ "chain:deploy": "tsx scripts/chain/deploy.ts",
75
+ "demo:merchant": "tsx demo/merchant/src/main.ts",
76
+ "dev:merchant": "tsx watch demo/merchant/src/main.ts",
77
+ "demo:gateway": "AGENT_COMMERCE_CONFIG=config-demo.yaml tsx src/gateway/main.ts",
78
+ "dev:gateway": "AGENT_COMMERCE_CONFIG=config-demo.yaml tsx watch src/gateway/main.ts",
79
+ "demo:dashboard": "vite --config demo/dashboard/vite.config.ts",
80
+ "dev:dashboard": "vite --config demo/dashboard/vite.config.ts",
81
+ "demo:agent": "tsx demo/agent/src/main.ts",
82
+ "demo:up": "docker compose up --build",
83
+ "demo:down": "docker compose down -v",
84
+ "test:cli:dist": "node dist/cli/index.js --help && node dist/cli/index.js --version",
85
+ "pack:dry": "npm pack --dry-run"
86
+ },
87
+ "dependencies": {
88
+ "@clack/prompts": "1.7.0",
89
+ "better-sqlite3": "13.0.3",
90
+ "commander": "15.0.0",
91
+ "fastify": "5.12.0",
92
+ "picocolors": "1.1.1",
93
+ "pino": "10.3.1",
94
+ "yaml": "2.9.0",
95
+ "zod": "3.25.76"
96
+ },
97
+ "peerDependencies": {
98
+ "@modelcontextprotocol/sdk": "1.30.0",
99
+ "x402": "1.2.0",
100
+ "viem": "2.55.18"
101
+ },
102
+ "peerDependenciesMeta": {
103
+ "@modelcontextprotocol/sdk": {
104
+ "optional": true
105
+ },
106
+ "x402": {
107
+ "optional": true
108
+ },
109
+ "viem": {
110
+ "optional": true
111
+ }
112
+ },
113
+ "devDependencies": {
114
+ "@biomejs/biome": "2.5.9",
115
+ "@modelcontextprotocol/sdk": "1.30.0",
116
+ "@types/better-sqlite3": "9.6.0",
117
+ "@types/node": "24.13.3",
118
+ "@types/react": "19.2.18",
119
+ "@types/react-dom": "19.2.4",
120
+ "@vitejs/plugin-react": "6.0.5",
121
+ "@vitest/coverage-v8": "4.1.10",
122
+ "pino-pretty": "13.1.2",
123
+ "react": "19.0.8",
124
+ "react-dom": "19.0.8",
125
+ "tsup": "8.5.1",
126
+ "tsx": "4.23.12",
127
+ "typescript": "5.9.3",
128
+ "viem": "2.55.18",
129
+ "vite": "8.2.1",
130
+ "vitest": "4.1.10",
131
+ "x402": "1.2.0"
132
+ },
133
+ "overrides": {
134
+ "zod": "3.25.76"
135
+ }
136
+ }