@bosonprotocol/x402-client 0.2.0 → 0.3.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.
- package/dist/cjs/index.d.ts +126 -3
- package/dist/cjs/index.js +280 -21
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +276 -22
- package/dist/esm/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/action.ts","../../src/fulfillment.ts","../../src/internal/web3lib-adapter.ts","../../src/core-sdk-factory.ts","../../src/response.ts","../../src/payload.ts","../../src/utils/crypto.ts","../../src/pre-commit.ts","../../src/post-commit.ts","../../src/withdraw.ts","../../src/token-auth/deadline.ts","../../src/token-auth/erc3009.ts","../../src/token-auth/permit.ts","../../src/token-auth/permit2.ts","../../src/token-auth/index.ts","../../src/client.ts","../../src/signer-from-adapter.ts"],"names":["Ajv","coreSdk","CoreSDK","parseEscrowPaymentPayload","encodeSignedPayload","DECIMAL_UINT","encodeFunctionData","decodeFunctionResult","PERMIT2_ADDRESS","parseEscrowPaymentRequirements","getAddress","serializeTypedData"],"mappings":";;;;;;;;;;;;;;AAIO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAEO,IAAM,yBAAA,GAAN,cAAwC,KAAA,CAAM;AAAA,EACnD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,2BAAA;AAAA,EACd;AACF;AAEO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO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AAO,GAAA,KAAQ,QAAA,IAAY,CAAC,kBAAA,CAAmB,IAAA,CAAK,GAAG,CAAA,EAAG;AAC5D,QAAA,MAAM,IAAI,KAAA;AAAA,UACR;AAAA,SACF;AAAA,MACF;AACA,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,GACF;AACF;AAQA,SAAS,uBAAuB,MAAA,EAAwD;AACtF,EAAA,MAAM,SAA+B,EAAC;AACtC,EAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,QAAA,EAAU,CAAA;AAC3E,EAAA,IAAI,MAAA,CAAO,OAAA,KAAY,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,QAAA,EAAU,CAAA;AACjF,EAAA,IAAI,MAAA,CAAO,OAAA,KAAY,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,SAAA,EAAW,CAAA;AAClF,EAAA,IAAI,OAAO,iBAAA,KAAsB,MAAA;AAC/B,IAAA,MAAA,CAAO,KAAK,EAAE,IAAA,EAAM,mBAAA,EAAqB,IAAA,EAAM,WAAW,CAAA;AAC5D,EAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW,CAAA;AAC5E,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// Typed error classes for the x402-client. Each is a leaf `Error` subclass\n// with a stable `name` so callers can branch on `instanceof` or string-match\n// without parsing messages.\n\nexport class UnsupportedSchemeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedSchemeError\";\n }\n}\n\nexport class UnsupportedTokenAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedTokenAuthError\";\n }\n}\n\nexport class NoCompatibleActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NoCompatibleActionError\";\n }\n}\n\nexport class FulfillmentValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FulfillmentValidationError\";\n }\n}\n\nexport class MaxAmountExceededError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MaxAmountExceededError\";\n }\n}\n","// Pick the on-chain Boson action to invoke from a parsed PaymentRequirements.\n//\n// Two commit-time actions are supported:\n// - `boson-createOfferAndCommit` (Flow A, deferred redeem)\n// - `boson-createOfferCommitAndRedeem` (Flow B, atomic commit+redeem)\n//\n// Selection rules:\n// - `policy.redeemMode = \"commit-only\"`: require Flow A.\n// - `policy.redeemMode = \"auto\"` (or unset): prefer Flow A, fall back to Flow B.\n// - `policy.redeemMode = \"commit-and-redeem\"`: require Flow B; throw\n// `NoCompatibleActionError` if the server hasn't advertised it.\n//\n// In \"auto\" mode we keep MVP behaviour (prefer Flow A whenever advertised)\n// so existing callers don't silently switch flows on the SDK upgrade. A\n// future policy could promote Flow B when both are offered, but that's a\n// separate change.\n\nimport type {\n BosonCommitActionId,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport { NoCompatibleActionError } from \"./errors.js\";\nimport type { Policy } from \"./types.js\";\n\nconst FLOW_A: BosonCommitActionId = \"boson-createOfferAndCommit\";\nconst FLOW_B: BosonCommitActionId = \"boson-createOfferCommitAndRedeem\";\n\n/**\n * Resolve the Boson commit-time action the client will sign. Throws\n * `NoCompatibleActionError` when the server hasn't advertised any action\n * compatible with the requested policy.\n */\nexport function pickAction(\n requirements: EscrowPaymentRequirements,\n policy?: Policy,\n): BosonCommitActionId {\n const redeemMode = policy?.redeemMode ?? \"auto\";\n\n const flowAOffered = requirements.actions.next.some(\n (a) => a.id === FLOW_A && a.channels.includes(\"server\"),\n );\n const flowBOffered = requirements.actions.next.some(\n (a) => a.id === FLOW_B && a.channels.includes(\"server\"),\n );\n\n if (redeemMode === \"commit-and-redeem\") {\n if (flowBOffered) return FLOW_B;\n throw new NoCompatibleActionError(\n `policy.redeemMode='commit-and-redeem' requires '${FLOW_B}' on the server channel; requirements only advertise [${requirements.actions.next.map((a) => a.id).join(\", \")}]`,\n );\n }\n\n if (redeemMode === \"commit-only\") {\n if (flowAOffered) return FLOW_A;\n throw new NoCompatibleActionError(\n `policy.redeemMode='commit-only' requires '${FLOW_A}' on the server channel; requirements only advertise [${requirements.actions.next.map((a) => a.id).join(\", \")}]`,\n );\n }\n\n // \"auto\": prefer Flow A when present, but fall back to Flow B.\n if (flowAOffered) return FLOW_A;\n if (flowBOffered) return FLOW_B;\n\n throw new NoCompatibleActionError(\n `no commit-time action ('${FLOW_A}' or '${FLOW_B}') with 'server' channel found in requirements.actions.next`,\n );\n}\n","// Resolve the `fulfillment` slot the client will attach to the commit-time\n// payment payload. The buyer's chosen `option` always flows (capability\n// negotiation against the server's advertised set); the `data` field is\n// validated locally against the option's JSON Schema either way so the\n// client fails fast before signing — but whether it travels with the\n// commit-time payload depends on the action the client is signing:\n//\n// - Atomic Flow B (`boson-createOfferCommitAndRedeem`): the commit and\n// on-chain redeem happen in one transaction, so the X-PAYMENT header\n// is the only round trip the buyer makes. `data` MUST be present.\n// - Two-step Flow A (`boson-createOfferAndCommit`): the buyer redeems\n// later via `boson-redeem`'s POST body — `data` is omitted at commit\n// and attached at redeem.\n//\n// The conditional emission lives in the payload assembler (`payload.ts`);\n// this module returns both `option` and `data` and lets the caller decide.\n\nimport Ajv from \"ajv\";\nimport type { EscrowPaymentRequirements } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport { FulfillmentValidationError } from \"./errors.js\";\nimport type { FulfillmentConfig, X402bClientConfig } from \"./types.js\";\n\nexport interface ResolvedFulfillment {\n option: string;\n /**\n * Buyer-supplied delivery data, validated locally against the option's\n * JSON Schema. The payload assembler decides whether to include this\n * field in the commit-time payload (Flow B yes, Flow A no).\n */\n data: Record<string, unknown> | null;\n}\n\n/**\n * Returns the resolved `{ option, data }` pair the assembler will attach\n * to the commit-time fulfillment slot (Flow B) or carry forward for the\n * redeem-time POST body (Flow A). Throws when the requirements demand a\n * fulfillment but the client config doesn't supply one, when the option\n * id isn't advertised by the server, or when the buyer data doesn't\n * validate against the option's schema.\n */\nexport function resolveFulfillment(\n requirements: EscrowPaymentRequirements,\n config: Pick<X402bClientConfig, \"fulfillment\">,\n): ResolvedFulfillment | undefined {\n const required = requirements.fulfillment?.required ?? false;\n if (!required) {\n return undefined;\n }\n\n const fulfillmentConfig: FulfillmentConfig | undefined = config.fulfillment;\n if (!fulfillmentConfig) {\n throw new FulfillmentValidationError(\n \"requirements.fulfillment.required is true but client config did not supply a fulfillment selection\",\n );\n }\n\n const option = requirements.fulfillment?.options.find((o) => o.id === fulfillmentConfig.option);\n if (!option) {\n const advertised = requirements.fulfillment?.options.map((o) => o.id).join(\", \") ?? \"<none>\";\n throw new FulfillmentValidationError(\n `fulfillment option '${fulfillmentConfig.option}' not advertised by requirements (advertised: ${advertised})`,\n );\n }\n\n if (option.schema === null) {\n if (fulfillmentConfig.data !== null) {\n throw new FulfillmentValidationError(\n `fulfillment option '${option.id}' accepts no buyer data; use null`,\n );\n }\n } else {\n const ajv = new Ajv({ allErrors: true, strict: false });\n const validate = ajv.compile(option.schema);\n const ok = validate(fulfillmentConfig.data);\n if (!ok) {\n throw new FulfillmentValidationError(\n `fulfillment data does not match option '${option.id}' schema: ${ajv.errorsText(validate.errors)}`,\n );\n }\n }\n\n return { option: fulfillmentConfig.option, data: fulfillmentConfig.data };\n}\n","// Translator that wraps a `Signer` (plus an optional viem `PublicClient`\n// for read-only RPC calls) into a `Web3LibAdapter` that `CoreSDK` can be\n// constructed against.\n//\n// Two RPC methods are forwarded:\n//\n// - `send(\"eth_signTypedData_v4\", ...)` — buyer signs via `signer.signTypedData`.\n// - `call({ to, data })` — read-only `eth_call`, forwarded to the\n// `PublicClient` when one is configured. Required by the EIP-2612\n// Permit token-auth path, which fetches the token's `nonces(owner)`\n// before signing. Throws a clear error when invoked without a\n// PublicClient so the configuration mistake surfaces fast.\n//\n// Transaction-flavour methods (`sendTransaction`, `estimateGas`,\n// `getBalance`, `getTransactionReceipt`, `getCurrentTimeMs`) reject — the\n// buyer never goes on-chain in MVP.\n\nimport type { Web3LibAdapter } from \"@bosonprotocol/common\";\nimport type { PublicClient, TypedDataDomain, TypedDataParameter } from \"viem\";\n\nimport type { Signer } from \"../types.js\";\n\n/**\n * Build the `Web3LibAdapter` that `@bosonprotocol/core-sdk`'s `CoreSDK`\n * accepts. `send(\"eth_signTypedData_v4\", [address, jsonString])` delegates\n * to `signer.signTypedData(...)`. `call({ to, data })` is forwarded to\n * `publicClient.call(...)` when one is provided; otherwise it throws (the\n * Permit strategy is the only path that exercises `call`).\n */\nexport function signerToWeb3LibAdapter(\n signer: Signer,\n chainId: number,\n publicClient?: PublicClient,\n): Web3LibAdapter {\n return {\n uuid: \"x402-client:signer-adapter\",\n getSignerAddress: () => signer.getAddress(),\n isSignerContract: async () => false,\n getChainId: async () => chainId,\n send: async (method, params) => {\n if (method !== \"eth_signTypedData_v4\") {\n throw new Error(\n `x402-client: signer adapter does not support RPC method '${method}'; only eth_signTypedData_v4 is implemented`,\n );\n }\n const raw = (params as unknown[])[1];\n if (typeof raw !== \"string\") {\n throw new Error(\n \"x402-client: eth_signTypedData_v4 payload[1] is not a JSON string — core-sdk internals may have changed\",\n );\n }\n const typedData = JSON.parse(raw) as {\n domain: TypedDataDomain;\n types: Record<string, readonly TypedDataParameter[]>;\n primaryType: string;\n message: Record<string, unknown>;\n };\n return signer.signTypedData(typedData);\n },\n call: async (req) => {\n if (!publicClient) {\n throw new Error(\n \"x402-client: signer adapter has no PublicClient configured; eth_call cannot be forwarded. \" +\n \"Pass `publicClients` in X402bClientConfig to enable the Permit token-auth strategy.\",\n );\n }\n const result = await publicClient.call({\n to: req.to as `0x${string}`,\n data: req.data as `0x${string}` | undefined,\n });\n return result.data ?? \"0x\";\n },\n getBalance: () => Promise.reject(unreachable(\"getBalance\")),\n estimateGas: () => Promise.reject(unreachable(\"estimateGas\")),\n sendTransaction: () => Promise.reject(unreachable(\"sendTransaction\")),\n getTransactionReceipt: () => Promise.reject(unreachable(\"getTransactionReceipt\")),\n getCurrentTimeMs: () => Promise.reject(unreachable(\"getCurrentTimeMs\")),\n };\n}\n\nfunction unreachable(method: string): Error {\n return new Error(\n `x402-client: stub Web3LibAdapter.${method}() is not implemented — the client never goes on-chain in MVP`,\n );\n}\n","// Construct (and cache) the `CoreSDK` instance the client signs through.\n//\n// The buyer never queries Boson's subgraph in MVP — only the EIP-712 meta-tx\n// signing path is invoked — but `CoreSDK`'s base constructor requires a\n// `subgraphUrl` string. Callers can configure real URLs per chain via\n// `subgraphUrls`, or omit it and rely on the placeholder sentinel below;\n// either way no HTTP call to that URL is made during signing.\n\nimport { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { Address } from \"viem\";\n\nimport { signerToWeb3LibAdapter } from \"./internal/web3lib-adapter.js\";\nimport type { Signer, X402bClientConfig } from \"./types.js\";\n\n// Sentinel used when the caller did not configure a real subgraph URL for\n// the chain. The signing path never reads from it; the value just needs to\n// be a non-empty string the constructor accepts.\nconst PLACEHOLDER_SUBGRAPH_URL = \"https://x402-client.placeholder.invalid/subgraph\";\n\nexport interface CoreSdkContext {\n coreSdk: CoreSDK;\n chainId: number;\n}\n\n/**\n * Parse a CAIP-2 EVM network identifier (e.g. `\"eip155:8453\"`) into its\n * numeric chain id. Throws if the network is not a well-formed `eip155:<N>`.\n */\nexport function parseChainId(network: string): number {\n const match = network.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `x402-client: unsupported network '${network}' (expected CAIP-2 'eip155:<chainId>')`,\n );\n }\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n throw new Error(\n `x402-client: unsupported network '${network}' (chainId must be a positive safe integer)`,\n );\n }\n return chainId;\n}\n\n/**\n * Lazy factory that returns a `CoreSDK` instance configured against the\n * escrow contract advertised in the network. Instances are cached per\n * `(chainId, escrowAddress)` so repeated calls on the same network — for\n * commit and subsequent post-commit actions on the same exchange — reuse a\n * single SDK.\n *\n * The SDK's `web3Lib.call(...)` is wired through `config.publicClients[chainId]`\n * when one is configured; this enables read-only RPC reads (e.g. the EIP-2612\n * Permit strategy's `nonces(owner)` lookup). Chains without a PublicClient\n * configured can still sign meta-transactions and ERC-3009 / Permit2\n * token-auths.\n */\nexport function createCoreSdkFactory(\n signer: Signer,\n config: Pick<X402bClientConfig, \"subgraphUrls\" | \"publicClients\">,\n) {\n const cache = new Map<string, CoreSDK>();\n\n return function buildCoreSdk(network: string, escrowAddress: Address): CoreSdkContext {\n const chainId = parseChainId(network);\n const cacheKey = `${chainId}:${escrowAddress.toLowerCase()}`;\n const cached = cache.get(cacheKey);\n if (cached) {\n return { coreSdk: cached, chainId };\n }\n\n const subgraphUrl = config.subgraphUrls?.[chainId] ?? PLACEHOLDER_SUBGRAPH_URL;\n const publicClient = config.publicClients?.[chainId];\n const web3Lib = signerToWeb3LibAdapter(signer, chainId, publicClient);\n\n const coreSdk = new CoreSDK({\n web3Lib,\n subgraphUrl,\n protocolDiamond: escrowAddress,\n chainId,\n });\n\n cache.set(cacheKey, coreSdk);\n return { coreSdk, chainId };\n };\n}\n","// Parse the optional `X-PAYMENT-RESPONSE` header the server may emit after\n// settling.\n//\n// The escrow-scheme spec doesn't pin a strict contract for this header yet,\n// so the parser is permissive: base64-decode the value, JSON-parse it, and\n// return `{ raw }`. Best-effort lifting picks `exchangeId` / `state` from\n// the common property paths an x402B server might use. Callers who need\n// stronger guarantees can read `raw` directly.\n\nimport type { ExchangeSummary } from \"./types.js\";\n\nconst HEADER_NAME = \"X-PAYMENT-RESPONSE\";\n\n/** Read a header value from anything that exposes `.get(name)`. */\ninterface HeaderLike {\n get(name: string): string | null;\n}\n\ninterface ResponseLike {\n headers: HeaderLike;\n}\n\n/**\n * Decode the `X-PAYMENT-RESPONSE` header on a Response-like object. Returns\n * `undefined` when the header isn't set; throws on a malformed payload.\n */\nexport function parsePaymentResponse(response: ResponseLike): ExchangeSummary | undefined {\n const raw = response.headers.get(HEADER_NAME);\n if (!raw) {\n return undefined;\n }\n\n const json = decodeBase64(raw);\n const parsed: unknown = JSON.parse(json);\n const summary: ExchangeSummary = { raw: parsed };\n\n // Only walk into the payload when it's actually a plain record. A valid\n // JSON value can be `null`, an array, or a primitive — touching keys on\n // those would crash, defeating the file-header permissive promise.\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n const obj = parsed as Record<string, unknown>;\n\n const exchangeId = pickString(obj, [\"exchangeId\", \"exchange_id\"]);\n if (exchangeId !== undefined) {\n summary.exchangeId = exchangeId;\n }\n\n if (isClientStateShape(obj.state)) {\n summary.state = obj.state;\n }\n\n // Fallback for the server-emitted shape, which carries exchange state\n // under `nextActions.exchangeState` (and optionally `disputeState`)\n // rather than a top-level `state` field. The top-level lookup above\n // still wins when present, preserving forward-compat with external\n // servers that publish the flatter shape.\n if (\n summary.state === undefined &&\n typeof obj.nextActions === \"object\" &&\n obj.nextActions !== null &&\n !Array.isArray(obj.nextActions)\n ) {\n const na = obj.nextActions as Record<string, unknown>;\n const exchange = pickString(na, [\"exchangeState\"]);\n const dispute = pickString(na, [\"disputeState\"]);\n if (exchange !== undefined) {\n let candidate: unknown;\n if (exchange === \"DISPUTED\") {\n candidate = dispute !== undefined ? { exchange, dispute } : undefined;\n } else {\n candidate = { exchange };\n }\n if (isClientStateShape(candidate)) {\n summary.state = candidate;\n }\n }\n }\n }\n\n return summary;\n}\n\n/**\n * Shape gate for `state` arriving from the permissive server header. We\n * keep the file-header promise of permissiveness — `ClientState` is\n * `\"PRE_COMMIT\"` or an `{ exchange, dispute? }` record today, but the\n * wire contract isn't pinned, so any non-empty string (e.g. raw\n * `ExchangeState` value) or non-array `{ exchange }`-shaped record is\n * surfaced verbatim. Numbers, booleans, `null`, empty strings, arrays,\n * and records missing a string `exchange` field are rejected so garbage\n * payloads can't masquerade as a typed `ClientState`.\n */\nfunction isClientStateShape(v: unknown): v is NonNullable<ExchangeSummary[\"state\"]> {\n if (typeof v === \"string\") return v.length > 0;\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n const rec = v as Record<string, unknown>;\n if (typeof rec.exchange !== \"string\" || rec.exchange.length === 0) return false;\n if (\"dispute\" in rec && rec.dispute !== undefined && typeof rec.dispute !== \"string\") {\n return false;\n }\n return true;\n}\n\nfunction decodeBase64(value: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(value, \"base64\").toString(\"utf8\");\n }\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n\nfunction pickString(obj: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const v = obj[key];\n if (typeof v === \"string\" && v.length > 0) {\n return v;\n }\n }\n return undefined;\n}\n","// Assemble the X-PAYMENT body and base64-encode it.\n//\n// Defense-in-depth: the assembled `EscrowPaymentPayload` is re-validated\n// through `parseEscrowPaymentPayload` from `@bosonprotocol/x402-core`\n// before serialization, so shape bugs surface here instead of at the\n// server. Base64 encoding picks `Buffer` on Node and `btoa` on browser\n// targets — tsup builds both, so the runtime branch matters.\n\nimport {\n parseEscrowPaymentPayload,\n type BosonMetaTx,\n type BosonTokenAuth,\n type EscrowPaymentPayload,\n type EscrowPaymentRequirements,\n type TokenAuthStrategy,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address } from \"viem\";\n\nimport type { ResolvedFulfillment } from \"./fulfillment.js\";\n\n/** Current x402 protocol version embedded in the payload envelope. */\nexport const X402_VERSION = 2;\n\nexport interface AssembleArgs {\n requirements: EscrowPaymentRequirements;\n action: string;\n tokenAuthStrategy: TokenAuthStrategy;\n metaTx: BosonMetaTx;\n tokenAuth?: BosonTokenAuth;\n fulfillment?: ResolvedFulfillment;\n buyer: Address;\n}\n\n/** Construct and re-validate the payload, returning the structured object. */\nexport function assemblePayload({\n requirements,\n action,\n tokenAuthStrategy,\n metaTx,\n tokenAuth,\n fulfillment,\n buyer,\n}: AssembleArgs): EscrowPaymentPayload {\n // Fulfillment `data` rides along only for atomic Flow B — Flow A\n // defers it to the redeem POST body. The conditional emission keeps\n // the assembler aligned with the server-side rule-13 validator that\n // rejects `data` on Flow A and requires it on Flow B.\n const fulfillmentSlot =\n fulfillment === undefined\n ? undefined\n : action === \"boson-createOfferCommitAndRedeem\"\n ? { option: fulfillment.option, data: fulfillment.data }\n : { option: fulfillment.option };\n\n const payload: EscrowPaymentPayload = {\n x402Version: X402_VERSION,\n scheme: \"escrow\",\n network: requirements.network,\n payload: {\n action,\n tokenAuthStrategy,\n offerRef: {\n fullOffer: requirements.offer.fullOffer,\n sellerSig: requirements.offer.sellerSig,\n },\n buyer,\n metaTx,\n ...(tokenAuth ? { tokenAuth } : {}),\n },\n ...(fulfillmentSlot ? { fulfillment: fulfillmentSlot } : {}),\n };\n\n // Defensive re-parse — surfaces shape bugs (e.g. malformed hex) before\n // the payload escapes the client.\n parseEscrowPaymentPayload(payload);\n return payload;\n}\n\n/** Build, validate, and base64-encode the payload for the `X-PAYMENT` header. */\nexport function assembleAndEncodePayload(args: AssembleArgs): string {\n const payload = assemblePayload(args);\n const json = JSON.stringify(payload);\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(json, \"utf8\").toString(\"base64\");\n }\n // Browser fallback. Wire payloads mostly carry hex/numeric strings,\n // but atomic Flow B's `fulfillment.data` is a `Record<string, unknown>`\n // the buyer populates — emails, addresses, free-form notes. `btoa`\n // accepts only a binary string (code units 0–255) and throws\n // `InvalidCharacterError` on any character above U+00FF. UTF-8 encode\n // the JSON first, then map the bytes into the binary-string form\n // `btoa` expects.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary);\n}\n","// Cross-platform random helpers.\n//\n// The client is framework-agnostic: it must run in browsers (where\n// `node:crypto` is unavailable) as well as Node. The Web Crypto API\n// (`globalThis.crypto.getRandomValues`) covers both — it's been a Node\n// global since 19 and is universally available in modern browsers.\n// The package's `engines.node` already requires Node ≥ 22, so we can\n// rely on the global without a `node:crypto` fallback.\n//\n// Centralizing the helpers here keeps `pre-commit.ts`, `post-commit.ts`,\n// and `token-auth/erc3009.ts` from each importing their own crypto\n// primitive and re-deriving the same byte → bigint / byte → hex\n// conversion (CLAUDE.md \"Move duplicated constants ... into a shared\n// file the moment they appear in two places\").\n\nimport type { Hex } from \"viem\";\n\n/** Fill a fresh `Uint8Array` of `size` bytes with cryptographically random bytes. */\nexport function randomBytes(size: number): Uint8Array {\n const bytes = new Uint8Array(size);\n if (typeof globalThis.crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"x402-client: globalThis.crypto.getRandomValues is unavailable — environment lacks the Web Crypto API\",\n );\n }\n globalThis.crypto.getRandomValues(bytes);\n return bytes;\n}\n\n/** 32-byte cryptographically random `0x`-prefixed hex string. */\nexport function randomBytes32(): Hex {\n const bytes = randomBytes(32);\n let hex = \"0x\";\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, \"0\");\n }\n return hex as Hex;\n}\n\n/** Cryptographically random `uint256`. Used for protocol meta-tx replay-protection nonces. */\nexport function randomUint256(): bigint {\n const bytes = randomBytes(32);\n let n = 0n;\n for (const byte of bytes) {\n n = (n << 8n) | BigInt(byte);\n }\n return n;\n}\n","// Sign the buyer's Boson protocol meta-transaction for one of the two\n// commit-time actions:\n//\n// - Flow A — `boson-createOfferAndCommit` (deferred redeem). Signed via\n// `coreSdk.signMetaTxCreateOfferAndCommit`.\n// - Flow B — `boson-createOfferCommitAndRedeem` (atomic commit+redeem\n// via `OrchestrationHandlerFacet2.createOfferCommitAndRedeem`). Signed\n// via `coreSdk.signMetaTxCreateOfferCommitAndRedeem`.\n//\n// Both route through `CoreSDK` directly so the EIP-712 domain, function\n// signature, and calldata encoding stay in lock-step with the deployed\n// protocol. The returned `SignedMetaTx` is shaped exactly as the on-chain\n// `MetaTransactionsHandlerFacet` recovers against; we re-shape it into\n// the escrow scheme's wire-format `BosonMetaTx` for the X-PAYMENT payload.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { FullOfferArgs } from \"@bosonprotocol/common\";\nimport type {\n BosonMetaTx,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\nexport interface SignCreateOfferAndCommitArgs {\n requirements: EscrowPaymentRequirements;\n coreSdk: CoreSDK;\n buyer: Address;\n}\n\n/**\n * Builds the buyer-side meta-tx for `createOfferAndCommit`, signs it via\n * `CoreSDK`, and returns the wire-format envelope ready to be embedded in\n * an `EscrowPaymentPayload`.\n *\n * The `createOfferAndCommitArgs` are reconstructed from the\n * `requirements.offer` triple — the opaque `fullOffer` carries the\n * `Omit<FullOfferArgs, \"signature\">` shape, `sellerSig` becomes the\n * `signature`, and the buyer's address is spliced in as `committer`. Any\n * shape drift between the wire format and `FullOfferArgs` surfaces as a\n * yup validation error from core-sdk's\n * `createOfferAndCommitArgsSchema.validateSync` — propagate it rather than\n * patch silently (CLAUDE.md \"Production over spec when they diverge\").\n */\nexport async function signCreateOfferAndCommit({\n requirements,\n coreSdk,\n buyer,\n}: SignCreateOfferAndCommitArgs): Promise<BosonMetaTx> {\n const nonce = randomUint256();\n\n const createOfferAndCommitArgs = buildCreateOfferAndCommitArgs(requirements, buyer);\n\n const signed = await coreSdk.signMetaTxCreateOfferAndCommit({\n nonce: nonce.toString(),\n createOfferAndCommitArgs,\n });\n\n return reshape(signed, buyer, nonce);\n}\n\n/**\n * Flow B counterpart to {@link signCreateOfferAndCommit} — signs\n * the meta-tx that drives `OrchestrationHandlerFacet2.createOfferCommitAndRedeem`.\n * The argument shape is identical (the protocol uses the same\n * `FullOfferArgs` struct); only the resulting function selector and\n * post-state differ.\n */\nexport async function signCreateOfferCommitAndRedeem({\n requirements,\n coreSdk,\n buyer,\n}: SignCreateOfferAndCommitArgs): Promise<BosonMetaTx> {\n const nonce = randomUint256();\n\n const createOfferAndCommitArgs = buildCreateOfferAndCommitArgs(requirements, buyer);\n\n const signed = await coreSdk.signMetaTxCreateOfferCommitAndRedeem({\n nonce: nonce.toString(),\n createOfferAndCommitArgs,\n });\n\n return reshape(signed, buyer, nonce);\n}\n\nfunction buildCreateOfferAndCommitArgs(\n requirements: EscrowPaymentRequirements,\n buyer: Address,\n): FullOfferArgs {\n return {\n ...(requirements.offer.fullOffer as object),\n signature: requirements.offer.sellerSig,\n committer: buyer,\n } as unknown as FullOfferArgs;\n}\n\nfunction reshape(\n signed: {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n },\n buyer: Address,\n nonce: bigint,\n): BosonMetaTx {\n return {\n from: buyer,\n nonce: nonce.toString(),\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n}\n","// Sign Boson protocol meta-transactions for post-commit buyer actions.\n//\n// These are the transitions the buyer can drive once an exchange exists on\n// chain: redeem the voucher, cancel/complete the exchange, or move through\n// the dispute family. Each is a single-call meta-tx that the\n// server/facilitator submits via\n// `MetaTransactionsHandlerFacet.executeMetaTransaction`. None of them\n// carry a token-auth payload (the funds are already escrowed) so the\n// returned `BosonMetaTx` is the full wire-format the server consumes —\n// usually as a JSON POST body, not an `X-PAYMENT` header.\n//\n// We return both the `BosonMetaTx` envelope (useful for on-chain or MCP\n// channels) and the ABI-encoded `signedPayload` Hex consumed by the\n// server/facilitator HTTP convenience routes. The encoder lives in\n// `@bosonprotocol/x402-evm/codec` so client and facilitator share one\n// implementation.\n//\n// `boson-escalateDispute` is the one exception. If the dispute resolver\n// requires an escalation deposit, the resolver/server can return its own\n// 402 carrying an `escrow` `PaymentRequirements` and the buyer pairs this\n// meta-tx with a token-auth payload — that wrapper lives outside MVP. Here\n// we only sign the meta-tx itself; the deposit flow is a later PR.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { BosonMetaTx, Hex as WireHex } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { ActionId } from \"@bosonprotocol/x402-core/state-machine\";\nimport { encodeSignedPayload } from \"@bosonprotocol/x402-evm/codec\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\n// Matches the subset of ethers' `BigNumberish` core-sdk actually accepts at\n// runtime, without pulling `@ethersproject/bignumber` into this package's\n// declared deps. Callers usually pass decimal strings (the wire format).\ntype BigNumberish = string | number | bigint;\n\n/**\n * Buyer-invokable post-commit action ids — derived from `ActionId` in\n * `@bosonprotocol/x402-core/state-machine` (the single source of truth)\n * by excluding:\n *\n * - the commit-time ids, which the buyer signs via `handle402`;\n * - `boson-revokeVoucher`, which is seller-only;\n * - entity-keyed actions (`boson-withdrawFunds`), which are signed via\n * `client.signWithdrawFunds` / `client.signWithdrawAllAvailableFunds`\n * because they take an `entityId` + token list rather than an\n * `exchangeId`.\n */\ntype BuyerPostCommitActionId = Exclude<\n ActionId,\n | \"boson-createOfferAndCommit\"\n | \"boson-createOfferCommitAndRedeem\"\n | \"boson-revokeVoucher\"\n | \"boson-withdrawFunds\"\n>;\n\n/** Caller-supplied arguments for `client.signAction`. */\nexport type SignActionArgs = SimplePostCommitArgs | ResolveDisputeArgs;\n\ninterface BaseArgs {\n exchangeId: BigNumberish;\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address (the `escrowAddress` from the prior 402). */\n escrowAddress: Address;\n}\n\nexport interface SimplePostCommitArgs extends BaseArgs {\n actionId: Exclude<BuyerPostCommitActionId, \"boson-resolveDispute\">;\n}\n\nexport interface ResolveDisputeArgs extends BaseArgs {\n actionId: \"boson-resolveDispute\";\n /** Buyer share of the disputed amount, in the units the protocol expects (basis points). */\n buyerPercent: BigNumberish;\n /** Counterparty (seller) signature over the proposal. Hex string or `{r, s, v}`. */\n counterpartySig: Hex | { r: Hex; s: Hex; v: number };\n}\n\nexport interface SignPostCommitActionDeps {\n buildCoreSdk: (network: string, escrowAddress: Address) => { coreSdk: CoreSDK; chainId: number };\n getBuyerAddress: () => Promise<Address>;\n}\n\n/**\n * Wire-format result of `signPostCommitAction`: the signed `BosonMetaTx`\n * envelope plus its ABI-encoded `signedPayload` Hex. Pick the one that\n * matches the channel — the server/facilitator HTTP routes consume\n * `signedPayload`; direct on-chain or MCP submissions use `metaTx`.\n */\nexport interface SignedPostCommitAction {\n metaTx: BosonMetaTx;\n /**\n * ABI-encoded `BosonMetaTx` ready to drop into a server / facilitator\n * route's `signedPayload` field. The hex is JSON-serialisable; we type\n * it as the loose wire `Hex` (string) rather than viem's strict\n * `\\`0x\\${string}\\`` so the codec's output matches the schemes module's\n * own `Hex` alias.\n */\n signedPayload: WireHex;\n}\n\n/**\n * Sign a post-commit action through the appropriate `CoreSDK.signMetaTx*`\n * mixin method. Returns both the wire-format `BosonMetaTx` envelope and\n * the ABI-encoded `signedPayload` Hex ready to POST to a server /\n * facilitator route.\n */\nexport async function signPostCommitAction(\n args: SignActionArgs,\n deps: SignPostCommitActionDeps,\n): Promise<SignedPostCommitAction> {\n const nonce = randomUint256();\n const buyer = await deps.getBuyerAddress();\n const { coreSdk } = deps.buildCoreSdk(args.network, args.escrowAddress);\n\n const signed = await callSignMetaTx(coreSdk, args, nonce);\n\n const metaTx: BosonMetaTx = {\n from: buyer,\n nonce: nonce.toString(),\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n\n return { metaTx, signedPayload: encodeSignedPayload(metaTx) };\n}\n\ninterface SignedMetaTxShape {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n}\n\nasync function callSignMetaTx(\n coreSdk: CoreSDK,\n args: SignActionArgs,\n nonce: bigint,\n): Promise<SignedMetaTxShape> {\n const nonceStr = nonce.toString();\n const exchangeId = args.exchangeId;\n\n switch (args.actionId) {\n case \"boson-redeem\":\n return coreSdk.signMetaTxRedeemVoucher({ nonce: nonceStr, exchangeId });\n case \"boson-cancelVoucher\":\n return coreSdk.signMetaTxCancelVoucher({ nonce: nonceStr, exchangeId });\n case \"boson-completeExchange\":\n return coreSdk.signMetaTxCompleteExchange({ nonce: nonceStr, exchangeId });\n case \"boson-raiseDispute\":\n return coreSdk.signMetaTxRaiseDispute({ nonce: nonceStr, exchangeId });\n case \"boson-retractDispute\":\n return coreSdk.signMetaTxRetractDispute({ nonce: nonceStr, exchangeId });\n case \"boson-escalateDispute\":\n return coreSdk.signMetaTxEscalateDispute({ nonce: nonceStr, exchangeId });\n case \"boson-resolveDispute\":\n return coreSdk.signMetaTxResolveDispute({\n nonce: nonceStr,\n exchangeId,\n buyerPercent: args.buyerPercent,\n counterpartySig: args.counterpartySig,\n });\n default: {\n // The discriminated union makes this unreachable at the type level;\n // the `never` annotation enforces exhaustiveness at compile time, and\n // the throw guarantees a clear error if a runtime value ever slips\n // past the type checker.\n const _exhaustive: never = args;\n throw new Error(\n `x402-client: unsupported post-commit action '${(_exhaustive as { actionId: string }).actionId}'`,\n );\n }\n }\n}\n","// Sign Boson protocol meta-transactions for the entity-keyed\n// `boson-withdrawFunds` action.\n//\n// Unlike the buyer-side post-commit signers, withdraw is keyed by the\n// Boson account `entityId` (buyer or seller) rather than an exchange\n// id. The on-chain primitive is\n// `FundsHandlerFacet.withdrawFunds(uint256 entityId, address[] tokenList,\n// uint256[] tokenAmounts)`. The meta-tx variant\n// (`coreSdk.signMetaTxWithdrawFunds`) wraps that calldata in an EIP-712\n// envelope ready for `MetaTransactionsHandlerFacet.executeMetaTransaction`.\n//\n// Scope cap for v1: callers withdraw the *whole* current balance set.\n// `signWithdrawAllAvailableFunds` reads the funds entity from the\n// subgraph, drops zero balances, then delegates to `signWithdrawFunds`\n// for the actual EIP-712 sign. Partial / user-chosen amounts can be\n// added later without a wire-format change.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport {\n DECIMAL_UINT,\n type BosonMetaTx,\n type Hex as WireHex,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport { encodeSignedPayload } from \"@bosonprotocol/x402-evm/codec\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\n// Matches the subset of ethers' `BigNumberish` core-sdk actually accepts at\n// runtime, without pulling `@ethersproject/bignumber` into this package's\n// declared deps. Callers usually pass decimal strings (the wire format).\ntype BigNumberish = string | number | bigint;\n\n/**\n * Coerce a caller-supplied `entityId` to its canonical wire form (a\n * non-negative integer decimal string). Rejects NaN, fractional, and\n * negative values up-front — passing them on to core-sdk would either\n * trip a downstream BigInt conversion or, worse, produce a signed\n * payload that always reverts on-chain.\n */\nfunction normalizeEntityId(value: BigNumberish): string {\n if (typeof value === \"bigint\") {\n if (value < 0n) throw new Error(`entityId must be non-negative, got ${value.toString()}`);\n return value.toString();\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n throw new Error(`entityId must be a non-negative integer, got ${String(value)}`);\n }\n return value.toString();\n }\n // typeof value === \"string\"\n const trimmed = value.trim();\n if (trimmed.length === 0 || !DECIMAL_UINT.test(trimmed)) {\n throw new Error(`entityId must be a decimal non-negative integer string, got \"${value}\"`);\n }\n return trimmed;\n}\n\n/**\n * Resolution targets accepted by the \"withdraw all\" helper. Either\n * pass the raw `entityId` (numeric Boson account id) or an EVM\n * `address` with an optional `role` discriminator for the case where\n * the address maps to both a seller and a buyer entity.\n */\nexport type WithdrawEntitySelector =\n | { entityId: BigNumberish }\n | { address: Address; role?: \"buyer\" | \"seller\" };\n\n/** Arguments accepted by `signWithdrawFunds` (caller-resolved entity + token list). */\nexport interface SignWithdrawFundsArgs {\n entityId: BigNumberish;\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address (the `escrowAddress` from the prior 402). */\n escrowAddress: Address;\n /** Token addresses to withdraw — must align by index with `tokenAmounts`. */\n tokenList: readonly Address[];\n /** Amounts to withdraw — must align by index with `tokenList`. */\n tokenAmounts: readonly BigNumberish[];\n}\n\n/** Arguments accepted by `signWithdrawAllAvailableFunds` — entity + network only. */\nexport type SignWithdrawAllAvailableFundsArgs = WithdrawEntitySelector & {\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address. */\n escrowAddress: Address;\n};\n\n/** Wire-format result identical in shape to `SignedPostCommitAction`. */\nexport interface SignedWithdrawFunds {\n metaTx: BosonMetaTx;\n signedPayload: WireHex;\n /** Resolved `entityId` (echoed back for caller convenience when looked up by address). */\n entityId: string;\n /** Tokens included in the signature, in calldata order. */\n tokenList: readonly Address[];\n /** Amounts included in the signature, in calldata order. */\n tokenAmounts: readonly string[];\n}\n\nexport interface SignWithdrawDeps {\n buildCoreSdk: (network: string, escrowAddress: Address) => { coreSdk: CoreSDK; chainId: number };\n /** Returns the address that will sign the meta-tx — must match the configured signer. */\n getSignerAddress: () => Promise<Address>;\n}\n\ninterface SignedMetaTxShape {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n}\n\n/** Subset of `CoreSDK` used here — kept narrow so tests can stub easily. */\ninterface WithdrawCoreSdkLike {\n signMetaTxWithdrawFunds(args: {\n nonce: string;\n entityId: BigNumberish;\n tokenList: string[];\n tokenAmounts: BigNumberish[];\n }): Promise<SignedMetaTxShape>;\n getFunds(queryVars: { fundsFilter: { accountId: string } }): Promise<\n Array<{\n accountId: string;\n availableAmount: string;\n token: { address: string };\n }>\n >;\n getSellersByAddress(address: string): Promise<Array<{ id: string }>>;\n getBuyers(queryVars: { buyersFilter: { wallet: string } }): Promise<Array<{ id: string }>>;\n}\n\n/**\n * Sign a `withdrawFunds(entityId, tokenList, tokenAmounts)` meta-tx\n * against the configured Diamond domain. The caller supplies the\n * exact token + amount snapshot to commit to.\n */\nexport async function signWithdrawFunds(\n args: SignWithdrawFundsArgs,\n deps: SignWithdrawDeps,\n): Promise<SignedWithdrawFunds> {\n const normalised: SignWithdrawFundsArgs = {\n ...args,\n entityId: normalizeEntityId(args.entityId),\n };\n const { coreSdk } = deps.buildCoreSdk(normalised.network, normalised.escrowAddress);\n const from = await deps.getSignerAddress();\n return signWithdrawFundsInternal(normalised, coreSdk as unknown as WithdrawCoreSdkLike, from);\n}\n\n/**\n * \"Withdraw all\" sugar. Resolves the entity (by id or by address),\n * reads the funds entity from the subgraph, drops zero balances, and\n * signs `withdrawFunds(entityId, allTokens, allAmounts)`. Throws when\n * the entity has no available funds.\n */\nexport async function signWithdrawAllAvailableFunds(\n args: SignWithdrawAllAvailableFundsArgs,\n deps: SignWithdrawDeps,\n): Promise<SignedWithdrawFunds> {\n const { coreSdk } = deps.buildCoreSdk(args.network, args.escrowAddress);\n const sdk = coreSdk as unknown as WithdrawCoreSdkLike;\n const from = await deps.getSignerAddress();\n const entityId = await resolveEntityIdClientSide(sdk, args);\n const funds = await sdk.getFunds({ fundsFilter: { accountId: entityId } });\n const nonZero = funds.filter((f) => f.availableAmount !== \"0\" && BigInt(f.availableAmount) > 0n);\n if (nonZero.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: entity ${entityId} has no available funds to withdraw`,\n );\n }\n return signWithdrawFundsInternal(\n {\n entityId,\n network: args.network,\n escrowAddress: args.escrowAddress,\n tokenList: nonZero.map((f) => f.token.address as Address),\n tokenAmounts: nonZero.map((f) => f.availableAmount),\n },\n sdk,\n from,\n );\n}\n\nasync function signWithdrawFundsInternal(\n args: SignWithdrawFundsArgs,\n coreSdk: WithdrawCoreSdkLike,\n from: Address,\n): Promise<SignedWithdrawFunds> {\n if (args.tokenList.length !== args.tokenAmounts.length) {\n throw new Error(\n `signWithdrawFunds: tokenList (${args.tokenList.length}) and tokenAmounts (${args.tokenAmounts.length}) must be the same length`,\n );\n }\n const nonce = randomUint256();\n const nonceStr = nonce.toString();\n const signed = await coreSdk.signMetaTxWithdrawFunds({\n nonce: nonceStr,\n entityId: args.entityId,\n tokenList: args.tokenList.map((t) => t),\n tokenAmounts: args.tokenAmounts.map((a) => a),\n });\n\n const metaTx: BosonMetaTx = {\n from,\n nonce: nonceStr,\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n\n return {\n metaTx,\n signedPayload: encodeSignedPayload(metaTx),\n entityId: normalizeEntityId(args.entityId),\n tokenList: args.tokenList,\n tokenAmounts: args.tokenAmounts.map((a) => String(a)),\n };\n}\n\nasync function resolveEntityIdClientSide(\n coreSdk: WithdrawCoreSdkLike,\n selector: WithdrawEntitySelector,\n): Promise<string> {\n if (\"entityId\" in selector) return normalizeEntityId(selector.entityId);\n const address = selector.address.toLowerCase();\n const role = selector.role;\n const [sellers, buyers] = await Promise.all([\n role === \"buyer\"\n ? Promise.resolve<Array<{ id: string }>>([])\n : coreSdk.getSellersByAddress(address),\n role === \"seller\"\n ? Promise.resolve<Array<{ id: string }>>([])\n : coreSdk.getBuyers({ buyersFilter: { wallet: address } }),\n ]);\n const sellerIds = sellers.map((s) => s.id);\n const buyerIds = buyers.map((b) => b.id);\n\n if (role === \"seller\") {\n if (sellerIds.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no seller entity found for address ${address}`,\n );\n }\n if (sellerIds.length > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to multiple seller entities (ids ${sellerIds.join(\", \")}); pass entityId to disambiguate`,\n );\n }\n return sellerIds[0]!;\n }\n if (role === \"buyer\") {\n if (buyerIds.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no buyer entity found for address ${address}`,\n );\n }\n if (buyerIds.length > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to multiple buyer entities (ids ${buyerIds.join(\", \")}); pass entityId to disambiguate`,\n );\n }\n return buyerIds[0]!;\n }\n\n // role unspecified — exactly-one rule across both sides. Refuse to\n // guess when the address resolves to multiple sellers, multiple\n // buyers, or any combination of the two: the signed payload commits\n // to a single entityId, so silently picking `[0]` would be a bug\n // farm waiting to bite.\n const totalMatches = sellerIds.length + buyerIds.length;\n if (totalMatches === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no seller or buyer entity found for address ${address}`,\n );\n }\n if (totalMatches > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to ${describeClientMatches(sellerIds, buyerIds)}; pass role and/or entityId to disambiguate`,\n );\n }\n if (sellerIds.length === 1) return sellerIds[0]!;\n return buyerIds[0]!;\n}\n\nfunction describeClientMatches(sellerIds: string[], buyerIds: string[]): string {\n const parts: string[] = [];\n if (sellerIds.length > 0) {\n parts.push(\n sellerIds.length === 1\n ? `seller (id ${sellerIds[0]})`\n : `${sellerIds.length} sellers (ids ${sellerIds.join(\", \")})`,\n );\n }\n if (buyerIds.length > 0) {\n parts.push(\n buyerIds.length === 1\n ? `buyer (id ${buyerIds[0]})`\n : `${buyerIds.length} buyers (ids ${buyerIds.join(\", \")})`,\n );\n }\n return parts.join(\" and \");\n}\n","// Client-side deadline for token-auth signatures (ERC-3009 `validBefore`,\n// EIP-2612 `deadline`, Permit2 `deadline`).\n//\n// The facilitator validates strictly: `deadline − facilitatorNow ≤\n// requirements.maxTimeoutSeconds`. If the client signs at the boundary\n// (`floor(clientNow) + maxTimeoutSeconds`), any moment where the\n// verifier's wall-clock lags the signer's by ≥ 1 s pushes the gap\n// over `maxTimeoutSeconds` and the facilitator rejects with\n// BAD_TOKEN_AUTH_SIGNATURE. Docker Desktop's container clock drifting\n// behind the host clock makes this happen randomly in the e2e suite.\n//\n// We pull the deadline closer to `clientNow` by a small margin so the\n// facilitator's check tolerates that backward skew. 60 s comfortably\n// covers Docker drift and leaves a useful validity window even at the\n// spec's example `maxTimeoutSeconds = 300`.\n\nexport const TOKEN_AUTH_DEADLINE_SAFETY_MARGIN_SECONDS = 60;\n\nexport function computeTokenAuthDeadline(\n maxTimeoutSeconds: number,\n now: () => number = Date.now,\n): number {\n // Clamp so the margin can never make the deadline retroactive — if\n // the caller's `maxTimeoutSeconds < 60`, subtracting the full margin\n // would emit an already-expired signature.\n const timeoutSeconds = Math.max(1, Math.floor(maxTimeoutSeconds));\n const safetyMarginSeconds = Math.min(\n TOKEN_AUTH_DEADLINE_SAFETY_MARGIN_SECONDS,\n Math.max(0, timeoutSeconds - 1),\n );\n return Math.floor(now() / 1000) + timeoutSeconds - safetyMarginSeconds;\n}\n","// Build and sign the buyer's ERC-3009 `ReceiveWithAuthorization` for the\n// escrow contract via `CoreSDK.signReceiveWithErc3009Authorization`.\n//\n// The SDK generates a 32-byte random nonce internally, builds the EIP-712\n// typed-data against the token's domain (taken from `tokenDomainResolver`),\n// signs through the configured `Web3LibAdapter`, and returns a\n// `TransferAuthorization` with `{ strategy, data: { validAfter, validBefore,\n// nonce }, r, s, v, signature }`. We re-shape the result into the\n// `Erc3009AuthData` slot of the escrow payment payload.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n Erc3009AuthData,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { parseChainId } from \"../core-sdk-factory.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nexport interface SignErc3009Args {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n tokenDomainResolver: TokenDomainResolver;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the ERC-3009 typed-data, sign it via core-sdk, and shape the result\n * into the `Erc3009AuthData` slot of the escrow payment payload.\n */\nexport async function signErc3009({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver,\n now = Date.now,\n}: SignErc3009Args): Promise<Erc3009AuthData> {\n const chainId = parseChainId(requirements.network);\n const domain = await tokenDomainResolver(requirements.asset as Address, chainId);\n\n const validAfter = 0;\n const validBefore = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n\n const result = await coreSdk.signReceiveWithErc3009Authorization(\n requirements.asset,\n { name: domain.name, version: domain.version },\n requirements.amount,\n validAfter,\n validBefore,\n { spender: requirements.escrowAddress as `0x${string}` },\n );\n\n return {\n from: buyer,\n to: requirements.escrowAddress,\n value: requirements.amount,\n validAfter: Number(result.data.validAfter),\n validBefore: Number(result.data.validBefore),\n nonce: result.data.nonce as Hex,\n v: result.v,\n r: result.r as Hex,\n s: result.s as Hex,\n };\n}\n","// Build and sign the buyer's EIP-2612 `Permit` for the escrow contract via\n// `CoreSDK.signReceiveWithErc2612Permit`.\n//\n// The SDK fetches the token's `nonces(owner)` via `web3Lib.call(...)` before\n// signing — that path requires the client's `signerToWeb3LibAdapter` to have\n// been built with a configured `PublicClient`. Without one, the underlying\n// `eth_call` rejects with a clear \"no PublicClient configured\" error,\n// surfaced to the caller as a sign-time failure.\n//\n// The SDK returns `{ strategy: \"EIP2612\", data: { deadline }, r, s, v,\n// signature }` — note that the nonce *is not* part of `data`. The wire\n// format `PermitAuthData` carries the nonce because the facilitator's\n// verification path needs it to rebuild the digest the buyer signed (the\n// on-chain `permit()` call refetches the current nonce, but the signature\n// is locked to the value at sign time). We recover it from the SDK's\n// signed typed-data by paying a second on-chain read of `nonces(owner)`;\n// in practice the value the SDK signed against is the one we observe\n// (only an interleaved successful `permit()` between sign and read would\n// shift it, which would then have invalidated the signature anyway).\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n EscrowPaymentRequirements,\n PermitAuthData,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport {\n encodeFunctionData,\n decodeFunctionResult,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n\nimport { parseChainId } from \"../core-sdk-factory.js\";\nimport { UnsupportedTokenAuthError } from \"../errors.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nconst NONCES_ABI = [\n {\n type: \"function\",\n name: \"nonces\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n },\n] as const;\n\nexport interface SignPermitArgs {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n tokenDomainResolver: TokenDomainResolver;\n /** PublicClient for the chain — required to recover the nonce that the SDK signed against. */\n publicClient: PublicClient;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the EIP-2612 Permit typed-data, sign it via core-sdk, look up the\n * token nonce the SDK signed against, and shape the result into the\n * `PermitAuthData` slot of the escrow payment payload.\n */\nexport async function signPermit({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver,\n publicClient,\n now = Date.now,\n}: SignPermitArgs): Promise<PermitAuthData> {\n const chainId = parseChainId(requirements.network);\n const domain = await tokenDomainResolver(requirements.asset as Address, chainId);\n\n const noncePreSign = await readNonce(publicClient, requirements.asset as Address, buyer);\n const deadline = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n\n const result = await coreSdk.signReceiveWithErc2612Permit(\n requirements.asset,\n { name: domain.name, version: domain.version },\n requirements.amount,\n deadline,\n { spender: requirements.escrowAddress as `0x${string}` },\n );\n\n const noncePostSign = await readNonce(publicClient, requirements.asset as Address, buyer);\n if (noncePreSign !== noncePostSign) {\n // A successful `permit()` for this owner landed on-chain between our\n // two reads, which means the SDK signed against either nonce. We can't\n // tell which without re-signing, so fail loudly.\n throw new UnsupportedTokenAuthError(\n `x402-client: token nonce shifted during permit signing (was ${noncePreSign}, now ${noncePostSign}); retry`,\n );\n }\n\n return {\n owner: buyer,\n spender: requirements.escrowAddress,\n value: requirements.amount,\n deadline,\n nonce: noncePreSign.toString(),\n v: result.v,\n r: result.r as Hex,\n s: result.s as Hex,\n };\n}\n\nasync function readNonce(\n publicClient: PublicClient,\n token: Address,\n owner: Address,\n): Promise<bigint> {\n const result = await publicClient.call({\n to: token as `0x${string}`,\n data: encodeFunctionData({\n abi: NONCES_ABI,\n functionName: \"nonces\",\n args: [owner as `0x${string}`],\n }),\n });\n if (!result.data) {\n throw new UnsupportedTokenAuthError(\n `x402-client: token ${token} did not return data for nonces(${owner}) — does it implement EIP-2612?`,\n );\n }\n return decodeFunctionResult({\n abi: NONCES_ABI,\n functionName: \"nonces\",\n data: result.data,\n });\n}\n","// Build and sign the buyer's Uniswap Permit2 `PermitTransferFrom` for the\n// escrow contract via `CoreSDK.signReceiveWithPermit2`.\n//\n// The SDK accepts an optional `permit2Nonce` override; if omitted it\n// generates a random uint256. We pass one explicitly via `randomUint256()`\n// so tests can stub the RNG and so the value never depends on the SDK's\n// internal nonce-generation surface. The Permit2 contract address comes\n// from the wire-format `requirements.onchainHints?.permit2` when present,\n// or falls back to the canonical CREATE2 vanity address re-exported from\n// `@bosonprotocol/x402-core/eip712/token-auth`.\n//\n// Result shape from core-sdk:\n// { strategy: \"Permit2\", data: { nonce, deadline }, r, s, v, signature }\n// — we lift it into the wire-format `Permit2AuthData`.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport { PERMIT2_ADDRESS } from \"@bosonprotocol/x402-core/eip712/token-auth\";\nimport type {\n EscrowPaymentRequirements,\n Permit2AuthData,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"../utils/crypto.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nexport interface SignPermit2Args {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the Permit2 `PermitTransferFrom` typed-data, sign it via core-sdk,\n * and shape the result into the `Permit2AuthData` slot of the escrow\n * payment payload.\n */\nexport async function signPermit2({\n requirements,\n buyer,\n coreSdk,\n now = Date.now,\n}: SignPermit2Args): Promise<Permit2AuthData> {\n const deadline = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n const permit2Nonce = randomUint256();\n\n // `buyer` is exposed in the call site for symmetry with the other\n // strategies and to keep the function signature stable as we add\n // explicit-`user` overrides. Today the SDK derives `user` internally\n // from `coreSdk._web3Lib.getSignerAddress()`, which we route through the\n // configured `signer.getAddress()` in `signerToWeb3LibAdapter`.\n void buyer;\n\n const result = await coreSdk.signReceiveWithPermit2(\n requirements.asset,\n requirements.amount,\n deadline,\n {\n spender: requirements.escrowAddress as `0x${string}`,\n permit2Address: PERMIT2_ADDRESS,\n permit2Nonce,\n },\n );\n\n return {\n permitted: { token: requirements.asset, amount: requirements.amount },\n spender: requirements.escrowAddress,\n nonce: permit2Nonce.toString(),\n deadline,\n signature: result.signature as Hex,\n };\n}\n","// Token-authorization strategy dispatcher.\n//\n// Picks one of the buyer-side strategies (`erc3009`, `permit`, `permit2`)\n// from `requirements.tokenAuthStrategies`, signs the corresponding payload\n// via `CoreSDK`, and returns the wire-format `BosonTokenAuth` slot. The\n// `none` strategy is encoded by the absence of `tokenAuth` on the payload\n// — callers handle it outside this module.\n//\n// Preference order when the server advertises multiple strategies:\n// `erc3009` → `permit2` → `permit`. ERC-3009 is preferred for tokens that\n// support it (USDC, USDP, EUROC, etc.) because the receive-variant\n// eliminates relayer front-running. Permit2 is preferred over Permit for\n// tokens behind the canonical Permit2 contract because it carries a\n// caller-controllable nonce. Permit is the fallback.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n BosonTokenAuth,\n EscrowPaymentRequirements,\n TokenAuthStrategy,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { UnsupportedTokenAuthError } from \"../errors.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { signErc3009 } from \"./erc3009.js\";\nimport { signPermit } from \"./permit.js\";\nimport { signPermit2 } from \"./permit2.js\";\n\nexport interface BuildTokenAuthArgs {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n /** Required for ERC-3009 and EIP-2612 Permit; not used by Permit2. */\n tokenDomainResolver?: TokenDomainResolver;\n /** Optional PublicClient for the requirements' chain. Required for Permit. */\n publicClient?: PublicClient;\n now?: () => number;\n}\n\nexport interface BuiltTokenAuth {\n strategy: TokenAuthStrategy;\n tokenAuth: BosonTokenAuth;\n}\n\nconst STRATEGY_PREFERENCE: readonly TokenAuthStrategy[] = [\"erc3009\", \"permit2\", \"permit\"];\n\nfunction strategyIsAvailable(s: TokenAuthStrategy, args: BuildTokenAuthArgs): boolean {\n switch (s) {\n case \"erc3009\":\n return args.tokenDomainResolver !== undefined;\n case \"permit\":\n return args.tokenDomainResolver !== undefined && args.publicClient !== undefined;\n case \"permit2\":\n return true;\n case \"none\":\n return false;\n default: {\n const _exhaustive: never = s;\n void _exhaustive;\n return false;\n }\n }\n}\n\n/**\n * Pick the highest-preference strategy from `requirements.tokenAuthStrategies`,\n * sign the corresponding payload via core-sdk, and return the wire-format\n * `BosonTokenAuth` slot.\n *\n * The picker is capability-aware: a strategy is only chosen when the runtime\n * config has the prerequisites for it (e.g. `tokenDomainResolver` for\n * ERC-3009, both `tokenDomainResolver` and `publicClient` for Permit). This\n * lets a deployment without `tokenDomainResolver` still satisfy servers that\n * advertise `[\"erc3009\", \"permit2\"]` by falling back to Permit2.\n */\nexport async function buildAndSignTokenAuth(args: BuildTokenAuthArgs): Promise<BuiltTokenAuth> {\n const advertised = args.requirements.tokenAuthStrategies;\n const chosen = STRATEGY_PREFERENCE.find(\n (s) => advertised.includes(s) && strategyIsAvailable(s, args),\n );\n if (!chosen) {\n throw new UnsupportedTokenAuthError(\n `server advertises tokenAuthStrategies=[${advertised.join(\", \")}]; ` +\n `client supports [${STRATEGY_PREFERENCE.join(\", \")}] but none are usable ` +\n `with the current X402bClientConfig ` +\n `(ERC-3009 and Permit require tokenDomainResolver; Permit also requires ` +\n `a PublicClient for the requirements' chain via publicClients)`,\n );\n }\n\n switch (chosen) {\n case \"erc3009\": {\n if (!args.tokenDomainResolver) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'erc3009' but no tokenDomainResolver is configured — pass tokenDomainResolver in X402bClientConfig\",\n );\n }\n const data = await signErc3009({\n ...args,\n tokenDomainResolver: args.tokenDomainResolver,\n });\n return { strategy: \"erc3009\", tokenAuth: { kind: \"erc3009\", data } };\n }\n case \"permit\": {\n if (!args.tokenDomainResolver) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'permit' but no tokenDomainResolver is configured — pass tokenDomainResolver in X402bClientConfig\",\n );\n }\n if (!args.publicClient) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'permit' but no PublicClient is configured for this chain — pass publicClients in X402bClientConfig\",\n );\n }\n const data = await signPermit({\n ...args,\n tokenDomainResolver: args.tokenDomainResolver,\n publicClient: args.publicClient,\n });\n return { strategy: \"permit\", tokenAuth: { kind: \"permit\", data } };\n }\n case \"permit2\": {\n const data = await signPermit2(args);\n return { strategy: \"permit2\", tokenAuth: { kind: \"permit2\", data } };\n }\n case \"none\": {\n // Should never reach: `STRATEGY_PREFERENCE` doesn't include \"none\",\n // so a server advertising only \"none\" falls through to the error\n // above. Keep the case for exhaustiveness against\n // `TokenAuthStrategy`.\n throw new UnsupportedTokenAuthError(\n \"tokenAuthStrategy='none' has no client-side signing — callers handle it without invoking this dispatcher\",\n );\n }\n default: {\n const _exhaustive: never = chosen;\n throw new UnsupportedTokenAuthError(\n `unrecognised tokenAuthStrategy '${(_exhaustive as { toString(): string }).toString()}'`,\n );\n }\n }\n}\n","// Top-level `createX402bClient` factory.\n//\n// Wires the action picker, token-auth strategy dispatcher, meta-tx signer\n// (via `CoreSDK`), fulfillment resolver, and payload assembler into:\n//\n// - `handle402(requirements)` — commit-time flow that emits the base64\n// `X-PAYMENT` value for the 402 retry.\n// - `signAction(args)` — post-commit flow that signs one of the buyer's\n// follow-up meta-transactions (redeem / cancel / complete / dispute\n// family). No token-auth or X-PAYMENT wrapping; the caller picks a\n// channel and POSTs the wire envelope.\n\nimport {\n parseEscrowPaymentRequirements,\n type EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address } from \"viem\";\n\nimport { pickAction } from \"./action.js\";\nimport { createCoreSdkFactory } from \"./core-sdk-factory.js\";\nimport { resolveFulfillment } from \"./fulfillment.js\";\nimport { assembleAndEncodePayload } from \"./payload.js\";\nimport { signCreateOfferAndCommit, signCreateOfferCommitAndRedeem } from \"./pre-commit.js\";\nimport {\n signPostCommitAction,\n type SignActionArgs,\n type SignedPostCommitAction,\n} from \"./post-commit.js\";\nimport { parsePaymentResponse } from \"./response.js\";\nimport {\n signWithdrawAllAvailableFunds,\n signWithdrawFunds,\n type SignWithdrawAllAvailableFundsArgs,\n type SignWithdrawFundsArgs,\n type SignedWithdrawFunds,\n} from \"./withdraw.js\";\nimport { buildAndSignTokenAuth } from \"./token-auth/index.js\";\nimport { MaxAmountExceededError, UnsupportedTokenAuthError } from \"./errors.js\";\nimport type { ExchangeSummary, X402bClientConfig } from \"./types.js\";\n\nexport interface X402bClient {\n /**\n * Consume a parsed escrow PaymentRequirements and return the base64\n * value to set as the `X-PAYMENT` header on the retry.\n */\n handle402(requirements: unknown): Promise<string>;\n\n /**\n * Sign a Boson protocol meta-transaction for a buyer-driven post-commit\n * action (redeem, cancel, complete, dispute family). Returns both the\n * wire-format `BosonMetaTx` envelope and the ABI-encoded `signedPayload`\n * Hex — pick the shape that matches the chosen channel. Server /\n * facilitator HTTP routes consume `signedPayload` directly (e.g. as\n * the `signedPayload` field on the JSON POST body to the endpoint the\n * prior response advertised under `actions.next[].endpoints.server`);\n * on-chain and MCP channels use the `metaTx` object.\n *\n * Note: `boson-escalateDispute` signs only the meta-tx. If the dispute\n * resolver requires an escalation deposit, the resolver/server returns\n * its own 402 with an `escrow` `PaymentRequirements` and the buyer pairs\n * this meta-tx with a token-auth payload — the deposit wrapper is out\n * of MVP.\n */\n signAction(args: SignActionArgs): Promise<SignedPostCommitAction>;\n\n /**\n * Sign a `withdrawFunds(entityId, tokenList, tokenAmounts)` meta-tx.\n * Caller-resolved entity + tokens snapshot — see\n * `signWithdrawAllAvailableFunds` for the read-from-subgraph \"withdraw\n * everything\" sugar.\n */\n signWithdrawFunds(args: SignWithdrawFundsArgs): Promise<SignedWithdrawFunds>;\n\n /**\n * Read available funds for the given entity from the subgraph and\n * sign a meta-tx withdrawing the entire current balance set. Accepts\n * either an `entityId` directly or an `address` (with optional\n * `role` for ambiguous wallets).\n */\n signWithdrawAllAvailableFunds(\n args: SignWithdrawAllAvailableFundsArgs,\n ): Promise<SignedWithdrawFunds>;\n\n /**\n * Best-effort decode of `X-PAYMENT-RESPONSE` after a successful retry.\n * Returns `undefined` when the header isn't present.\n */\n parsePaymentResponse(response: {\n headers: { get(name: string): string | null };\n }): ExchangeSummary | undefined;\n}\n\n/**\n * Build a stateless client bound to a buyer signer + policy. The\n * underlying `CoreSDK` is built lazily per `(chainId, escrowAddress)` and\n * cached across calls — both `handle402` and `signAction` reuse it.\n */\nexport function createX402bClient(config: X402bClientConfig): X402bClient {\n const buildCoreSdk = createCoreSdkFactory(config.signer, config);\n\n const getBuyerAddress = async () => (await config.signer.getAddress()) as Address;\n\n return {\n async handle402(rawRequirements) {\n const requirements: EscrowPaymentRequirements =\n parseEscrowPaymentRequirements(rawRequirements);\n\n const action = pickAction(requirements, config.policy);\n const fulfillment = resolveFulfillment(requirements, config);\n enforceMaxAmount(requirements.amount, config.policy?.maxAmount);\n const buyer = await getBuyerAddress();\n\n const { coreSdk, chainId } = buildCoreSdk(\n requirements.network,\n requirements.escrowAddress as Address,\n );\n\n // `policy.tokenAuthStrategy` forces a specific strategy from the\n // server's advertised set instead of letting the dispatcher pick\n // by preference. The forced value must be in\n // `requirements.tokenAuthStrategies`; otherwise the override is\n // rejected. `\"none\"` short-circuits the dispatcher entirely (the\n // buyer has approved the escrow off-band and the payment rides\n // the protocol's `safeTransferFrom` fallback); for the other\n // strategies the dispatcher is invoked with the advertised set\n // narrowed to a single element so it must pick the requested one.\n let tokenAuth: Awaited<ReturnType<typeof buildAndSignTokenAuth>>[\"tokenAuth\"] | undefined;\n let strategy: Awaited<ReturnType<typeof buildAndSignTokenAuth>>[\"strategy\"];\n const forcedStrategy = config.policy?.tokenAuthStrategy;\n if (forcedStrategy !== undefined) {\n if (!requirements.tokenAuthStrategies.includes(forcedStrategy)) {\n throw new UnsupportedTokenAuthError(\n `policy.tokenAuthStrategy \"${forcedStrategy}\" is not in requirements.tokenAuthStrategies (${requirements.tokenAuthStrategies.join(\", \")})`,\n );\n }\n if (forcedStrategy === \"none\") {\n strategy = \"none\";\n tokenAuth = undefined;\n } else {\n const built = await buildAndSignTokenAuth({\n requirements: { ...requirements, tokenAuthStrategies: [forcedStrategy] },\n buyer,\n coreSdk,\n tokenDomainResolver: config.tokenDomainResolver,\n publicClient: config.publicClients?.[chainId],\n });\n strategy = built.strategy;\n tokenAuth = built.tokenAuth;\n }\n } else {\n const built = await buildAndSignTokenAuth({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver: config.tokenDomainResolver,\n publicClient: config.publicClients?.[chainId],\n });\n strategy = built.strategy;\n tokenAuth = built.tokenAuth;\n }\n\n // Flow B (boson-createOfferCommitAndRedeem) carries the buyer's\n // delivery data along with the commit-time payload — there's no\n // later round trip in which to attach it. Flow A defers `data` to\n // the redeem-time POST body; `assemblePayload` handles the\n // conditional emission based on `action`.\n const signMetaTx =\n action === \"boson-createOfferCommitAndRedeem\"\n ? signCreateOfferCommitAndRedeem\n : signCreateOfferAndCommit;\n const metaTx = await signMetaTx({ requirements, coreSdk, buyer });\n\n return assembleAndEncodePayload({\n requirements,\n action,\n tokenAuthStrategy: strategy,\n metaTx,\n tokenAuth,\n fulfillment,\n buyer,\n });\n },\n\n signAction(args) {\n return signPostCommitAction(args, { buildCoreSdk, getBuyerAddress });\n },\n\n signWithdrawFunds(args) {\n return signWithdrawFunds(args, { buildCoreSdk, getSignerAddress: getBuyerAddress });\n },\n\n signWithdrawAllAvailableFunds(args) {\n return signWithdrawAllAvailableFunds(args, {\n buildCoreSdk,\n getSignerAddress: getBuyerAddress,\n });\n },\n\n parsePaymentResponse(response) {\n return parsePaymentResponse(response);\n },\n };\n}\n\nfunction enforceMaxAmount(amount: string, maxAmount?: string): void {\n if (maxAmount === undefined) {\n return;\n }\n\n const amountBigInt = BigInt(amount);\n const maxAmountBigInt = BigInt(maxAmount);\n if (amountBigInt > maxAmountBigInt) {\n throw new MaxAmountExceededError(\n `x402-client: requirements.amount ${amount} exceeds policy.maxAmount ${maxAmount}`,\n );\n }\n}\n","// Translator that wraps a Boson `Web3LibAdapter` (e.g. an `EthersAdapter`\n// from `@bosonprotocol/ethers-sdk`) as an x402-client `Signer`. The point\n// is to let consumers who already hold an adapter for the deployed Boson\n// protocol reuse it with `createX402bClient` without writing the shim\n// themselves — and without forcing this package to take `ethers` (or\n// `@bosonprotocol/common`) as a peer dep.\n//\n// Structural typing keeps the coupling minimal: `Web3LibAdapterLike` picks\n// only the two methods we actually invoke. The consumer's own `ethers` /\n// `@bosonprotocol/ethers-sdk` install carries the full types — an\n// `EthersAdapter` instance satisfies `Web3LibAdapterLike` by shape.\n//\n// Note on `EIP712Domain` injection: `eth_signTypedData_v4` (and the\n// `EthersAdapter` JSON path) expects `types.EIP712Domain` to be present\n// and to match exactly the fields populated on `domain`. We derive it\n// from `domain`'s field presence — the same rule viem applies internally\n// in `getTypesForEIP712Domain`.\n\nimport {\n getAddress,\n serializeTypedData,\n type Address,\n type Hex,\n type TypedDataDomain,\n type TypedDataDefinition,\n type TypedDataParameter,\n} from \"viem\";\n\nimport type { Signer } from \"./types.js\";\n\n/**\n * Structural subset of `@bosonprotocol/common`'s `Web3LibAdapter` that\n * {@link signerFromEthersAdapter} actually exercises. An `EthersAdapter`\n * from `@bosonprotocol/ethers-sdk` (or any future concrete adapter)\n * satisfies this shape without an explicit cast.\n */\nexport interface Web3LibAdapterLike {\n getSignerAddress(): Promise<string>;\n send(method: string, params: readonly unknown[]): Promise<unknown>;\n}\n\n/**\n * Wrap a Boson `Web3LibAdapter`-shaped object as an x402-client\n * {@link Signer}. `signTypedData` builds the standard\n * `eth_signTypedData_v4` JSON payload (including a derived\n * `EIP712Domain` type list) and routes it through `adapter.send`.\n */\nexport function signerFromEthersAdapter(adapter: Web3LibAdapterLike): Signer {\n const resolveAddress = async (): Promise<Address> => getAddress(await adapter.getSignerAddress());\n return {\n getAddress: resolveAddress,\n signTypedData: async ({ domain, types, primaryType, message }) => {\n const from = await resolveAddress();\n const typedData = {\n domain,\n types: { ...types, EIP712Domain: deriveEip712DomainType(domain) },\n primaryType,\n message,\n };\n const json = serializeTypedData(typedData as unknown as TypedDataDefinition);\n const sig = await adapter.send(\"eth_signTypedData_v4\", [from, json]);\n if (typeof sig !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(sig)) {\n throw new Error(\n \"signerFromEthersAdapter: adapter.send did not return a hex signature string\",\n );\n }\n return sig as Hex;\n },\n };\n}\n\n/**\n * Build the `EIP712Domain` type-list from the fields actually present on\n * `domain`, in the canonical EIP-712 order (`name`, `version`, `chainId`,\n * `verifyingContract`, `salt`). Matches viem's internal derivation so the\n * resulting digest agrees with what a viem signer would produce.\n */\nfunction deriveEip712DomainType(domain: TypedDataDomain): readonly TypedDataParameter[] {\n const fields: TypedDataParameter[] = [];\n if (domain.name !== undefined) fields.push({ name: \"name\", type: \"string\" });\n if (domain.version !== undefined) fields.push({ name: \"version\", type: \"string\" });\n if (domain.chainId !== undefined) fields.push({ name: \"chainId\", type: \"uint256\" });\n if (domain.verifyingContract !== undefined)\n fields.push({ name: \"verifyingContract\", type: \"address\" });\n if (domain.salt !== undefined) fields.push({ name: \"salt\", type: \"bytes32\" });\n return fields;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/action.ts","../../src/base64.ts","../../src/fulfillment.ts","../../src/internal/web3lib-adapter.ts","../../src/core-sdk-factory.ts","../../src/response.ts","../../src/payload.ts","../../src/utils/crypto.ts","../../src/pre-commit.ts","../../src/post-commit.ts","../../src/submit.ts","../../src/withdraw.ts","../../src/token-auth/deadline.ts","../../src/token-auth/erc3009.ts","../../src/token-auth/permit.ts","../../src/token-auth/permit2.ts","../../src/token-auth/index.ts","../../src/client.ts","../../src/signer-from-adapter.ts"],"names":["Ajv","coreSdk","CoreSDK","parseEscrowPaymentPayload","encodeSignedPayload","ExchangeState","DisputeState","DECIMAL_UINT","encodeFunctionData","decodeFunctionResult","PERMIT2_ADDRESS","parseEscrowPaymentRequirements","getAddress","serializeTypedData"],"mappings":";;;;;;;;;;;;;;;AAIO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAEO,IAAM,yBAAA,GAAN,cAAwC,KAAA,CAAM;AAAA,EACnD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,2BAAA;AAAA,EACd;AACF;AAEO,IAAM,uBAAA,GAAN,cAAsC,KAAA,CAAM;AAAA,EACjD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAEO,IAAM,0BAAA,GAAN,cAAyC,KAAA,CAAM;AAAA,EACpD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GA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EAAA,MAAM,SAA+B,EAAC;AACtC,EAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,QAAA,EAAU,CAAA;AAC3E,EAAA,IAAI,MAAA,CAAO,OAAA,KAAY,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,QAAA,EAAU,CAAA;AACjF,EAAA,IAAI,MAAA,CAAO,OAAA,KAAY,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,SAAA,EAAW,IAAA,EAAM,SAAA,EAAW,CAAA;AAClF,EAAA,IAAI,OAAO,iBAAA,KAAsB,MAAA;AAC/B,IAAA,MAAA,CAAO,KAAK,EAAE,IAAA,EAAM,mBAAA,EAAqB,IAAA,EAAM,WAAW,CAAA;AAC5D,EAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,MAAA,CAAO,IAAA,CAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW,CAAA;AAC5E,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// Typed error classes for the x402-client. Each is a leaf `Error` subclass\n// with a stable `name` so callers can branch on `instanceof` or string-match\n// without parsing messages.\n\nexport class UnsupportedSchemeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedSchemeError\";\n }\n}\n\nexport class UnsupportedTokenAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"UnsupportedTokenAuthError\";\n }\n}\n\nexport class NoCompatibleActionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NoCompatibleActionError\";\n }\n}\n\nexport class FulfillmentValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FulfillmentValidationError\";\n }\n}\n\nexport class MaxAmountExceededError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"MaxAmountExceededError\";\n }\n}\n","// Pick the on-chain Boson action to invoke from a parsed PaymentRequirements.\n//\n// Two commit-time actions are supported:\n// - `boson-createOfferAndCommit` (Flow A, deferred redeem)\n// - `boson-createOfferCommitAndRedeem` (Flow B, atomic commit+redeem)\n//\n// Selection rules:\n// - `policy.redeemMode = \"commit-only\"`: require Flow A.\n// - `policy.redeemMode = \"auto\"` (or unset): prefer Flow A, fall back to Flow B.\n// - `policy.redeemMode = \"commit-and-redeem\"`: require Flow B; throw\n// `NoCompatibleActionError` if the server hasn't advertised it.\n//\n// In \"auto\" mode we keep MVP behaviour (prefer Flow A whenever advertised)\n// so existing callers don't silently switch flows on the SDK upgrade. A\n// future policy could promote Flow B when both are offered, but that's a\n// separate change.\n\nimport type {\n BosonCommitActionId,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport { NoCompatibleActionError } from \"./errors.js\";\nimport type { Policy } from \"./types.js\";\n\nconst FLOW_A: BosonCommitActionId = \"boson-createOfferAndCommit\";\nconst FLOW_B: BosonCommitActionId = \"boson-createOfferCommitAndRedeem\";\n\n/**\n * Resolve the Boson commit-time action the client will sign. Throws\n * `NoCompatibleActionError` when the server hasn't advertised any action\n * compatible with the requested policy.\n */\nexport function pickAction(\n requirements: EscrowPaymentRequirements,\n policy?: Policy,\n): BosonCommitActionId {\n const redeemMode = policy?.redeemMode ?? \"auto\";\n\n const flowAOffered = requirements.actions.next.some(\n (a) => a.id === FLOW_A && a.channels.includes(\"server\"),\n );\n const flowBOffered = requirements.actions.next.some(\n (a) => a.id === FLOW_B && a.channels.includes(\"server\"),\n );\n\n if (redeemMode === \"commit-and-redeem\") {\n if (flowBOffered) return FLOW_B;\n throw new NoCompatibleActionError(\n `policy.redeemMode='commit-and-redeem' requires '${FLOW_B}' on the server channel; requirements only advertise [${requirements.actions.next.map((a) => a.id).join(\", \")}]`,\n );\n }\n\n if (redeemMode === \"commit-only\") {\n if (flowAOffered) return FLOW_A;\n throw new NoCompatibleActionError(\n `policy.redeemMode='commit-only' requires '${FLOW_A}' on the server channel; requirements only advertise [${requirements.actions.next.map((a) => a.id).join(\", \")}]`,\n );\n }\n\n // \"auto\": prefer Flow A when present, but fall back to Flow B.\n if (flowAOffered) return FLOW_A;\n if (flowBOffered) return FLOW_B;\n\n throw new NoCompatibleActionError(\n `no commit-time action ('${FLOW_A}' or '${FLOW_B}') with 'server' channel found in requirements.actions.next`,\n );\n}\n","// Isomorphic base64 helpers used by the X-PAYMENT / X-PAYMENT-RESPONSE\n// header pipeline. Picks `Buffer` on Node and `atob` / `btoa` on\n// browsers — tsup builds both formats, so the runtime branch matters.\n//\n// Browser-side encode goes UTF-8 → binary-string → `btoa` because\n// `btoa` accepts only code units 0–255 and throws\n// `InvalidCharacterError` on any character above U+00FF, while wire\n// payloads can carry free-form fulfillment data populated by the\n// buyer (emails, addresses, notes). Decode does the inverse.\n\n/** Decode a base64-encoded string to UTF-8. */\nexport function decodeBase64(value: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(value, \"base64\").toString(\"utf8\");\n }\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n\n/** Encode a UTF-8 string as base64. */\nexport function encodeBase64(value: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(value, \"utf8\").toString(\"base64\");\n }\n const bytes = new TextEncoder().encode(value);\n let binary = \"\";\n for (const b of bytes) {\n binary += String.fromCharCode(b);\n }\n return btoa(binary);\n}\n","// Resolve the `fulfillment` slot the client will attach to the commit-time\n// payment payload. The buyer's chosen `option` always flows (capability\n// negotiation against the server's advertised set); the `data` field is\n// validated locally against the option's JSON Schema either way so the\n// client fails fast before signing — but whether it travels with the\n// commit-time payload depends on the action the client is signing:\n//\n// - Atomic Flow B (`boson-createOfferCommitAndRedeem`): the commit and\n// on-chain redeem happen in one transaction, so the X-PAYMENT header\n// is the only round trip the buyer makes. `data` MUST be present.\n// - Two-step Flow A (`boson-createOfferAndCommit`): the buyer redeems\n// later via `boson-redeem`'s POST body — `data` is omitted at commit\n// and attached at redeem.\n//\n// The conditional emission lives in the payload assembler (`payload.ts`);\n// this module returns both `option` and `data` and lets the caller decide.\n\nimport Ajv from \"ajv\";\nimport type { EscrowPaymentRequirements } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport { FulfillmentValidationError } from \"./errors.js\";\nimport type { FulfillmentConfig, X402bClientConfig } from \"./types.js\";\n\nexport interface ResolvedFulfillment {\n option: string;\n /**\n * Buyer-supplied delivery data, validated locally against the option's\n * JSON Schema. The payload assembler decides whether to include this\n * field in the commit-time payload (Flow B yes, Flow A no).\n */\n data: Record<string, unknown> | null;\n}\n\n/**\n * Returns the resolved `{ option, data }` pair the assembler will attach\n * to the commit-time fulfillment slot (Flow B) or carry forward for the\n * redeem-time POST body (Flow A). Throws when the requirements demand a\n * fulfillment but the client config doesn't supply one, when the option\n * id isn't advertised by the server, or when the buyer data doesn't\n * validate against the option's schema.\n */\nexport function resolveFulfillment(\n requirements: EscrowPaymentRequirements,\n config: Pick<X402bClientConfig, \"fulfillment\">,\n): ResolvedFulfillment | undefined {\n const required = requirements.fulfillment?.required ?? false;\n if (!required) {\n return undefined;\n }\n\n const fulfillmentConfig: FulfillmentConfig | undefined = config.fulfillment;\n if (!fulfillmentConfig) {\n throw new FulfillmentValidationError(\n \"requirements.fulfillment.required is true but client config did not supply a fulfillment selection\",\n );\n }\n\n const option = requirements.fulfillment?.options.find((o) => o.id === fulfillmentConfig.option);\n if (!option) {\n const advertised = requirements.fulfillment?.options.map((o) => o.id).join(\", \") ?? \"<none>\";\n throw new FulfillmentValidationError(\n `fulfillment option '${fulfillmentConfig.option}' not advertised by requirements (advertised: ${advertised})`,\n );\n }\n\n if (option.schema === null) {\n if (fulfillmentConfig.data !== null) {\n throw new FulfillmentValidationError(\n `fulfillment option '${option.id}' accepts no buyer data; use null`,\n );\n }\n } else {\n const ajv = new Ajv({ allErrors: true, strict: false });\n const validate = ajv.compile(option.schema);\n const ok = validate(fulfillmentConfig.data);\n if (!ok) {\n throw new FulfillmentValidationError(\n `fulfillment data does not match option '${option.id}' schema: ${ajv.errorsText(validate.errors)}`,\n );\n }\n }\n\n return { option: fulfillmentConfig.option, data: fulfillmentConfig.data };\n}\n","// Translator that wraps a `Signer` (plus an optional viem `PublicClient`\n// for read-only RPC calls) into a `Web3LibAdapter` that `CoreSDK` can be\n// constructed against.\n//\n// Two RPC methods are forwarded:\n//\n// - `send(\"eth_signTypedData_v4\", ...)` — buyer signs via `signer.signTypedData`.\n// - `call({ to, data })` — read-only `eth_call`, forwarded to the\n// `PublicClient` when one is configured. Required by the EIP-2612\n// Permit token-auth path, which fetches the token's `nonces(owner)`\n// before signing. Throws a clear error when invoked without a\n// PublicClient so the configuration mistake surfaces fast.\n//\n// Transaction-flavour methods (`sendTransaction`, `estimateGas`,\n// `getBalance`, `getTransactionReceipt`, `getCurrentTimeMs`) reject — the\n// buyer never goes on-chain in MVP.\n\nimport type { Web3LibAdapter } from \"@bosonprotocol/common\";\nimport type { PublicClient, TypedDataDomain, TypedDataParameter } from \"viem\";\n\nimport type { Signer } from \"../types.js\";\n\n/**\n * Build the `Web3LibAdapter` that `@bosonprotocol/core-sdk`'s `CoreSDK`\n * accepts. `send(\"eth_signTypedData_v4\", [address, jsonString])` delegates\n * to `signer.signTypedData(...)`. `call({ to, data })` is forwarded to\n * `publicClient.call(...)` when one is provided; otherwise it throws (the\n * Permit strategy is the only path that exercises `call`).\n */\nexport function signerToWeb3LibAdapter(\n signer: Signer,\n chainId: number,\n publicClient?: PublicClient,\n): Web3LibAdapter {\n return {\n uuid: \"x402-client:signer-adapter\",\n getSignerAddress: () => signer.getAddress(),\n isSignerContract: async () => false,\n getChainId: async () => chainId,\n send: async (method, params) => {\n if (method !== \"eth_signTypedData_v4\") {\n throw new Error(\n `x402-client: signer adapter does not support RPC method '${method}'; only eth_signTypedData_v4 is implemented`,\n );\n }\n const raw = (params as unknown[])[1];\n if (typeof raw !== \"string\") {\n throw new Error(\n \"x402-client: eth_signTypedData_v4 payload[1] is not a JSON string — core-sdk internals may have changed\",\n );\n }\n const typedData = JSON.parse(raw) as {\n domain: TypedDataDomain;\n types: Record<string, readonly TypedDataParameter[]>;\n primaryType: string;\n message: Record<string, unknown>;\n };\n return signer.signTypedData(typedData);\n },\n call: async (req) => {\n if (!publicClient) {\n throw new Error(\n \"x402-client: signer adapter has no PublicClient configured; eth_call cannot be forwarded. \" +\n \"Pass `publicClients` in X402bClientConfig to enable the Permit token-auth strategy.\",\n );\n }\n const result = await publicClient.call({\n to: req.to as `0x${string}`,\n data: req.data as `0x${string}` | undefined,\n });\n return result.data ?? \"0x\";\n },\n getBalance: () => Promise.reject(unreachable(\"getBalance\")),\n estimateGas: () => Promise.reject(unreachable(\"estimateGas\")),\n sendTransaction: () => Promise.reject(unreachable(\"sendTransaction\")),\n getTransactionReceipt: () => Promise.reject(unreachable(\"getTransactionReceipt\")),\n getCurrentTimeMs: () => Promise.reject(unreachable(\"getCurrentTimeMs\")),\n };\n}\n\nfunction unreachable(method: string): Error {\n return new Error(\n `x402-client: stub Web3LibAdapter.${method}() is not implemented — the client never goes on-chain in MVP`,\n );\n}\n","// Construct (and cache) the `CoreSDK` instance the client signs through.\n//\n// The buyer never queries Boson's subgraph in MVP — only the EIP-712 meta-tx\n// signing path is invoked — but `CoreSDK`'s base constructor requires a\n// `subgraphUrl` string. Callers can configure real URLs per chain via\n// `subgraphUrls`, or omit it and rely on the placeholder sentinel below;\n// either way no HTTP call to that URL is made during signing.\n\nimport { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { Address } from \"viem\";\n\nimport { signerToWeb3LibAdapter } from \"./internal/web3lib-adapter.js\";\nimport type { Signer, X402bClientConfig } from \"./types.js\";\n\n// Sentinel used when the caller did not configure a real subgraph URL for\n// the chain. The signing path never reads from it; the value just needs to\n// be a non-empty string the constructor accepts.\nconst PLACEHOLDER_SUBGRAPH_URL = \"https://x402-client.placeholder.invalid/subgraph\";\n\nexport interface CoreSdkContext {\n coreSdk: CoreSDK;\n chainId: number;\n}\n\n/**\n * Parse a CAIP-2 EVM network identifier (e.g. `\"eip155:8453\"`) into its\n * numeric chain id. Throws if the network is not a well-formed `eip155:<N>`.\n */\nexport function parseChainId(network: string): number {\n const match = network.match(/^eip155:(\\d+)$/);\n if (!match) {\n throw new Error(\n `x402-client: unsupported network '${network}' (expected CAIP-2 'eip155:<chainId>')`,\n );\n }\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n throw new Error(\n `x402-client: unsupported network '${network}' (chainId must be a positive safe integer)`,\n );\n }\n return chainId;\n}\n\n/**\n * Lazy factory that returns a `CoreSDK` instance configured against the\n * escrow contract advertised in the network. Instances are cached per\n * `(chainId, escrowAddress)` so repeated calls on the same network — for\n * commit and subsequent post-commit actions on the same exchange — reuse a\n * single SDK.\n *\n * The SDK's `web3Lib.call(...)` is wired through `config.publicClients[chainId]`\n * when one is configured; this enables read-only RPC reads (e.g. the EIP-2612\n * Permit strategy's `nonces(owner)` lookup). Chains without a PublicClient\n * configured can still sign meta-transactions and ERC-3009 / Permit2\n * token-auths.\n */\nexport function createCoreSdkFactory(\n signer: Signer,\n config: Pick<X402bClientConfig, \"subgraphUrls\" | \"publicClients\">,\n) {\n const cache = new Map<string, CoreSDK>();\n\n return function buildCoreSdk(network: string, escrowAddress: Address): CoreSdkContext {\n const chainId = parseChainId(network);\n const cacheKey = `${chainId}:${escrowAddress.toLowerCase()}`;\n const cached = cache.get(cacheKey);\n if (cached) {\n return { coreSdk: cached, chainId };\n }\n\n const subgraphUrl = config.subgraphUrls?.[chainId] ?? PLACEHOLDER_SUBGRAPH_URL;\n const publicClient = config.publicClients?.[chainId];\n const web3Lib = signerToWeb3LibAdapter(signer, chainId, publicClient);\n\n const coreSdk = new CoreSDK({\n web3Lib,\n subgraphUrl,\n protocolDiamond: escrowAddress,\n chainId,\n });\n\n cache.set(cacheKey, coreSdk);\n return { coreSdk, chainId };\n };\n}\n","// Parse the optional `X-PAYMENT-RESPONSE` header the server may emit after\n// settling.\n//\n// The escrow-scheme spec doesn't pin a strict contract for this header yet,\n// so the parser is permissive: base64-decode the value, JSON-parse it, and\n// return `{ raw }`. Best-effort lifting picks `exchangeId` / `state` from\n// the common property paths an x402B server might use. Callers who need\n// stronger guarantees can read `raw` directly.\n\nimport { decodeBase64 } from \"./base64.js\";\nimport type { ExchangeSummary } from \"./types.js\";\n\nconst HEADER_NAME = \"X-PAYMENT-RESPONSE\";\n\n/** Read a header value from anything that exposes `.get(name)`. */\ninterface HeaderLike {\n get(name: string): string | null;\n}\n\ninterface ResponseLike {\n headers: HeaderLike;\n}\n\n/**\n * Decode the `X-PAYMENT-RESPONSE` header on a Response-like object. Returns\n * `undefined` when the header isn't set; throws on a malformed payload.\n */\nexport function parsePaymentResponse(response: ResponseLike): ExchangeSummary | undefined {\n const raw = response.headers.get(HEADER_NAME);\n if (!raw) {\n return undefined;\n }\n\n const json = decodeBase64(raw);\n const parsed: unknown = JSON.parse(json);\n const summary: ExchangeSummary = { raw: parsed };\n\n // Only walk into the payload when it's actually a plain record. A valid\n // JSON value can be `null`, an array, or a primitive — touching keys on\n // those would crash, defeating the file-header permissive promise.\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n const obj = parsed as Record<string, unknown>;\n\n const exchangeId = pickString(obj, [\"exchangeId\", \"exchange_id\"]);\n if (exchangeId !== undefined) {\n summary.exchangeId = exchangeId;\n }\n\n if (isClientStateShape(obj.state)) {\n summary.state = obj.state;\n }\n\n // Fallback for the server-emitted shape, which carries exchange state\n // under `nextActions.exchangeState` (and optionally `disputeState`)\n // rather than a top-level `state` field. The top-level lookup above\n // still wins when present, preserving forward-compat with external\n // servers that publish the flatter shape.\n if (\n summary.state === undefined &&\n typeof obj.nextActions === \"object\" &&\n obj.nextActions !== null &&\n !Array.isArray(obj.nextActions)\n ) {\n const na = obj.nextActions as Record<string, unknown>;\n const exchange = pickString(na, [\"exchangeState\"]);\n const dispute = pickString(na, [\"disputeState\"]);\n if (exchange !== undefined) {\n let candidate: unknown;\n if (exchange === \"DISPUTED\") {\n candidate = dispute !== undefined ? { exchange, dispute } : undefined;\n } else {\n candidate = { exchange };\n }\n if (isClientStateShape(candidate)) {\n summary.state = candidate;\n }\n }\n }\n }\n\n return summary;\n}\n\n/**\n * Shape gate for `state` arriving from the permissive server header. We\n * keep the file-header promise of permissiveness — `ClientState` is\n * `\"PRE_COMMIT\"` or an `{ exchange, dispute? }` record today, but the\n * wire contract isn't pinned, so any non-empty string (e.g. raw\n * `ExchangeState` value) or non-array `{ exchange }`-shaped record is\n * surfaced verbatim. Numbers, booleans, `null`, empty strings, arrays,\n * and records missing a string `exchange` field are rejected so garbage\n * payloads can't masquerade as a typed `ClientState`.\n */\nfunction isClientStateShape(v: unknown): v is NonNullable<ExchangeSummary[\"state\"]> {\n if (typeof v === \"string\") return v.length > 0;\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n const rec = v as Record<string, unknown>;\n if (typeof rec.exchange !== \"string\" || rec.exchange.length === 0) return false;\n if (\"dispute\" in rec && rec.dispute !== undefined && typeof rec.dispute !== \"string\") {\n return false;\n }\n return true;\n}\n\nfunction pickString(obj: Record<string, unknown>, keys: string[]): string | undefined {\n for (const key of keys) {\n const v = obj[key];\n if (typeof v === \"string\" && v.length > 0) {\n return v;\n }\n }\n return undefined;\n}\n","// Assemble the X-PAYMENT body and base64-encode it.\n//\n// Defense-in-depth: the assembled `EscrowPaymentPayload` is re-validated\n// through `parseEscrowPaymentPayload` from `@bosonprotocol/x402-core`\n// before serialization, so shape bugs surface here instead of at the\n// server. Base64 encoding goes through the isomorphic `encodeBase64`\n// helper from `./base64.js` — `Buffer` on Node, UTF-8-aware\n// `btoa` on browsers.\n\nimport {\n parseEscrowPaymentPayload,\n type BosonMetaTx,\n type BosonTokenAuth,\n type EscrowPaymentPayload,\n type EscrowPaymentRequirements,\n type TokenAuthStrategy,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address } from \"viem\";\n\nimport { encodeBase64 } from \"./base64.js\";\nimport type { ResolvedFulfillment } from \"./fulfillment.js\";\n\n/** Current x402 protocol version embedded in the payload envelope. */\nexport const X402_VERSION = 2;\n\nexport interface AssembleArgs {\n requirements: EscrowPaymentRequirements;\n action: string;\n tokenAuthStrategy: TokenAuthStrategy;\n metaTx: BosonMetaTx;\n tokenAuth?: BosonTokenAuth;\n fulfillment?: ResolvedFulfillment;\n buyer: Address;\n}\n\n/** Construct and re-validate the payload, returning the structured object. */\nexport function assemblePayload({\n requirements,\n action,\n tokenAuthStrategy,\n metaTx,\n tokenAuth,\n fulfillment,\n buyer,\n}: AssembleArgs): EscrowPaymentPayload {\n // Fulfillment `data` rides along only for atomic Flow B — Flow A\n // defers it to the redeem POST body. The conditional emission keeps\n // the assembler aligned with the server-side rule-13 validator that\n // rejects `data` on Flow A and requires it on Flow B.\n const fulfillmentSlot =\n fulfillment === undefined\n ? undefined\n : action === \"boson-createOfferCommitAndRedeem\"\n ? { option: fulfillment.option, data: fulfillment.data }\n : { option: fulfillment.option };\n\n const payload: EscrowPaymentPayload = {\n x402Version: X402_VERSION,\n scheme: \"escrow\",\n network: requirements.network,\n payload: {\n action,\n tokenAuthStrategy,\n offerRef: {\n fullOffer: requirements.offer.fullOffer,\n sellerSig: requirements.offer.sellerSig,\n },\n buyer,\n metaTx,\n ...(tokenAuth ? { tokenAuth } : {}),\n },\n ...(fulfillmentSlot ? { fulfillment: fulfillmentSlot } : {}),\n };\n\n // Defensive re-parse — surfaces shape bugs (e.g. malformed hex) before\n // the payload escapes the client.\n parseEscrowPaymentPayload(payload);\n return payload;\n}\n\n/** Build, validate, and base64-encode the payload for the `X-PAYMENT` header. */\nexport function assembleAndEncodePayload(args: AssembleArgs): string {\n const payload = assemblePayload(args);\n return encodeBase64(JSON.stringify(payload));\n}\n","// Cross-platform random helpers.\n//\n// The client is framework-agnostic: it must run in browsers (where\n// `node:crypto` is unavailable) as well as Node. The Web Crypto API\n// (`globalThis.crypto.getRandomValues`) covers both — it's been a Node\n// global since 19 and is universally available in modern browsers.\n// The package's `engines.node` already requires Node ≥ 22, so we can\n// rely on the global without a `node:crypto` fallback.\n//\n// Centralizing the helpers here keeps `pre-commit.ts`, `post-commit.ts`,\n// and `token-auth/erc3009.ts` from each importing their own crypto\n// primitive and re-deriving the same byte → bigint / byte → hex\n// conversion (CLAUDE.md \"Move duplicated constants ... into a shared\n// file the moment they appear in two places\").\n\nimport type { Hex } from \"viem\";\n\n/** Fill a fresh `Uint8Array` of `size` bytes with cryptographically random bytes. */\nexport function randomBytes(size: number): Uint8Array {\n const bytes = new Uint8Array(size);\n if (typeof globalThis.crypto?.getRandomValues !== \"function\") {\n throw new Error(\n \"x402-client: globalThis.crypto.getRandomValues is unavailable — environment lacks the Web Crypto API\",\n );\n }\n globalThis.crypto.getRandomValues(bytes);\n return bytes;\n}\n\n/** 32-byte cryptographically random `0x`-prefixed hex string. */\nexport function randomBytes32(): Hex {\n const bytes = randomBytes(32);\n let hex = \"0x\";\n for (const b of bytes) {\n hex += b.toString(16).padStart(2, \"0\");\n }\n return hex as Hex;\n}\n\n/** Cryptographically random `uint256`. Used for protocol meta-tx replay-protection nonces. */\nexport function randomUint256(): bigint {\n const bytes = randomBytes(32);\n let n = 0n;\n for (const byte of bytes) {\n n = (n << 8n) | BigInt(byte);\n }\n return n;\n}\n","// Sign the buyer's Boson protocol meta-transaction for one of the two\n// commit-time actions:\n//\n// - Flow A — `boson-createOfferAndCommit` (deferred redeem). Signed via\n// `coreSdk.signMetaTxCreateOfferAndCommit`.\n// - Flow B — `boson-createOfferCommitAndRedeem` (atomic commit+redeem\n// via `OrchestrationHandlerFacet2.createOfferCommitAndRedeem`). Signed\n// via `coreSdk.signMetaTxCreateOfferCommitAndRedeem`.\n//\n// Both route through `CoreSDK` directly so the EIP-712 domain, function\n// signature, and calldata encoding stay in lock-step with the deployed\n// protocol. The returned `SignedMetaTx` is shaped exactly as the on-chain\n// `MetaTransactionsHandlerFacet` recovers against; we re-shape it into\n// the escrow scheme's wire-format `BosonMetaTx` for the X-PAYMENT payload.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { FullOfferArgs } from \"@bosonprotocol/common\";\nimport type {\n BosonMetaTx,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\nexport interface SignCreateOfferAndCommitArgs {\n requirements: EscrowPaymentRequirements;\n coreSdk: CoreSDK;\n buyer: Address;\n}\n\n/**\n * Builds the buyer-side meta-tx for `createOfferAndCommit`, signs it via\n * `CoreSDK`, and returns the wire-format envelope ready to be embedded in\n * an `EscrowPaymentPayload`.\n *\n * The `createOfferAndCommitArgs` are reconstructed from the\n * `requirements.offer` triple — the opaque `fullOffer` carries the\n * `Omit<FullOfferArgs, \"signature\">` shape, `sellerSig` becomes the\n * `signature`, and the buyer's address is spliced in as `committer`. Any\n * shape drift between the wire format and `FullOfferArgs` surfaces as a\n * yup validation error from core-sdk's\n * `createOfferAndCommitArgsSchema.validateSync` — propagate it rather than\n * patch silently (CLAUDE.md \"Production over spec when they diverge\").\n */\nexport async function signCreateOfferAndCommit({\n requirements,\n coreSdk,\n buyer,\n}: SignCreateOfferAndCommitArgs): Promise<BosonMetaTx> {\n const nonce = randomUint256();\n\n const createOfferAndCommitArgs = buildCreateOfferAndCommitArgs(requirements, buyer);\n\n const signed = await coreSdk.signMetaTxCreateOfferAndCommit({\n nonce: nonce.toString(),\n createOfferAndCommitArgs,\n });\n\n return reshape(signed, buyer, nonce);\n}\n\n/**\n * Flow B counterpart to {@link signCreateOfferAndCommit} — signs\n * the meta-tx that drives `OrchestrationHandlerFacet2.createOfferCommitAndRedeem`.\n * The argument shape is identical (the protocol uses the same\n * `FullOfferArgs` struct); only the resulting function selector and\n * post-state differ.\n */\nexport async function signCreateOfferCommitAndRedeem({\n requirements,\n coreSdk,\n buyer,\n}: SignCreateOfferAndCommitArgs): Promise<BosonMetaTx> {\n const nonce = randomUint256();\n\n const createOfferAndCommitArgs = buildCreateOfferAndCommitArgs(requirements, buyer);\n\n const signed = await coreSdk.signMetaTxCreateOfferCommitAndRedeem({\n nonce: nonce.toString(),\n createOfferAndCommitArgs,\n });\n\n return reshape(signed, buyer, nonce);\n}\n\nfunction buildCreateOfferAndCommitArgs(\n requirements: EscrowPaymentRequirements,\n buyer: Address,\n): FullOfferArgs {\n return {\n ...(requirements.offer.fullOffer as object),\n signature: requirements.offer.sellerSig,\n committer: buyer,\n } as unknown as FullOfferArgs;\n}\n\nfunction reshape(\n signed: {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n },\n buyer: Address,\n nonce: bigint,\n): BosonMetaTx {\n return {\n from: buyer,\n nonce: nonce.toString(),\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n}\n","// Sign Boson protocol meta-transactions for post-commit buyer actions.\n//\n// These are the transitions the buyer can drive once an exchange exists on\n// chain: redeem the voucher, cancel/complete the exchange, or move through\n// the dispute family. Each is a single-call meta-tx that the\n// server/facilitator submits via\n// `MetaTransactionsHandlerFacet.executeMetaTransaction`. None of them\n// carry a token-auth payload (the funds are already escrowed) so the\n// returned `BosonMetaTx` is the full wire-format the server consumes —\n// usually as a JSON POST body, not an `X-PAYMENT` header.\n//\n// We return both the `BosonMetaTx` envelope (useful for on-chain or MCP\n// channels) and the ABI-encoded `signedPayload` Hex consumed by the\n// server/facilitator HTTP convenience routes. The encoder lives in\n// `@bosonprotocol/x402-evm/codec` so client and facilitator share one\n// implementation.\n//\n// `boson-escalateDispute` is the one exception. If the dispute resolver\n// requires an escalation deposit, the resolver/server can return its own\n// 402 carrying an `escrow` `PaymentRequirements` and the buyer pairs this\n// meta-tx with a token-auth payload — that wrapper lives outside MVP. Here\n// we only sign the meta-tx itself; the deposit flow is a later PR.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { BosonMetaTx, Hex as WireHex } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { ActionId } from \"@bosonprotocol/x402-core/state-machine\";\nimport { encodeSignedPayload } from \"@bosonprotocol/x402-evm/codec\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\n// Matches the subset of ethers' `BigNumberish` core-sdk actually accepts at\n// runtime, without pulling `@ethersproject/bignumber` into this package's\n// declared deps. Callers usually pass decimal strings (the wire format).\ntype BigNumberish = string | number | bigint;\n\n/**\n * Buyer-invokable post-commit action ids — derived from `ActionId` in\n * `@bosonprotocol/x402-core/state-machine` (the single source of truth)\n * by excluding:\n *\n * - the commit-time ids, which the buyer signs via `handle402`;\n * - `boson-revokeVoucher`, which is seller-only;\n * - entity-keyed actions (`boson-withdrawFunds`), which are signed via\n * `client.signWithdrawFunds` / `client.signWithdrawAllAvailableFunds`\n * because they take an `entityId` + token list rather than an\n * `exchangeId`.\n */\ntype BuyerPostCommitActionId = Exclude<\n ActionId,\n | \"boson-createOfferAndCommit\"\n | \"boson-createOfferCommitAndRedeem\"\n | \"boson-revokeVoucher\"\n | \"boson-withdrawFunds\"\n>;\n\n/** Caller-supplied arguments for `client.signAction`. */\nexport type SignActionArgs = SimplePostCommitArgs | ResolveDisputeArgs;\n\ninterface BaseArgs {\n exchangeId: BigNumberish;\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address (the `escrowAddress` from the prior 402). */\n escrowAddress: Address;\n}\n\nexport interface SimplePostCommitArgs extends BaseArgs {\n actionId: Exclude<BuyerPostCommitActionId, \"boson-resolveDispute\">;\n}\n\nexport interface ResolveDisputeArgs extends BaseArgs {\n actionId: \"boson-resolveDispute\";\n /** Buyer share of the disputed amount, in the units the protocol expects (basis points). */\n buyerPercent: BigNumberish;\n /** Counterparty (seller) signature over the proposal. Hex string or `{r, s, v}`. */\n counterpartySig: Hex | { r: Hex; s: Hex; v: number };\n}\n\nexport interface SignPostCommitActionDeps {\n buildCoreSdk: (network: string, escrowAddress: Address) => { coreSdk: CoreSDK; chainId: number };\n getBuyerAddress: () => Promise<Address>;\n}\n\n/**\n * Wire-format result of `signPostCommitAction`: the signed `BosonMetaTx`\n * envelope plus its ABI-encoded `signedPayload` Hex. Pick the one that\n * matches the channel — the server/facilitator HTTP routes consume\n * `signedPayload`; direct on-chain or MCP submissions use `metaTx`.\n */\nexport interface SignedPostCommitAction {\n metaTx: BosonMetaTx;\n /**\n * ABI-encoded `BosonMetaTx` ready to drop into a server / facilitator\n * route's `signedPayload` field. The hex is JSON-serialisable; we type\n * it as the loose wire `Hex` (string) rather than viem's strict\n * `\\`0x\\${string}\\`` so the codec's output matches the schemes module's\n * own `Hex` alias.\n */\n signedPayload: WireHex;\n}\n\n/**\n * Sign a post-commit action through the appropriate `CoreSDK.signMetaTx*`\n * mixin method. Returns both the wire-format `BosonMetaTx` envelope and\n * the ABI-encoded `signedPayload` Hex ready to POST to a server /\n * facilitator route.\n */\nexport async function signPostCommitAction(\n args: SignActionArgs,\n deps: SignPostCommitActionDeps,\n): Promise<SignedPostCommitAction> {\n const nonce = randomUint256();\n const buyer = await deps.getBuyerAddress();\n const { coreSdk } = deps.buildCoreSdk(args.network, args.escrowAddress);\n\n const signed = await callSignMetaTx(coreSdk, args, nonce);\n\n const metaTx: BosonMetaTx = {\n from: buyer,\n nonce: nonce.toString(),\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n\n return { metaTx, signedPayload: encodeSignedPayload(metaTx) };\n}\n\ninterface SignedMetaTxShape {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n}\n\nasync function callSignMetaTx(\n coreSdk: CoreSDK,\n args: SignActionArgs,\n nonce: bigint,\n): Promise<SignedMetaTxShape> {\n const nonceStr = nonce.toString();\n const exchangeId = args.exchangeId;\n\n switch (args.actionId) {\n case \"boson-redeem\":\n return coreSdk.signMetaTxRedeemVoucher({ nonce: nonceStr, exchangeId });\n case \"boson-cancelVoucher\":\n return coreSdk.signMetaTxCancelVoucher({ nonce: nonceStr, exchangeId });\n case \"boson-completeExchange\":\n return coreSdk.signMetaTxCompleteExchange({ nonce: nonceStr, exchangeId });\n case \"boson-raiseDispute\":\n return coreSdk.signMetaTxRaiseDispute({ nonce: nonceStr, exchangeId });\n case \"boson-retractDispute\":\n return coreSdk.signMetaTxRetractDispute({ nonce: nonceStr, exchangeId });\n case \"boson-escalateDispute\":\n return coreSdk.signMetaTxEscalateDispute({ nonce: nonceStr, exchangeId });\n case \"boson-resolveDispute\":\n return coreSdk.signMetaTxResolveDispute({\n nonce: nonceStr,\n exchangeId,\n buyerPercent: args.buyerPercent,\n counterpartySig: args.counterpartySig,\n });\n default: {\n // The discriminated union makes this unreachable at the type level;\n // the `never` annotation enforces exhaustiveness at compile time, and\n // the throw guarantees a clear error if a runtime value ever slips\n // past the type checker.\n const _exhaustive: never = args;\n throw new Error(\n `x402-client: unsupported post-commit action '${(_exhaustive as { actionId: string }).actionId}'`,\n );\n }\n }\n}\n","// Channel-aware submitter for buyer-driven post-commit actions.\n//\n// Given a `NextAction` entry (from a prior server response's\n// `nextActions.next[]`) and a signed payload, walk the action's\n// advertised `channels` in order, intersected with the channels this\n// submitter knows how to drive over HTTP (`server`, `facilitator`).\n// Stop at the first 2xx and return the normalized result; treat 5xx /\n// network errors / timeouts as a signal to fall back; treat 4xx as\n// terminal (a buyer-side payload error fallback can't fix — masking it\n// would hide bugs).\n//\n// `onchain` / `mcp` / `xmtp` channels stay out of this module: the\n// onchain submitter needs a wallet client plumbed through client config\n// and tx-receipt waiting; the agentic channels need a separate\n// `@bosonprotocol/x402-agent` package that isn't shipped. Callers whose\n// `action.channels` only list those will hit `NoCompatibleChannelError`.\n//\n// The server channel returns the rich `{ txHash, nextActions, fulfillment? }`\n// envelope; the facilitator's `/perform-action` returns only\n// `{ ok: true, txHash, newExchangeState, newDisputeState? }`. The result\n// is normalized to the intersection — `nextActions` is surfaced when\n// the server channel handled the action, omitted when the facilitator\n// did (callers that need a fresh envelope after a facilitator fallback\n// can re-derive it server-side or read it from the next response).\n\nimport type { EscrowNextActions, NextAction } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport { DisputeState, ExchangeState, type ActionId } from \"@bosonprotocol/x402-core/state-machine\";\nimport type { Address, Hex } from \"viem\";\n\nimport type { SignedPostCommitAction } from \"./post-commit.js\";\n\n/** Channels this submitter drives over HTTP. */\nexport type SubmitChannel = \"server\" | \"facilitator\";\n\nconst SUBMIT_CHANNELS: readonly SubmitChannel[] = [\"server\", \"facilitator\"];\n\n/**\n * Why a channel attempt didn't yield a 2xx. `\"no-endpoint\"` is a\n * configuration gap (channel advertised, but no URL listed under\n * `action.endpoints`) — distinct from a real transport-level\n * `\"network\"` failure so callers branching on `reason` can tell the\n * two apart. `\"invalid-response\"` covers 2xx replies whose body\n * doesn't match the channel's expected shape — the server replied\n * but with something we can't make sense of, treated as a\n * recoverable failure (the next channel is tried).\n */\nexport type ChannelFailureReason =\n | \"5xx\"\n | \"4xx\"\n | \"network\"\n | \"timeout\"\n | \"no-endpoint\"\n | \"invalid-response\";\n\n/** Per-channel attempt record — every walk-step appended to `attempts[]`. */\nexport type ChannelAttempt =\n | { channel: SubmitChannel; ok: true; status: number }\n | {\n channel: SubmitChannel;\n ok: false;\n reason: ChannelFailureReason;\n status?: number;\n message?: string;\n };\n\n/** Caller passes `{ option, data }` for the redeem-only fulfillment payload. */\nexport interface FulfillmentRequest {\n option: string;\n data: Record<string, unknown> | null;\n}\n\nexport interface SubmitArgs {\n action: NextAction;\n signed: SignedPostCommitAction;\n exchangeId: string;\n /** CAIP-2 (e.g. `\"eip155:31337\"`). Required by the facilitator route. */\n network: string;\n /** Escrow contract address. Required by the facilitator route. */\n escrowAddress: Address;\n /** Redeem-only — forwarded to the `server` channel body; ignored by `facilitator`. */\n fulfillment?: FulfillmentRequest;\n /** Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Per-channel timeout in milliseconds. Defaults to 10000. */\n timeoutMs?: number;\n}\n\nexport interface SubmitResult {\n txHash: Hex;\n newExchangeState: ExchangeState;\n newDisputeState?: DisputeState;\n /** Present only when the `server` channel handled the action. */\n nextActions?: EscrowNextActions;\n channelUsed: SubmitChannel;\n attempts: readonly ChannelAttempt[];\n}\n\n/** Thrown when no advertised channel matches one this submitter can drive. */\nexport class NoCompatibleChannelError extends Error {\n readonly actionId: string;\n readonly advertisedChannels: readonly string[];\n constructor(actionId: string, advertisedChannels: readonly string[]) {\n super(\n `x402-client: action '${actionId}' advertises channels [${advertisedChannels.join(\", \")}] but none are submittable over HTTP (server / facilitator).`,\n );\n this.name = \"NoCompatibleChannelError\";\n this.actionId = actionId;\n this.advertisedChannels = advertisedChannels;\n }\n}\n\n/**\n * Thrown when every attempted channel failed. Carries the per-channel\n * attempt log so callers can branch on the final cause (e.g. 4xx from\n * the server → buyer payload bug; 5xx from both → outage).\n */\nexport class AllChannelsFailedError extends Error {\n readonly attempts: readonly ChannelAttempt[];\n constructor(actionId: string, attempts: readonly ChannelAttempt[]) {\n super(\n `x402-client: action '${actionId}' failed on every attempted channel — ${attempts\n .map((a) => formatAttempt(a))\n .join(\"; \")}`,\n );\n this.name = \"AllChannelsFailedError\";\n this.attempts = attempts;\n }\n}\n\nfunction formatAttempt(a: ChannelAttempt): string {\n if (a.ok) return `${a.channel}=ok(${a.status})`;\n const tail = a.status !== undefined ? `(${a.status})` : \"\";\n return `${a.channel}=${a.reason}${tail}`;\n}\n\n/**\n * Submit a signed post-commit action through the first responsive HTTP\n * channel advertised on `action.channels`. Returns the normalized result\n * on first 2xx; throws `NoCompatibleChannelError` when no submittable\n * channel is advertised, or `AllChannelsFailedError` when every attempt\n * failed.\n */\nexport async function submitAction(args: SubmitArgs): Promise<SubmitResult> {\n const fetcher = args.fetch ?? globalThis.fetch.bind(globalThis);\n const timeoutMs = args.timeoutMs ?? 10_000;\n\n const ordered = orderedChannels(args.action);\n if (ordered.length === 0) {\n throw new NoCompatibleChannelError(args.action.id, args.action.channels);\n }\n\n const attempts: ChannelAttempt[] = [];\n for (const channel of ordered) {\n const endpoint = args.action.endpoints?.[channel];\n if (endpoint === undefined) {\n attempts.push({\n channel,\n ok: false,\n reason: \"no-endpoint\",\n message: `no endpoint advertised for channel '${channel}'`,\n });\n continue;\n }\n\n const outcome = await attemptChannel({\n channel,\n endpoint,\n args,\n fetcher,\n timeoutMs,\n });\n attempts.push(outcome.attempt);\n\n if (outcome.attempt.ok && outcome.result !== undefined) {\n return { ...outcome.result, attempts };\n }\n if (!outcome.attempt.ok && outcome.attempt.reason === \"4xx\") {\n // 4xx is a buyer-payload error — no fallback can fix it; surface it.\n throw new AllChannelsFailedError(args.action.id, attempts);\n }\n }\n\n throw new AllChannelsFailedError(args.action.id, attempts);\n}\n\nfunction orderedChannels(action: NextAction): SubmitChannel[] {\n const seen = new Set<SubmitChannel>();\n const out: SubmitChannel[] = [];\n for (const c of action.channels) {\n if ((SUBMIT_CHANNELS as readonly string[]).includes(c) && !seen.has(c as SubmitChannel)) {\n seen.add(c as SubmitChannel);\n out.push(c as SubmitChannel);\n }\n }\n return out;\n}\n\ninterface AttemptOutcome {\n attempt: ChannelAttempt;\n /** Set when `attempt.ok === true`. */\n result?: Omit<SubmitResult, \"attempts\">;\n}\n\nasync function attemptChannel(input: {\n channel: SubmitChannel;\n endpoint: string;\n args: SubmitArgs;\n fetcher: typeof globalThis.fetch;\n timeoutMs: number;\n}): Promise<AttemptOutcome> {\n const { channel, endpoint, args, fetcher, timeoutMs } = input;\n\n const body = channel === \"server\" ? buildServerBody(args) : buildFacilitatorBody(args);\n\n let res: Response;\n try {\n res = await fetchWithTimeout(fetcher, endpoint, body, timeoutMs);\n } catch (e) {\n const reason = isTimeout(e) ? \"timeout\" : \"network\";\n return {\n attempt: {\n channel,\n ok: false,\n reason,\n message: e instanceof Error ? e.message : String(e),\n },\n };\n }\n\n const parsed = (await res.json().catch(() => null)) as unknown;\n if (res.status >= 500) {\n return {\n attempt: { channel, ok: false, reason: \"5xx\", status: res.status },\n };\n }\n if (!res.ok) {\n return {\n attempt: { channel, ok: false, reason: \"4xx\", status: res.status },\n };\n }\n if (parsed === null || typeof parsed !== \"object\") {\n return {\n attempt: {\n channel,\n ok: false,\n reason: \"invalid-response\",\n status: res.status,\n message: \"response body is not a JSON object\",\n },\n };\n }\n\n try {\n const result =\n channel === \"server\" ? parseServerResult(parsed) : parseFacilitatorResult(parsed);\n return {\n attempt: { channel, ok: true, status: res.status },\n result: { ...result, channelUsed: channel },\n };\n } catch (e) {\n // 2xx body parsed as JSON but doesn't match the expected shape — the\n // server replied with something we can't make sense of. Treat as\n // recoverable so the next channel gets a chance (vs. a 4xx, which\n // is terminal because no other channel can fix the buyer's payload).\n return {\n attempt: {\n channel,\n ok: false,\n reason: \"invalid-response\",\n status: res.status,\n message: e instanceof Error ? e.message : String(e),\n },\n };\n }\n}\n\nfunction buildServerBody(args: SubmitArgs): unknown {\n const body: Record<string, unknown> = {\n exchangeId: args.exchangeId,\n signedPayload: args.signed.signedPayload,\n };\n if (args.action.id === \"boson-redeem\" && args.fulfillment !== undefined) {\n body.fulfillment = args.fulfillment;\n }\n return body;\n}\n\nfunction buildFacilitatorBody(args: SubmitArgs): unknown {\n return {\n action: args.action.id as ActionId,\n exchangeId: args.exchangeId,\n network: args.network,\n escrowAddress: args.escrowAddress,\n signedPayload: args.signed.signedPayload,\n };\n}\n\nasync function fetchWithTimeout(\n fetcher: typeof globalThis.fetch,\n endpoint: string,\n body: unknown,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(new TimeoutError(timeoutMs)), timeoutMs);\n try {\n return await fetcher(endpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n}\n\nclass TimeoutError extends Error {\n readonly isTimeout = true as const;\n constructor(timeoutMs: number) {\n super(`x402-client/submit: channel attempt timed out after ${timeoutMs}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\nfunction isTimeout(e: unknown): boolean {\n if (e instanceof TimeoutError) return true;\n if (typeof e !== \"object\" || e === null) return false;\n const obj = e as { name?: unknown; isTimeout?: unknown; cause?: unknown };\n if (obj.isTimeout === true) return true;\n if (obj.name === \"AbortError\" || obj.name === \"TimeoutError\") return true;\n // `AbortController.abort(reason)` surfaces the reason on `.cause` for\n // fetch implementations that wrap it; check one level deep.\n if (typeof obj.cause === \"object\" && obj.cause !== null) {\n const cause = obj.cause as { isTimeout?: unknown; name?: unknown };\n if (cause.isTimeout === true) return true;\n if (cause.name === \"TimeoutError\") return true;\n }\n return false;\n}\n\nfunction parseServerResult(body: unknown): Omit<SubmitResult, \"attempts\" | \"channelUsed\"> {\n if (typeof body !== \"object\" || body === null) {\n throw new Error(\"server response body is not an object\");\n }\n const raw = body as {\n txHash?: unknown;\n nextActions?: {\n exchangeState?: unknown;\n disputeState?: unknown;\n next?: unknown;\n exchangeId?: unknown;\n fallback?: unknown;\n };\n };\n const txHash = raw.txHash;\n const exchangeState = raw.nextActions?.exchangeState;\n if (!isHexHash(txHash) || !isExchangeState(exchangeState)) {\n throw new Error(\"server response missing txHash or nextActions.exchangeState\");\n }\n const out: Omit<SubmitResult, \"attempts\" | \"channelUsed\"> = {\n txHash,\n newExchangeState: exchangeState,\n nextActions: raw.nextActions as EscrowNextActions,\n };\n if (isDisputeState(raw.nextActions?.disputeState)) {\n out.newDisputeState = raw.nextActions.disputeState;\n }\n return out;\n}\n\nfunction parseFacilitatorResult(body: unknown): Omit<SubmitResult, \"attempts\" | \"channelUsed\"> {\n if (typeof body !== \"object\" || body === null) {\n throw new Error(\"facilitator response body is not an object\");\n }\n const raw = body as {\n ok?: unknown;\n txHash?: unknown;\n newExchangeState?: unknown;\n newDisputeState?: unknown;\n };\n if (raw.ok !== true || !isHexHash(raw.txHash) || !isExchangeState(raw.newExchangeState)) {\n throw new Error(\"facilitator response missing ok/txHash/newExchangeState\");\n }\n const out: Omit<SubmitResult, \"attempts\" | \"channelUsed\"> = {\n txHash: raw.txHash,\n newExchangeState: raw.newExchangeState,\n };\n if (isDisputeState(raw.newDisputeState)) {\n out.newDisputeState = raw.newDisputeState;\n }\n return out;\n}\n\n// Standard EVM tx-hash shape: `0x` + 64 hex chars (32 bytes). Validating\n// here ensures invalid hashes (e.g. test placeholders, garbled\n// payloads) don't slip through as typed-success results that break\n// downstream consumers expecting a real `Hex`.\nconst TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;\n\nfunction isHexHash(v: unknown): v is Hex {\n return typeof v === \"string\" && TX_HASH_RE.test(v);\n}\n\nfunction isExchangeState(v: unknown): v is ExchangeState {\n return typeof v === \"string\" && (Object.values(ExchangeState) as string[]).includes(v);\n}\n\nfunction isDisputeState(v: unknown): v is DisputeState {\n return typeof v === \"string\" && (Object.values(DisputeState) as string[]).includes(v);\n}\n","// Sign Boson protocol meta-transactions for the entity-keyed\n// `boson-withdrawFunds` action.\n//\n// Unlike the buyer-side post-commit signers, withdraw is keyed by the\n// Boson account `entityId` (buyer or seller) rather than an exchange\n// id. The on-chain primitive is\n// `FundsHandlerFacet.withdrawFunds(uint256 entityId, address[] tokenList,\n// uint256[] tokenAmounts)`. The meta-tx variant\n// (`coreSdk.signMetaTxWithdrawFunds`) wraps that calldata in an EIP-712\n// envelope ready for `MetaTransactionsHandlerFacet.executeMetaTransaction`.\n//\n// Scope cap for v1: callers withdraw the *whole* current balance set.\n// `signWithdrawAllAvailableFunds` reads the funds entity from the\n// subgraph, drops zero balances, then delegates to `signWithdrawFunds`\n// for the actual EIP-712 sign. Partial / user-chosen amounts can be\n// added later without a wire-format change.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport {\n DECIMAL_UINT,\n type BosonMetaTx,\n type Hex as WireHex,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport { encodeSignedPayload } from \"@bosonprotocol/x402-evm/codec\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"./utils/crypto.js\";\n\n// Matches the subset of ethers' `BigNumberish` core-sdk actually accepts at\n// runtime, without pulling `@ethersproject/bignumber` into this package's\n// declared deps. Callers usually pass decimal strings (the wire format).\ntype BigNumberish = string | number | bigint;\n\n/**\n * Coerce a caller-supplied `entityId` to its canonical wire form (a\n * non-negative integer decimal string). Rejects NaN, fractional, and\n * negative values up-front — passing them on to core-sdk would either\n * trip a downstream BigInt conversion or, worse, produce a signed\n * payload that always reverts on-chain.\n */\nfunction normalizeEntityId(value: BigNumberish): string {\n if (typeof value === \"bigint\") {\n if (value < 0n) throw new Error(`entityId must be non-negative, got ${value.toString()}`);\n return value.toString();\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0) {\n throw new Error(`entityId must be a non-negative integer, got ${String(value)}`);\n }\n return value.toString();\n }\n // typeof value === \"string\"\n const trimmed = value.trim();\n if (trimmed.length === 0 || !DECIMAL_UINT.test(trimmed)) {\n throw new Error(`entityId must be a decimal non-negative integer string, got \"${value}\"`);\n }\n return trimmed;\n}\n\n/**\n * Resolution targets accepted by the \"withdraw all\" helper. Either\n * pass the raw `entityId` (numeric Boson account id) or an EVM\n * `address` with an optional `role` discriminator for the case where\n * the address maps to both a seller and a buyer entity.\n */\nexport type WithdrawEntitySelector =\n | { entityId: BigNumberish }\n | { address: Address; role?: \"buyer\" | \"seller\" };\n\n/** Arguments accepted by `signWithdrawFunds` (caller-resolved entity + token list). */\nexport interface SignWithdrawFundsArgs {\n entityId: BigNumberish;\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address (the `escrowAddress` from the prior 402). */\n escrowAddress: Address;\n /** Token addresses to withdraw — must align by index with `tokenAmounts`. */\n tokenList: readonly Address[];\n /** Amounts to withdraw — must align by index with `tokenList`. */\n tokenAmounts: readonly BigNumberish[];\n}\n\n/** Arguments accepted by `signWithdrawAllAvailableFunds` — entity + network only. */\nexport type SignWithdrawAllAvailableFundsArgs = WithdrawEntitySelector & {\n /** CAIP-2 network identifier (e.g. `\"eip155:8453\"`). */\n network: string;\n /** Boson Diamond address. */\n escrowAddress: Address;\n};\n\n/** Wire-format result identical in shape to `SignedPostCommitAction`. */\nexport interface SignedWithdrawFunds {\n metaTx: BosonMetaTx;\n signedPayload: WireHex;\n /** Resolved `entityId` (echoed back for caller convenience when looked up by address). */\n entityId: string;\n /** Tokens included in the signature, in calldata order. */\n tokenList: readonly Address[];\n /** Amounts included in the signature, in calldata order. */\n tokenAmounts: readonly string[];\n}\n\nexport interface SignWithdrawDeps {\n buildCoreSdk: (network: string, escrowAddress: Address) => { coreSdk: CoreSDK; chainId: number };\n /** Returns the address that will sign the meta-tx — must match the configured signer. */\n getSignerAddress: () => Promise<Address>;\n}\n\ninterface SignedMetaTxShape {\n functionName: string;\n functionSignature: string;\n r: string;\n s: string;\n v: number;\n}\n\n/** Subset of `CoreSDK` used here — kept narrow so tests can stub easily. */\ninterface WithdrawCoreSdkLike {\n signMetaTxWithdrawFunds(args: {\n nonce: string;\n entityId: BigNumberish;\n tokenList: string[];\n tokenAmounts: BigNumberish[];\n }): Promise<SignedMetaTxShape>;\n getFunds(queryVars: { fundsFilter: { accountId: string } }): Promise<\n Array<{\n accountId: string;\n availableAmount: string;\n token: { address: string };\n }>\n >;\n getSellersByAddress(address: string): Promise<Array<{ id: string }>>;\n getBuyers(queryVars: { buyersFilter: { wallet: string } }): Promise<Array<{ id: string }>>;\n}\n\n/**\n * Sign a `withdrawFunds(entityId, tokenList, tokenAmounts)` meta-tx\n * against the configured Diamond domain. The caller supplies the\n * exact token + amount snapshot to commit to.\n */\nexport async function signWithdrawFunds(\n args: SignWithdrawFundsArgs,\n deps: SignWithdrawDeps,\n): Promise<SignedWithdrawFunds> {\n const normalised: SignWithdrawFundsArgs = {\n ...args,\n entityId: normalizeEntityId(args.entityId),\n };\n const { coreSdk } = deps.buildCoreSdk(normalised.network, normalised.escrowAddress);\n const from = await deps.getSignerAddress();\n return signWithdrawFundsInternal(normalised, coreSdk as unknown as WithdrawCoreSdkLike, from);\n}\n\n/**\n * \"Withdraw all\" sugar. Resolves the entity (by id or by address),\n * reads the funds entity from the subgraph, drops zero balances, and\n * signs `withdrawFunds(entityId, allTokens, allAmounts)`. Throws when\n * the entity has no available funds.\n */\nexport async function signWithdrawAllAvailableFunds(\n args: SignWithdrawAllAvailableFundsArgs,\n deps: SignWithdrawDeps,\n): Promise<SignedWithdrawFunds> {\n const { coreSdk } = deps.buildCoreSdk(args.network, args.escrowAddress);\n const sdk = coreSdk as unknown as WithdrawCoreSdkLike;\n const from = await deps.getSignerAddress();\n const entityId = await resolveEntityIdClientSide(sdk, args);\n const funds = await sdk.getFunds({ fundsFilter: { accountId: entityId } });\n const nonZero = funds.filter((f) => f.availableAmount !== \"0\" && BigInt(f.availableAmount) > 0n);\n if (nonZero.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: entity ${entityId} has no available funds to withdraw`,\n );\n }\n return signWithdrawFundsInternal(\n {\n entityId,\n network: args.network,\n escrowAddress: args.escrowAddress,\n tokenList: nonZero.map((f) => f.token.address as Address),\n tokenAmounts: nonZero.map((f) => f.availableAmount),\n },\n sdk,\n from,\n );\n}\n\nasync function signWithdrawFundsInternal(\n args: SignWithdrawFundsArgs,\n coreSdk: WithdrawCoreSdkLike,\n from: Address,\n): Promise<SignedWithdrawFunds> {\n if (args.tokenList.length !== args.tokenAmounts.length) {\n throw new Error(\n `signWithdrawFunds: tokenList (${args.tokenList.length}) and tokenAmounts (${args.tokenAmounts.length}) must be the same length`,\n );\n }\n const nonce = randomUint256();\n const nonceStr = nonce.toString();\n const signed = await coreSdk.signMetaTxWithdrawFunds({\n nonce: nonceStr,\n entityId: args.entityId,\n tokenList: args.tokenList.map((t) => t),\n tokenAmounts: args.tokenAmounts.map((a) => a),\n });\n\n const metaTx: BosonMetaTx = {\n from,\n nonce: nonceStr,\n functionName: signed.functionName,\n functionSignature: signed.functionSignature as Hex,\n sig: {\n v: Number(signed.v),\n r: signed.r as Hex,\n s: signed.s as Hex,\n },\n };\n\n return {\n metaTx,\n signedPayload: encodeSignedPayload(metaTx),\n entityId: normalizeEntityId(args.entityId),\n tokenList: args.tokenList,\n tokenAmounts: args.tokenAmounts.map((a) => String(a)),\n };\n}\n\nasync function resolveEntityIdClientSide(\n coreSdk: WithdrawCoreSdkLike,\n selector: WithdrawEntitySelector,\n): Promise<string> {\n if (\"entityId\" in selector) return normalizeEntityId(selector.entityId);\n const address = selector.address.toLowerCase();\n const role = selector.role;\n const [sellers, buyers] = await Promise.all([\n role === \"buyer\"\n ? Promise.resolve<Array<{ id: string }>>([])\n : coreSdk.getSellersByAddress(address),\n role === \"seller\"\n ? Promise.resolve<Array<{ id: string }>>([])\n : coreSdk.getBuyers({ buyersFilter: { wallet: address } }),\n ]);\n const sellerIds = sellers.map((s) => s.id);\n const buyerIds = buyers.map((b) => b.id);\n\n if (role === \"seller\") {\n if (sellerIds.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no seller entity found for address ${address}`,\n );\n }\n if (sellerIds.length > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to multiple seller entities (ids ${sellerIds.join(\", \")}); pass entityId to disambiguate`,\n );\n }\n return sellerIds[0]!;\n }\n if (role === \"buyer\") {\n if (buyerIds.length === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no buyer entity found for address ${address}`,\n );\n }\n if (buyerIds.length > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to multiple buyer entities (ids ${buyerIds.join(\", \")}); pass entityId to disambiguate`,\n );\n }\n return buyerIds[0]!;\n }\n\n // role unspecified — exactly-one rule across both sides. Refuse to\n // guess when the address resolves to multiple sellers, multiple\n // buyers, or any combination of the two: the signed payload commits\n // to a single entityId, so silently picking `[0]` would be a bug\n // farm waiting to bite.\n const totalMatches = sellerIds.length + buyerIds.length;\n if (totalMatches === 0) {\n throw new Error(\n `signWithdrawAllAvailableFunds: no seller or buyer entity found for address ${address}`,\n );\n }\n if (totalMatches > 1) {\n throw new Error(\n `signWithdrawAllAvailableFunds: address ${address} resolves to ${describeClientMatches(sellerIds, buyerIds)}; pass role and/or entityId to disambiguate`,\n );\n }\n if (sellerIds.length === 1) return sellerIds[0]!;\n return buyerIds[0]!;\n}\n\nfunction describeClientMatches(sellerIds: string[], buyerIds: string[]): string {\n const parts: string[] = [];\n if (sellerIds.length > 0) {\n parts.push(\n sellerIds.length === 1\n ? `seller (id ${sellerIds[0]})`\n : `${sellerIds.length} sellers (ids ${sellerIds.join(\", \")})`,\n );\n }\n if (buyerIds.length > 0) {\n parts.push(\n buyerIds.length === 1\n ? `buyer (id ${buyerIds[0]})`\n : `${buyerIds.length} buyers (ids ${buyerIds.join(\", \")})`,\n );\n }\n return parts.join(\" and \");\n}\n","// Client-side deadline for token-auth signatures (ERC-3009 `validBefore`,\n// EIP-2612 `deadline`, Permit2 `deadline`).\n//\n// The facilitator validates strictly: `deadline − facilitatorNow ≤\n// requirements.maxTimeoutSeconds`. If the client signs at the boundary\n// (`floor(clientNow) + maxTimeoutSeconds`), any moment where the\n// verifier's wall-clock lags the signer's by ≥ 1 s pushes the gap\n// over `maxTimeoutSeconds` and the facilitator rejects with\n// BAD_TOKEN_AUTH_SIGNATURE. Docker Desktop's container clock drifting\n// behind the host clock makes this happen randomly in the e2e suite.\n//\n// We pull the deadline closer to `clientNow` by a small margin so the\n// facilitator's check tolerates that backward skew. 60 s comfortably\n// covers Docker drift and leaves a useful validity window even at the\n// spec's example `maxTimeoutSeconds = 300`.\n\nexport const TOKEN_AUTH_DEADLINE_SAFETY_MARGIN_SECONDS = 60;\n\nexport function computeTokenAuthDeadline(\n maxTimeoutSeconds: number,\n now: () => number = Date.now,\n): number {\n // Clamp so the margin can never make the deadline retroactive — if\n // the caller's `maxTimeoutSeconds < 60`, subtracting the full margin\n // would emit an already-expired signature.\n const timeoutSeconds = Math.max(1, Math.floor(maxTimeoutSeconds));\n const safetyMarginSeconds = Math.min(\n TOKEN_AUTH_DEADLINE_SAFETY_MARGIN_SECONDS,\n Math.max(0, timeoutSeconds - 1),\n );\n return Math.floor(now() / 1000) + timeoutSeconds - safetyMarginSeconds;\n}\n","// Build and sign the buyer's ERC-3009 `ReceiveWithAuthorization` for the\n// escrow contract via `CoreSDK.signReceiveWithErc3009Authorization`.\n//\n// The SDK generates a 32-byte random nonce internally, builds the EIP-712\n// typed-data against the token's domain (taken from `tokenDomainResolver`),\n// signs through the configured `Web3LibAdapter`, and returns a\n// `TransferAuthorization` with `{ strategy, data: { validAfter, validBefore,\n// nonce }, r, s, v, signature }`. We re-shape the result into the\n// `Erc3009AuthData` slot of the escrow payment payload.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n Erc3009AuthData,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { parseChainId } from \"../core-sdk-factory.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nexport interface SignErc3009Args {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n tokenDomainResolver: TokenDomainResolver;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the ERC-3009 typed-data, sign it via core-sdk, and shape the result\n * into the `Erc3009AuthData` slot of the escrow payment payload.\n */\nexport async function signErc3009({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver,\n now = Date.now,\n}: SignErc3009Args): Promise<Erc3009AuthData> {\n const chainId = parseChainId(requirements.network);\n const domain = await tokenDomainResolver(requirements.asset as Address, chainId);\n\n const validAfter = 0;\n const validBefore = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n\n const result = await coreSdk.signReceiveWithErc3009Authorization(\n requirements.asset,\n { name: domain.name, version: domain.version },\n requirements.amount,\n validAfter,\n validBefore,\n { spender: requirements.escrowAddress as `0x${string}` },\n );\n\n return {\n from: buyer,\n to: requirements.escrowAddress,\n value: requirements.amount,\n validAfter: Number(result.data.validAfter),\n validBefore: Number(result.data.validBefore),\n nonce: result.data.nonce as Hex,\n v: result.v,\n r: result.r as Hex,\n s: result.s as Hex,\n };\n}\n","// Build and sign the buyer's EIP-2612 `Permit` for the escrow contract via\n// `CoreSDK.signReceiveWithErc2612Permit`.\n//\n// The SDK fetches the token's `nonces(owner)` via `web3Lib.call(...)` before\n// signing — that path requires the client's `signerToWeb3LibAdapter` to have\n// been built with a configured `PublicClient`. Without one, the underlying\n// `eth_call` rejects with a clear \"no PublicClient configured\" error,\n// surfaced to the caller as a sign-time failure.\n//\n// The SDK returns `{ strategy: \"EIP2612\", data: { deadline }, r, s, v,\n// signature }` — note that the nonce *is not* part of `data`. The wire\n// format `PermitAuthData` carries the nonce because the facilitator's\n// verification path needs it to rebuild the digest the buyer signed (the\n// on-chain `permit()` call refetches the current nonce, but the signature\n// is locked to the value at sign time). We recover it from the SDK's\n// signed typed-data by paying a second on-chain read of `nonces(owner)`;\n// in practice the value the SDK signed against is the one we observe\n// (only an interleaved successful `permit()` between sign and read would\n// shift it, which would then have invalidated the signature anyway).\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n EscrowPaymentRequirements,\n PermitAuthData,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport {\n encodeFunctionData,\n decodeFunctionResult,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\n\nimport { parseChainId } from \"../core-sdk-factory.js\";\nimport { UnsupportedTokenAuthError } from \"../errors.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nconst NONCES_ABI = [\n {\n type: \"function\",\n name: \"nonces\",\n stateMutability: \"view\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ type: \"uint256\" }],\n },\n] as const;\n\nexport interface SignPermitArgs {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n tokenDomainResolver: TokenDomainResolver;\n /** PublicClient for the chain — required to recover the nonce that the SDK signed against. */\n publicClient: PublicClient;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the EIP-2612 Permit typed-data, sign it via core-sdk, look up the\n * token nonce the SDK signed against, and shape the result into the\n * `PermitAuthData` slot of the escrow payment payload.\n */\nexport async function signPermit({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver,\n publicClient,\n now = Date.now,\n}: SignPermitArgs): Promise<PermitAuthData> {\n const chainId = parseChainId(requirements.network);\n const domain = await tokenDomainResolver(requirements.asset as Address, chainId);\n\n const noncePreSign = await readNonce(publicClient, requirements.asset as Address, buyer);\n const deadline = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n\n const result = await coreSdk.signReceiveWithErc2612Permit(\n requirements.asset,\n { name: domain.name, version: domain.version },\n requirements.amount,\n deadline,\n { spender: requirements.escrowAddress as `0x${string}` },\n );\n\n const noncePostSign = await readNonce(publicClient, requirements.asset as Address, buyer);\n if (noncePreSign !== noncePostSign) {\n // A successful `permit()` for this owner landed on-chain between our\n // two reads, which means the SDK signed against either nonce. We can't\n // tell which without re-signing, so fail loudly.\n throw new UnsupportedTokenAuthError(\n `x402-client: token nonce shifted during permit signing (was ${noncePreSign}, now ${noncePostSign}); retry`,\n );\n }\n\n return {\n owner: buyer,\n spender: requirements.escrowAddress,\n value: requirements.amount,\n deadline,\n nonce: noncePreSign.toString(),\n v: result.v,\n r: result.r as Hex,\n s: result.s as Hex,\n };\n}\n\nasync function readNonce(\n publicClient: PublicClient,\n token: Address,\n owner: Address,\n): Promise<bigint> {\n const result = await publicClient.call({\n to: token as `0x${string}`,\n data: encodeFunctionData({\n abi: NONCES_ABI,\n functionName: \"nonces\",\n args: [owner as `0x${string}`],\n }),\n });\n if (!result.data) {\n throw new UnsupportedTokenAuthError(\n `x402-client: token ${token} did not return data for nonces(${owner}) — does it implement EIP-2612?`,\n );\n }\n return decodeFunctionResult({\n abi: NONCES_ABI,\n functionName: \"nonces\",\n data: result.data,\n });\n}\n","// Build and sign the buyer's Uniswap Permit2 `PermitTransferFrom` for the\n// escrow contract via `CoreSDK.signReceiveWithPermit2`.\n//\n// The SDK accepts an optional `permit2Nonce` override; if omitted it\n// generates a random uint256. We pass one explicitly via `randomUint256()`\n// so tests can stub the RNG and so the value never depends on the SDK's\n// internal nonce-generation surface. The Permit2 contract address comes\n// from the wire-format `requirements.onchainHints?.permit2` when present,\n// or falls back to the canonical CREATE2 vanity address re-exported from\n// `@bosonprotocol/x402-core/eip712/token-auth`.\n//\n// Result shape from core-sdk:\n// { strategy: \"Permit2\", data: { nonce, deadline }, r, s, v, signature }\n// — we lift it into the wire-format `Permit2AuthData`.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport { PERMIT2_ADDRESS } from \"@bosonprotocol/x402-core/eip712/token-auth\";\nimport type {\n EscrowPaymentRequirements,\n Permit2AuthData,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, Hex } from \"viem\";\n\nimport { randomUint256 } from \"../utils/crypto.js\";\n\nimport { computeTokenAuthDeadline } from \"./deadline.js\";\n\nexport interface SignPermit2Args {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n /** Override the wall-clock; injected by tests for determinism. Defaults to `Date.now()`. */\n now?: () => number;\n}\n\n/**\n * Build the Permit2 `PermitTransferFrom` typed-data, sign it via core-sdk,\n * and shape the result into the `Permit2AuthData` slot of the escrow\n * payment payload.\n */\nexport async function signPermit2({\n requirements,\n buyer,\n coreSdk,\n now = Date.now,\n}: SignPermit2Args): Promise<Permit2AuthData> {\n const deadline = computeTokenAuthDeadline(requirements.maxTimeoutSeconds, now);\n const permit2Nonce = randomUint256();\n\n // `buyer` is exposed in the call site for symmetry with the other\n // strategies and to keep the function signature stable as we add\n // explicit-`user` overrides. Today the SDK derives `user` internally\n // from `coreSdk._web3Lib.getSignerAddress()`, which we route through the\n // configured `signer.getAddress()` in `signerToWeb3LibAdapter`.\n void buyer;\n\n const result = await coreSdk.signReceiveWithPermit2(\n requirements.asset,\n requirements.amount,\n deadline,\n {\n spender: requirements.escrowAddress as `0x${string}`,\n permit2Address: PERMIT2_ADDRESS,\n permit2Nonce,\n },\n );\n\n return {\n permitted: { token: requirements.asset, amount: requirements.amount },\n spender: requirements.escrowAddress,\n nonce: permit2Nonce.toString(),\n deadline,\n signature: result.signature as Hex,\n };\n}\n","// Token-authorization strategy dispatcher.\n//\n// Picks one of the buyer-side strategies (`erc3009`, `permit`, `permit2`)\n// from `requirements.tokenAuthStrategies`, signs the corresponding payload\n// via `CoreSDK`, and returns the wire-format `BosonTokenAuth` slot. The\n// `none` strategy is encoded by the absence of `tokenAuth` on the payload\n// — callers handle it outside this module.\n//\n// Preference order when the server advertises multiple strategies:\n// `erc3009` → `permit2` → `permit`. ERC-3009 is preferred for tokens that\n// support it (USDC, USDP, EUROC, etc.) because the receive-variant\n// eliminates relayer front-running. Permit2 is preferred over Permit for\n// tokens behind the canonical Permit2 contract because it carries a\n// caller-controllable nonce. Permit is the fallback.\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type {\n BosonTokenAuth,\n EscrowPaymentRequirements,\n TokenAuthStrategy,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address, PublicClient } from \"viem\";\n\nimport { UnsupportedTokenAuthError } from \"../errors.js\";\nimport type { TokenDomainResolver } from \"../types.js\";\n\nimport { signErc3009 } from \"./erc3009.js\";\nimport { signPermit } from \"./permit.js\";\nimport { signPermit2 } from \"./permit2.js\";\n\nexport interface BuildTokenAuthArgs {\n requirements: EscrowPaymentRequirements;\n buyer: Address;\n coreSdk: CoreSDK;\n /** Required for ERC-3009 and EIP-2612 Permit; not used by Permit2. */\n tokenDomainResolver?: TokenDomainResolver;\n /** Optional PublicClient for the requirements' chain. Required for Permit. */\n publicClient?: PublicClient;\n now?: () => number;\n}\n\nexport interface BuiltTokenAuth {\n strategy: TokenAuthStrategy;\n tokenAuth: BosonTokenAuth;\n}\n\nconst STRATEGY_PREFERENCE: readonly TokenAuthStrategy[] = [\"erc3009\", \"permit2\", \"permit\"];\n\nfunction strategyIsAvailable(s: TokenAuthStrategy, args: BuildTokenAuthArgs): boolean {\n switch (s) {\n case \"erc3009\":\n return args.tokenDomainResolver !== undefined;\n case \"permit\":\n return args.tokenDomainResolver !== undefined && args.publicClient !== undefined;\n case \"permit2\":\n return true;\n case \"none\":\n return false;\n default: {\n const _exhaustive: never = s;\n void _exhaustive;\n return false;\n }\n }\n}\n\n/**\n * Pick the highest-preference strategy from `requirements.tokenAuthStrategies`,\n * sign the corresponding payload via core-sdk, and return the wire-format\n * `BosonTokenAuth` slot.\n *\n * The picker is capability-aware: a strategy is only chosen when the runtime\n * config has the prerequisites for it (e.g. `tokenDomainResolver` for\n * ERC-3009, both `tokenDomainResolver` and `publicClient` for Permit). This\n * lets a deployment without `tokenDomainResolver` still satisfy servers that\n * advertise `[\"erc3009\", \"permit2\"]` by falling back to Permit2.\n */\nexport async function buildAndSignTokenAuth(args: BuildTokenAuthArgs): Promise<BuiltTokenAuth> {\n const advertised = args.requirements.tokenAuthStrategies;\n const chosen = STRATEGY_PREFERENCE.find(\n (s) => advertised.includes(s) && strategyIsAvailable(s, args),\n );\n if (!chosen) {\n throw new UnsupportedTokenAuthError(\n `server advertises tokenAuthStrategies=[${advertised.join(\", \")}]; ` +\n `client supports [${STRATEGY_PREFERENCE.join(\", \")}] but none are usable ` +\n `with the current X402bClientConfig ` +\n `(ERC-3009 and Permit require tokenDomainResolver; Permit also requires ` +\n `a PublicClient for the requirements' chain via publicClients)`,\n );\n }\n\n switch (chosen) {\n case \"erc3009\": {\n if (!args.tokenDomainResolver) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'erc3009' but no tokenDomainResolver is configured — pass tokenDomainResolver in X402bClientConfig\",\n );\n }\n const data = await signErc3009({\n ...args,\n tokenDomainResolver: args.tokenDomainResolver,\n });\n return { strategy: \"erc3009\", tokenAuth: { kind: \"erc3009\", data } };\n }\n case \"permit\": {\n if (!args.tokenDomainResolver) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'permit' but no tokenDomainResolver is configured — pass tokenDomainResolver in X402bClientConfig\",\n );\n }\n if (!args.publicClient) {\n throw new UnsupportedTokenAuthError(\n \"server advertises 'permit' but no PublicClient is configured for this chain — pass publicClients in X402bClientConfig\",\n );\n }\n const data = await signPermit({\n ...args,\n tokenDomainResolver: args.tokenDomainResolver,\n publicClient: args.publicClient,\n });\n return { strategy: \"permit\", tokenAuth: { kind: \"permit\", data } };\n }\n case \"permit2\": {\n const data = await signPermit2(args);\n return { strategy: \"permit2\", tokenAuth: { kind: \"permit2\", data } };\n }\n case \"none\": {\n // Should never reach: `STRATEGY_PREFERENCE` doesn't include \"none\",\n // so a server advertising only \"none\" falls through to the error\n // above. Keep the case for exhaustiveness against\n // `TokenAuthStrategy`.\n throw new UnsupportedTokenAuthError(\n \"tokenAuthStrategy='none' has no client-side signing — callers handle it without invoking this dispatcher\",\n );\n }\n default: {\n const _exhaustive: never = chosen;\n throw new UnsupportedTokenAuthError(\n `unrecognised tokenAuthStrategy '${(_exhaustive as { toString(): string }).toString()}'`,\n );\n }\n }\n}\n","// Top-level `createX402bClient` factory.\n//\n// Wires the action picker, token-auth strategy dispatcher, meta-tx signer\n// (via `CoreSDK`), fulfillment resolver, and payload assembler into:\n//\n// - `handle402(requirements)` — commit-time flow that emits the base64\n// `X-PAYMENT` value for the 402 retry.\n// - `signAction(args)` — post-commit flow that signs one of the buyer's\n// follow-up meta-transactions (redeem / cancel / complete / dispute\n// family). No token-auth or X-PAYMENT wrapping; the caller picks a\n// channel and POSTs the wire envelope.\n\nimport {\n parseEscrowPaymentRequirements,\n type EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Address } from \"viem\";\n\nimport { pickAction } from \"./action.js\";\nimport { createCoreSdkFactory } from \"./core-sdk-factory.js\";\nimport { resolveFulfillment } from \"./fulfillment.js\";\nimport { assembleAndEncodePayload } from \"./payload.js\";\nimport { signCreateOfferAndCommit, signCreateOfferCommitAndRedeem } from \"./pre-commit.js\";\nimport {\n signPostCommitAction,\n type SignActionArgs,\n type SignedPostCommitAction,\n} from \"./post-commit.js\";\nimport { parsePaymentResponse } from \"./response.js\";\nimport {\n submitAction as submitActionInner,\n type FulfillmentRequest,\n type SubmitResult,\n} from \"./submit.js\";\nimport {\n signWithdrawAllAvailableFunds,\n signWithdrawFunds,\n type SignWithdrawAllAvailableFundsArgs,\n type SignWithdrawFundsArgs,\n type SignedWithdrawFunds,\n} from \"./withdraw.js\";\nimport { buildAndSignTokenAuth } from \"./token-auth/index.js\";\nimport { MaxAmountExceededError, UnsupportedTokenAuthError } from \"./errors.js\";\nimport type { ExchangeSummary, X402bClientConfig } from \"./types.js\";\nimport type { EscrowNextActions } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\n/**\n * Args for `client.submitAction`. Layered over `SignActionArgs`: the\n * client signs the meta-tx, then resolves the matching `NextAction`\n * entry on `priorNextActions` and walks its `channels[]` (server →\n * facilitator) until the first 2xx. See `submit.ts` for the channel\n * walk semantics; see `signAction` for the signing args.\n */\nexport type SubmitActionArgs = SignActionArgs & {\n /**\n * The `nextActions` envelope returned by the prior server response.\n * Used to read `channels[]` + `endpoints[channel]` for the entry\n * matching `actionId`.\n */\n priorNextActions: EscrowNextActions;\n /** Redeem-only fulfillment payload — forwarded to the `server` channel body. */\n fulfillment?: FulfillmentRequest;\n /** Override the default `globalThis.fetch`. Useful for tests / custom transports. */\n fetch?: typeof globalThis.fetch;\n /** Per-channel timeout in milliseconds. Default 10000. */\n timeoutMs?: number;\n};\n\nexport interface X402bClient {\n /**\n * Consume a parsed escrow PaymentRequirements and return the base64\n * value to set as the `X-PAYMENT` header on the retry.\n */\n handle402(requirements: unknown): Promise<string>;\n\n /**\n * Sign a Boson protocol meta-transaction for a buyer-driven post-commit\n * action (redeem, cancel, complete, dispute family). Returns both the\n * wire-format `BosonMetaTx` envelope and the ABI-encoded `signedPayload`\n * Hex — pick the shape that matches the chosen channel. Server /\n * facilitator HTTP routes consume `signedPayload` directly (e.g. as\n * the `signedPayload` field on the JSON POST body to the endpoint the\n * prior response advertised under `actions.next[].endpoints.server`);\n * on-chain and MCP channels use the `metaTx` object.\n *\n * Note: `boson-escalateDispute` signs only the meta-tx. If the dispute\n * resolver requires an escalation deposit, the resolver/server returns\n * its own 402 with an `escrow` `PaymentRequirements` and the buyer pairs\n * this meta-tx with a token-auth payload — the deposit wrapper is out\n * of MVP.\n */\n signAction(args: SignActionArgs): Promise<SignedPostCommitAction>;\n\n /**\n * Sign a buyer post-commit action via {@link X402bClient.signAction} and\n * submit it through the first responsive HTTP channel the seller\n * advertised on the matching `nextActions.next[]` entry. Order is taken\n * from `priorNextActions` (the envelope from the prior server response);\n * the walk is intersected with `[\"server\", \"facilitator\"]` — `onchain` /\n * `mcp` / `xmtp` channels are out of scope for this method.\n *\n * Falls back to the next channel on **5xx / network error / timeout**.\n * Stops and throws on **4xx** (a buyer-side payload error fallback\n * can't fix — masking it would hide bugs). Throws\n * `NoCompatibleChannelError` when the matching entry advertises only\n * non-HTTP channels, and `AllChannelsFailedError` when every attempt\n * failed.\n *\n * Pre-existing callers that prefer to keep submission outside the SDK\n * can still use `signAction` + their own dispatch.\n */\n submitAction(args: SubmitActionArgs): Promise<SubmitResult>;\n\n /**\n * Sign a `withdrawFunds(entityId, tokenList, tokenAmounts)` meta-tx.\n * Caller-resolved entity + tokens snapshot — see\n * `signWithdrawAllAvailableFunds` for the read-from-subgraph \"withdraw\n * everything\" sugar.\n */\n signWithdrawFunds(args: SignWithdrawFundsArgs): Promise<SignedWithdrawFunds>;\n\n /**\n * Read available funds for the given entity from the subgraph and\n * sign a meta-tx withdrawing the entire current balance set. Accepts\n * either an `entityId` directly or an `address` (with optional\n * `role` for ambiguous wallets).\n */\n signWithdrawAllAvailableFunds(\n args: SignWithdrawAllAvailableFundsArgs,\n ): Promise<SignedWithdrawFunds>;\n\n /**\n * Best-effort decode of `X-PAYMENT-RESPONSE` after a successful retry.\n * Returns `undefined` when the header isn't present.\n */\n parsePaymentResponse(response: {\n headers: { get(name: string): string | null };\n }): ExchangeSummary | undefined;\n}\n\n/**\n * Build a stateless client bound to a buyer signer + policy. The\n * underlying `CoreSDK` is built lazily per `(chainId, escrowAddress)` and\n * cached across calls — both `handle402` and `signAction` reuse it.\n */\nexport function createX402bClient(config: X402bClientConfig): X402bClient {\n const buildCoreSdk = createCoreSdkFactory(config.signer, config);\n\n const getBuyerAddress = async () => (await config.signer.getAddress()) as Address;\n\n return {\n async handle402(rawRequirements) {\n const requirements: EscrowPaymentRequirements =\n parseEscrowPaymentRequirements(rawRequirements);\n\n const action = pickAction(requirements, config.policy);\n const fulfillment = resolveFulfillment(requirements, config);\n enforceMaxAmount(requirements.amount, config.policy?.maxAmount);\n const buyer = await getBuyerAddress();\n\n const { coreSdk, chainId } = buildCoreSdk(\n requirements.network,\n requirements.escrowAddress as Address,\n );\n\n // `policy.tokenAuthStrategy` forces a specific strategy from the\n // server's advertised set instead of letting the dispatcher pick\n // by preference. The forced value must be in\n // `requirements.tokenAuthStrategies`; otherwise the override is\n // rejected. `\"none\"` short-circuits the dispatcher entirely (the\n // buyer has approved the escrow off-band and the payment rides\n // the protocol's `safeTransferFrom` fallback); for the other\n // strategies the dispatcher is invoked with the advertised set\n // narrowed to a single element so it must pick the requested one.\n let tokenAuth: Awaited<ReturnType<typeof buildAndSignTokenAuth>>[\"tokenAuth\"] | undefined;\n let strategy: Awaited<ReturnType<typeof buildAndSignTokenAuth>>[\"strategy\"];\n const forcedStrategy = config.policy?.tokenAuthStrategy;\n if (forcedStrategy !== undefined) {\n if (!requirements.tokenAuthStrategies.includes(forcedStrategy)) {\n throw new UnsupportedTokenAuthError(\n `policy.tokenAuthStrategy \"${forcedStrategy}\" is not in requirements.tokenAuthStrategies (${requirements.tokenAuthStrategies.join(\", \")})`,\n );\n }\n if (forcedStrategy === \"none\") {\n strategy = \"none\";\n tokenAuth = undefined;\n } else {\n const built = await buildAndSignTokenAuth({\n requirements: { ...requirements, tokenAuthStrategies: [forcedStrategy] },\n buyer,\n coreSdk,\n tokenDomainResolver: config.tokenDomainResolver,\n publicClient: config.publicClients?.[chainId],\n });\n strategy = built.strategy;\n tokenAuth = built.tokenAuth;\n }\n } else {\n const built = await buildAndSignTokenAuth({\n requirements,\n buyer,\n coreSdk,\n tokenDomainResolver: config.tokenDomainResolver,\n publicClient: config.publicClients?.[chainId],\n });\n strategy = built.strategy;\n tokenAuth = built.tokenAuth;\n }\n\n // Flow B (boson-createOfferCommitAndRedeem) carries the buyer's\n // delivery data along with the commit-time payload — there's no\n // later round trip in which to attach it. Flow A defers `data` to\n // the redeem-time POST body; `assemblePayload` handles the\n // conditional emission based on `action`.\n const signMetaTx =\n action === \"boson-createOfferCommitAndRedeem\"\n ? signCreateOfferCommitAndRedeem\n : signCreateOfferAndCommit;\n const metaTx = await signMetaTx({ requirements, coreSdk, buyer });\n\n return assembleAndEncodePayload({\n requirements,\n action,\n tokenAuthStrategy: strategy,\n metaTx,\n tokenAuth,\n fulfillment,\n buyer,\n });\n },\n\n signAction(args) {\n return signPostCommitAction(args, { buildCoreSdk, getBuyerAddress });\n },\n\n async submitAction(args) {\n const signed = await signPostCommitAction(args, { buildCoreSdk, getBuyerAddress });\n const action = args.priorNextActions.next.find((entry) => entry.id === args.actionId);\n if (action === undefined) {\n throw new Error(\n `x402-client/submitAction: actionId '${args.actionId}' is not present in priorNextActions.next[]`,\n );\n }\n const submitArgs = {\n action,\n signed,\n exchangeId: String(args.exchangeId),\n network: args.network,\n escrowAddress: args.escrowAddress,\n fulfillment: args.fulfillment,\n fetch: args.fetch,\n timeoutMs: args.timeoutMs,\n };\n return submitActionInner(submitArgs);\n },\n\n signWithdrawFunds(args) {\n return signWithdrawFunds(args, { buildCoreSdk, getSignerAddress: getBuyerAddress });\n },\n\n signWithdrawAllAvailableFunds(args) {\n return signWithdrawAllAvailableFunds(args, {\n buildCoreSdk,\n getSignerAddress: getBuyerAddress,\n });\n },\n\n parsePaymentResponse(response) {\n return parsePaymentResponse(response);\n },\n };\n}\n\nfunction enforceMaxAmount(amount: string, maxAmount?: string): void {\n if (maxAmount === undefined) {\n return;\n }\n\n const amountBigInt = BigInt(amount);\n const maxAmountBigInt = BigInt(maxAmount);\n if (amountBigInt > maxAmountBigInt) {\n throw new MaxAmountExceededError(\n `x402-client: requirements.amount ${amount} exceeds policy.maxAmount ${maxAmount}`,\n );\n }\n}\n","// Translator that wraps a Boson `Web3LibAdapter` (e.g. an `EthersAdapter`\n// from `@bosonprotocol/ethers-sdk`) as an x402-client `Signer`. The point\n// is to let consumers who already hold an adapter for the deployed Boson\n// protocol reuse it with `createX402bClient` without writing the shim\n// themselves — and without forcing this package to take `ethers` (or\n// `@bosonprotocol/common`) as a peer dep.\n//\n// Structural typing keeps the coupling minimal: `Web3LibAdapterLike` picks\n// only the two methods we actually invoke. The consumer's own `ethers` /\n// `@bosonprotocol/ethers-sdk` install carries the full types — an\n// `EthersAdapter` instance satisfies `Web3LibAdapterLike` by shape.\n//\n// Note on `EIP712Domain` injection: `eth_signTypedData_v4` (and the\n// `EthersAdapter` JSON path) expects `types.EIP712Domain` to be present\n// and to match exactly the fields populated on `domain`. We derive it\n// from `domain`'s field presence — the same rule viem applies internally\n// in `getTypesForEIP712Domain`.\n\nimport {\n getAddress,\n serializeTypedData,\n type Address,\n type Hex,\n type TypedDataDomain,\n type TypedDataDefinition,\n type TypedDataParameter,\n} from \"viem\";\n\nimport type { Signer } from \"./types.js\";\n\n/**\n * Structural subset of `@bosonprotocol/common`'s `Web3LibAdapter` that\n * {@link signerFromEthersAdapter} actually exercises. An `EthersAdapter`\n * from `@bosonprotocol/ethers-sdk` (or any future concrete adapter)\n * satisfies this shape without an explicit cast.\n */\nexport interface Web3LibAdapterLike {\n getSignerAddress(): Promise<string>;\n send(method: string, params: readonly unknown[]): Promise<unknown>;\n}\n\n/**\n * Wrap a Boson `Web3LibAdapter`-shaped object as an x402-client\n * {@link Signer}. `signTypedData` builds the standard\n * `eth_signTypedData_v4` JSON payload (including a derived\n * `EIP712Domain` type list) and routes it through `adapter.send`.\n */\nexport function signerFromEthersAdapter(adapter: Web3LibAdapterLike): Signer {\n const resolveAddress = async (): Promise<Address> => getAddress(await adapter.getSignerAddress());\n return {\n getAddress: resolveAddress,\n signTypedData: async ({ domain, types, primaryType, message }) => {\n const from = await resolveAddress();\n const typedData = {\n domain,\n types: { ...types, EIP712Domain: deriveEip712DomainType(domain) },\n primaryType,\n message,\n };\n const json = serializeTypedData(typedData as unknown as TypedDataDefinition);\n const sig = await adapter.send(\"eth_signTypedData_v4\", [from, json]);\n if (typeof sig !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(sig)) {\n throw new Error(\n \"signerFromEthersAdapter: adapter.send did not return a hex signature string\",\n );\n }\n return sig as Hex;\n },\n };\n}\n\n/**\n * Build the `EIP712Domain` type-list from the fields actually present on\n * `domain`, in the canonical EIP-712 order (`name`, `version`, `chainId`,\n * `verifyingContract`, `salt`). Matches viem's internal derivation so the\n * resulting digest agrees with what a viem signer would produce.\n */\nfunction deriveEip712DomainType(domain: TypedDataDomain): readonly TypedDataParameter[] {\n const fields: TypedDataParameter[] = [];\n if (domain.name !== undefined) fields.push({ name: \"name\", type: \"string\" });\n if (domain.version !== undefined) fields.push({ name: \"version\", type: \"string\" });\n if (domain.chainId !== undefined) fields.push({ name: \"chainId\", type: \"uint256\" });\n if (domain.verifyingContract !== undefined)\n fields.push({ name: \"verifyingContract\", type: \"address\" });\n if (domain.salt !== undefined) fields.push({ name: \"salt\", type: \"bytes32\" });\n return fields;\n}\n"]}
|