kawasekit 0.1.0-beta.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/asset-domain-4Ioxqn28.d.cts +348 -0
  2. package/dist/asset-domain-4Ioxqn28.d.ts +348 -0
  3. package/dist/{chunk-YMABXRCK.js → chunk-6CNAYQOL.js} +2 -2
  4. package/dist/chunk-6CNAYQOL.js.map +1 -0
  5. package/dist/{chunk-E2EG72U2.js → chunk-SMAZUZFO.js} +4 -9
  6. package/dist/chunk-SMAZUZFO.js.map +1 -0
  7. package/dist/{chunk-RUWCCP37.js → chunk-THTVJZ2Q.js} +5 -10
  8. package/dist/chunk-THTVJZ2Q.js.map +1 -0
  9. package/dist/{chunk-VPRR3TNA.js → chunk-VXZHS74W.js} +59 -51
  10. package/dist/chunk-VXZHS74W.js.map +1 -0
  11. package/dist/{chunk-UQ7WJY6O.js → chunk-XRSZTZVZ.js} +2 -2
  12. package/dist/{chunk-UQ7WJY6O.js.map → chunk-XRSZTZVZ.js.map} +1 -1
  13. package/dist/cli/index.cjs +1 -1
  14. package/dist/cli/index.cjs.map +1 -1
  15. package/dist/cli/index.js +6 -6
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/{index-Z6AL1MR_.d.cts → index-Cn6kg7KH.d.cts} +1 -1
  18. package/dist/{index-BaAOB0xd.d.ts → index-f-Xg86P9.d.ts} +1 -1
  19. package/dist/index.cjs +14 -12
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +5 -170
  22. package/dist/index.d.ts +5 -170
  23. package/dist/index.js +5 -5
  24. package/dist/policy/index.cjs.map +1 -1
  25. package/dist/policy/index.d.cts +1 -1
  26. package/dist/policy/index.d.ts +1 -1
  27. package/dist/policy/index.js +1 -1
  28. package/dist/signer/index.cjs +9 -6
  29. package/dist/signer/index.cjs.map +1 -1
  30. package/dist/signer/index.d.cts +2 -2
  31. package/dist/signer/index.d.ts +2 -2
  32. package/dist/signer/index.js +3 -3
  33. package/dist/{spending-policy-DZSNHqnD.d.ts → spending-policy-DKZN3Sg8.d.ts} +3 -2
  34. package/dist/{spending-policy-DqBRDUxx.d.cts → spending-policy-DaajDg9B.d.cts} +3 -2
  35. package/dist/x402/index.cjs +9 -6
  36. package/dist/x402/index.cjs.map +1 -1
  37. package/dist/x402/index.d.cts +2 -2
  38. package/dist/x402/index.d.ts +2 -2
  39. package/dist/x402/index.js +2 -2
  40. package/package.json +1 -1
  41. package/dist/asset-domain-CpJuDkI2.d.cts +0 -102
  42. package/dist/asset-domain-CpJuDkI2.d.ts +0 -102
  43. package/dist/chunk-E2EG72U2.js.map +0 -1
  44. package/dist/chunk-RUWCCP37.js.map +0 -1
  45. package/dist/chunk-VPRR3TNA.js.map +0 -1
  46. package/dist/chunk-YMABXRCK.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chains/avalanche.ts","../../src/chains/ethereum.ts","../../src/chains/kaia.ts","../../src/chains/polygon.ts","../../src/chains/index.ts","../../src/tokens/jpyc.ts","../../src/tokens/known-assets.ts","../../src/signer/errors.ts","../../src/signer/gate.ts","../../src/x402/errors.ts","../../src/tokens/asset-domain.ts","../../src/tokens/eip3009.ts","../../src/x402/types.ts","../../src/x402/client.ts","../../src/x402/encoding.ts","../../src/observability/hooks.ts","../../src/x402/facilitator.ts","../../src/x402/fetch.ts","../../src/x402/payment-requirements.ts","../../src/idempotency/errors.ts","../../src/idempotency/record.ts","../../src/idempotency/store.ts","../../src/x402/server.ts"],"names":["viemAvalanche","viemAvalancheFuji","viemMainnet","viemSepolia","viemKaia","viemKairos","viemPolygon","viemPolygonAmoy","getAddress","isAddress","keccak256","stringToHex","parseSignature","recoverTypedDataAddress","paymentRequired","UINT256_MAX","UINT256_DECIMAL","assertAddress","headers"],"mappings":";;;;;;AAaO,IAAM,SAAA,GAAY;AAAA,EACxB,GAAGA,gBAAA;AAAA,EACH,SAAA,EAAW,KAAA;AAAA,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A;AAAA,QACZ;AAAA,OACD;AACA,MAAA,IAAI,WAAW,IAAA,EAAM;AACpB,QAAA,IAAI;AACH,UAAA,MAAM,WAAA,CAAY,KAAA,CAAM,QAAA,CAAS,OAAA,EAAS,QAAQ,KAAK,CAAA;AAAA,QACxD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACD,CAAA,MAAO;AACN,QAAA,MAAM,YAAA,CAAa,WAAA,EAAa,OAAA,EAAS,KAAK,CAAA;AAAA,MAC/C;AAAA,IACD;AACA,IAAA,OAAO,aAAA;AAAA,EACR,CAAA;AACD","file":"index.cjs","sourcesContent":["import { avalanche as viemAvalanche, avalancheFuji as viemAvalancheFuji } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Avalanche C-Chain — priority 3 production chain.\n *\n * Snowman BFT gives sub-`2 s` **deterministic finality**, so\n * `defaultConfirmations` of `2` is ample — deep confirmations add latency for\n * no extra safety. JPYC is live at the same address as the other chains.\n *\n * The x402 EOA-payer path works today; the smart-account path via ZeroDev is\n * not yet verified on Avalanche.\n */\nexport const avalanche = {\n\t...viemAvalanche,\n\tisTestnet: false,\n\tdefaultConfirmations: 2,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n\n/**\n * Avalanche Fuji testnet. JPYC is live at the same address as the other chains\n * (confirmed via a read-only on-chain `name()` == \"JPY Coin\" / `symbol()` ==\n * \"JPYC\" check, 2026-05-31). Real x402 settlement here has not been exercised.\n */\nexport const avalancheFuji = {\n\t...viemAvalancheFuji,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n","import { mainnet as viemMainnet, sepolia as viemSepolia } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Ethereum mainnet — priority 4 production chain (institutional use cases).\n *\n * Casper FFG finalises in epochs (~12.8 min). `defaultConfirmations` of `32`\n * (~6.4 min at ~12 s blocks) gives finalised-grade safety. **Do NOT use\n * Polygon's `4` here** — 4 blocks (~48 s) is nowhere near finalised, and would\n * re-open the settle-reorg gap (threat 2.8). The facilitator auto-sizes\n * `receiptTimeoutMs` from this depth (~10 min), so the default does not time\n * out. JPYC is live at the same address as the other chains.\n */\nexport const ethereum = {\n\t...viemMainnet,\n\tisTestnet: false,\n\tdefaultConfirmations: 32,\n\tblockTimeMs: 12_000,\n} satisfies KawaseChain;\n\n/**\n * Sepolia — Ethereum testnet. JPYC is live at the same address as the other\n * chains (confirmed via a read-only on-chain `name()` == \"JPY Coin\" / `symbol()`\n * == \"JPYC\" check, 2026-05-31). Real x402 settlement here has not been exercised.\n */\nexport const sepolia = {\n\t...viemSepolia,\n\tisTestnet: true,\n\tdefaultConfirmations: 4,\n\tblockTimeMs: 12_000,\n} satisfies KawaseChain;\n","import { kaia as viemKaia, kairos as viemKairos } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Kaia mainnet — priority 2 production chain.\n *\n * Kaia (Klaytn + Finschia) runs IBFT consensus with **immediate finality** — a\n * single confirmed block is final — so `defaultConfirmations` is `1` (do NOT\n * copy Polygon's `4`). JPYC is live at the same address as the other chains\n * (`src/tokens/jpyc.ts`).\n *\n * Note: ZeroDev does not support Kaia, so the **smart-account path** (session\n * keys, sponsored UserOps) is not yet available here — it is planned via\n * Pimlico (M5-3 Phase 2). The **x402 EOA-payer path** works today.\n */\nexport const kaia = {\n\t...viemKaia,\n\tisTestnet: false,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 1_000,\n} satisfies KawaseChain;\n\n/**\n * Kairos — Kaia testnet. JPYC is available via the Kaia faucet at the same\n * address as mainnet; suitable for the same Amoy→Polygon-style testnet→mainnet\n * verification pattern.\n */\nexport const kairos = {\n\t...viemKairos,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 1_000,\n} satisfies KawaseChain;\n","import { polygon as viemPolygon, polygonAmoy as viemPolygonAmoy } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Polygon mainnet — priority 1 production chain.\n *\n * Built on viem's `polygon` definition (official RPC URLs, block explorers,\n * and `POL` native currency) plus kawasekit metadata. Polygon PoS is\n * probabilistic; the default `4` confirmations ≈ ~8 s of soft finality.\n */\nexport const polygon = {\n\t...viemPolygon,\n\tisTestnet: false,\n\tdefaultConfirmations: 4,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n\n/**\n * Polygon Amoy testnet — the primary kawasekit development target.\n *\n * Built on viem's `polygonAmoy` definition. JPYC is also live on Amoy at the\n * same address as mainnet; see `src/tokens/jpyc.ts`.\n */\nexport const polygonAmoy = {\n\t...viemPolygonAmoy,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n","import { avalanche, avalancheFuji } from \"./avalanche\";\nimport { ethereum, sepolia } from \"./ethereum\";\nimport { kaia, kairos } from \"./kaia\";\nimport { polygon, polygonAmoy } from \"./polygon\";\nimport { type KawaseChain, zerodevRpcUrl } from \"./types\";\n\nexport {\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\ttype KawaseChain,\n\tkaia,\n\tkairos,\n\tpolygon,\n\tpolygonAmoy,\n\tsepolia,\n\tzerodevRpcUrl,\n};\n\n/**\n * All chains kawasekit supports, in priority order (CLAUDE.md chain priority:\n * Polygon → Kaia → Avalanche → Ethereum, each with its testnet).\n *\n * Exposed as a `readonly` tuple — **not** a `Map` — so that bundlers can\n * tree-shake chains a consumer never references.\n *\n * JPYC liveness is a separate axis (`src/tokens/jpyc.ts`): a chain can be\n * supported here while JPYC is not yet live on it (Avalanche Fuji / Sepolia).\n *\n * @example\n * ```ts\n * import { supportedChains } from \"kawasekit\";\n *\n * for (const chain of supportedChains) {\n * \tconsole.log(chain.id, chain.name);\n * }\n * ```\n */\nexport const supportedChains = [\n\tpolygon,\n\tpolygonAmoy,\n\tkaia,\n\tkairos,\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\tsepolia,\n] as const;\n\n/**\n * Union of every chain ID kawasekit supports\n * (`137 | 80002 | 8217 | 1001 | 43114 | 43113 | 1 | 11155111`).\n *\n * Derived from {@link supportedChains}, so adding a chain there extends this\n * type automatically.\n */\nexport type SupportedChainId = (typeof supportedChains)[number][\"id\"];\n\n/** A single member of {@link supportedChains}, with its literal `id`. */\ntype SupportedChain = (typeof supportedChains)[number];\n\n/**\n * Internal chain lookup, built once at module scope.\n *\n * This `Map` is an implementation detail and is intentionally **not**\n * exported: the public API exposes the {@link supportedChains} tuple instead,\n * so importing one chain does not pull in all of them.\n */\nconst chainsById: ReadonlyMap<number, SupportedChain> = new Map(\n\tsupportedChains.map((chain) => [chain.id, chain]),\n);\n\n/**\n * Error thrown when a chain ID kawasekit does not support is requested.\n *\n * @example\n * ```ts\n * import { ChainNotSupportedError, getChain } from \"kawasekit\";\n *\n * try {\n * \tgetChain(1);\n * } catch (error) {\n * \tif (error instanceof ChainNotSupportedError) {\n * \t\tconsole.error(error.message);\n * \t}\n * }\n * ```\n */\nexport class ChainNotSupportedError extends Error {\n\tconstructor(chainId: number) {\n\t\tconst supported = supportedChains.map((chain) => chain.id).join(\", \");\n\t\tsuper(\n\t\t\t`Chain ID ${chainId} is not supported by kawasekit. ` + `Supported chain IDs: ${supported}.`,\n\t\t);\n\t\tthis.name = \"ChainNotSupportedError\";\n\t}\n}\n\n/**\n * Type guard that narrows an arbitrary chain ID to a {@link SupportedChainId}.\n *\n * @param chainId - The numeric chain ID to test.\n * @returns `true` if kawasekit supports this chain ID.\n *\n * @example\n * ```ts\n * import { isSupportedChainId } from \"kawasekit\";\n *\n * const id = 80002;\n * if (isSupportedChainId(id)) {\n * \t// `id` is now narrowed to SupportedChainId\n * }\n * ```\n */\nexport function isSupportedChainId(chainId: number): chainId is SupportedChainId {\n\treturn chainsById.has(chainId);\n}\n\n/**\n * Looks up a supported chain by its numeric chain ID.\n *\n * The returned chain's `id` is narrowed to {@link SupportedChainId}.\n *\n * @param chainId - The numeric chain ID to look up.\n * @returns The matching {@link KawaseChain}.\n * @throws {ChainNotSupportedError} If `chainId` is not supported.\n *\n * @example\n * ```ts\n * import { getChain } from \"kawasekit\";\n *\n * const chain = getChain(80002); // Polygon Amoy\n * console.log(chain.name);\n * ```\n */\nexport function getChain(chainId: number): SupportedChain {\n\tconst chain = chainsById.get(chainId);\n\tif (chain === undefined) {\n\t\tthrow new ChainNotSupportedError(chainId);\n\t}\n\treturn chain;\n}\n","/**\n * JPYC stablecoin metadata, deployments, and ABI.\n *\n * JPYC is a Japanese yen-pegged stablecoin issued by JPYC Inc. under the\n * revised Payment Services Act as 電子決済手段 (electronic payment\n * instrument). The new (\"v2\") JPYC, launched 2025-10, lives at the same\n * address on every chain where it is deployed.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport {\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\tkaia,\n\tkairos,\n\tpolygon,\n\tpolygonAmoy,\n\tsepolia,\n} from \"../chains\";\n\n/** ERC-20 decimals for JPYC. Constant across every chain. */\nexport const JPYC_DECIMALS = 18;\n\n/**\n * EIP-712 domain hint for off-chain authorization signing (EIP-3009, EIP-2612).\n *\n * The real JPYC contract does not expose `version()` publicly — it lives in an\n * `internal VERSION` state variable set during proxy initialization. The\n * canonical value is `\"1\"`, matching the FiatToken lineage; the\n * {@link signTransferWithAuthorization} helper accepts an override if a future\n * deployment changes this.\n *\n * `name` is \"JPY Coin\" — the on-chain `name()` value on every live deployment.\n */\nexport const JPYC_EIP712_DOMAIN_HINT = {\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n/**\n * Address shared by every live JPYC deployment.\n *\n * Verified on:\n * - Ethereum : https://etherscan.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * - Polygon : https://polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Polygon Amoy : https://amoy.polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Avalanche : https://snowtrace.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n *\n * Do NOT confuse with the legacy 前払式支払手段 JPYC at `0x431D5dFF...`.\n */\nexport const JPYC_V2_ADDRESS: Address = \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\";\n\n/** A JPYC deployment on a single chain. */\nexport interface JpycDeployment {\n\treadonly chainId: SupportedChainId;\n\treadonly address: Address;\n\t/** `true` if the token is live on this chain right now. */\n\treadonly isLive: boolean;\n}\n\n/**\n * JPYC deployments keyed by chain.\n *\n * JPYC v2 uses the **same address** (`JPYC_V2_ADDRESS`) on every chain where it\n * is live. `isLive` is the separate \"is JPYC actually deployed here yet?\" axis.\n * All eight supported chains are live at this address: the four mainnets\n * (Polygon, Kaia, Avalanche, Ethereum) + Amoy + Kairos + Avalanche Fuji +\n * Sepolia. Kaia/Kairos/Avalanche/Fuji/Sepolia were confirmed by a read-only\n * on-chain check (`name() == \"JPY Coin\"`, `symbol() == \"JPYC\"` at `0xE7C3…`,\n * 2026-05-31); Polygon/Amoy/Ethereum are established. `isLive: false` + the\n * {@link JpycNotAvailableError} path remain for any future chain added before\n * its JPYC deployment lands.\n */\nexport const jpycDeployments: { readonly [chainId in SupportedChainId]: JpycDeployment } = {\n\t[polygon.id]: { chainId: polygon.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[polygonAmoy.id]: { chainId: polygonAmoy.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[kaia.id]: { chainId: kaia.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[kairos.id]: { chainId: kairos.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[avalanche.id]: { chainId: avalanche.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[ethereum.id]: { chainId: ethereum.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[avalancheFuji.id]: { chainId: avalancheFuji.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[sepolia.id]: { chainId: sepolia.id, address: JPYC_V2_ADDRESS, isLive: true },\n};\n\n/**\n * Thrown when JPYC is not deployed on the requested chain.\n *\n * Today this is unreachable (every {@link SupportedChainId} has a live\n * deployment), but the error class is exported for future chains (Kaia) where\n * JPYC is still in development.\n */\nexport class JpycNotAvailableError extends Error {\n\tconstructor(chainId: number) {\n\t\tsuper(`JPYC is not yet deployed on chain ID ${chainId}.`);\n\t\tthis.name = \"JpycNotAvailableError\";\n\t}\n}\n\n/**\n * Returns the JPYC contract address for a kawasekit-supported chain.\n *\n * @param chainId - A {@link SupportedChainId}.\n * @returns The JPYC contract address on that chain.\n * @throws {JpycNotAvailableError} If JPYC is not live on the chain.\n *\n * @example\n * ```ts\n * import { getJpycAddress, polygonAmoy } from \"kawasekit\";\n *\n * const address = getJpycAddress(polygonAmoy.id);\n * ```\n */\nexport function getJpycAddress(chainId: SupportedChainId): Address {\n\tconst deployment = jpycDeployments[chainId];\n\tif (!deployment.isLive) {\n\t\tthrow new JpycNotAvailableError(chainId);\n\t}\n\treturn deployment.address;\n}\n\n/**\n * Minimal JPYC ABI: ERC-20 + EIP-3009 surface that kawasekit needs.\n *\n * Excludes permit / mint / blocklist / pause — kawasekit only reads balance,\n * sends `transfer()` via UserOp, and constructs / submits EIP-3009\n * authorizations. Bringing in the full FiatTokenV1 ABI would be wasted bytes.\n */\nexport const jpycAbi = [\n\t// ----- ERC-20 read -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"name\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"symbol\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"decimals\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint8\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"totalSupply\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"balanceOf\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [{ name: \"account\", type: \"address\" }],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"allowance\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\" },\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t// ----- ERC-20 write -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transfer\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferFrom\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"approve\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- EIP-3009 -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"receiveWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"cancelAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"authorizationState\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- Events kawasekit needs to decode -----\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Transfer\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\", indexed: true },\n\t\t\t{ name: \"to\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Approval\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\", indexed: true },\n\t\t\t{ name: \"spender\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationUsed\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationCanceled\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n] as const;\n","/**\n * Known-asset registry for {@link createX402PaymentSigner}'s\n * `asset: { kind: \"known\", id }` discriminated-union branch.\n *\n * kawasekit only ships pinned EIP-712 domain definitions for assets it has\n * verified empirically against the deployed contracts. Adding a new entry\n * here requires citing the source-file + line reference for the contract\n * that owns the `name` / `version` (so the next reviewer can spot-check the\n * claim, the same discipline `docs/THREAT_MODEL.md` §0 demands of any ✅\n * verdict that delegates to an out-of-scope component).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS } from \"./jpyc\";\n\n/** Known asset identifiers. New entries must update this union AND the table. */\nexport type KnownAssetId = \"jpyc-v2\";\n\n/** Fully-pinned EIP-712 domain for a known asset. */\nexport interface KnownAssetDomain {\n\treadonly id: KnownAssetId;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Canonical table. Lookups go through {@link getKnownAssetDomain}, which\n * returns a frozen copy so callers cannot mutate the registry.\n *\n * `verifyingContract` is the multi-chain canonical address — JPYC v2 is the\n * same address on Ethereum / Polygon (mainnet + Amoy) / Avalanche. The\n * signer cross-checks `requirements.asset` against this value at sign time,\n * so a server advertising a different `asset` is rejected before any\n * signature is produced.\n *\n * JPYC v2 domain: `name = \"JPY Coin\"`, `version = \"1\"`. Source of truth is\n * the deployed contract's `eip712Domain()` view — verified empirically and\n * also cached in `src/tokens/jpyc.ts:JPYC_EIP712_DOMAIN_HINT`.\n */\nconst KNOWN_ASSETS: ReadonlyArray<KnownAssetDomain> = [\n\t{\n\t\tid: \"jpyc-v2\",\n\t\tname: JPYC_EIP712_DOMAIN_HINT.name,\n\t\tversion: JPYC_EIP712_DOMAIN_HINT.version,\n\t\tverifyingContract: getAddress(JPYC_V2_ADDRESS),\n\t},\n];\n\n/**\n * Look up a known asset's pinned EIP-712 domain by id.\n *\n * @returns The domain, or `undefined` if the id is not in the registry.\n *\n * @example\n * ```ts\n * import { getKnownAssetDomain } from \"kawasekit\";\n *\n * const jpyc = getKnownAssetDomain(\"jpyc-v2\");\n * if (jpyc === undefined) throw new Error(\"unreachable\");\n * console.log(jpyc.verifyingContract); // 0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * ```\n */\nexport function getKnownAssetDomain(id: KnownAssetId): KnownAssetDomain | undefined {\n\treturn KNOWN_ASSETS.find((entry) => entry.id === id);\n}\n\n/** List every known asset id (for diagnostics / error messages). */\nexport function listKnownAssetIds(): readonly KnownAssetId[] {\n\treturn KNOWN_ASSETS.map((entry) => entry.id);\n}\n","/**\n * PolicyGatedSigner error types.\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown for a construction-time / configuration error in a PolicyGatedSigner\n * adapter — e.g. a `local` signer constructed without the required\n * `acknowledgeAdvisory: true`, or a non-bypassable signer asserted on an\n * advisory one (`assertNonBypassable`). Policy *denials* are NOT errors — they\n * are returned as a typed {@link PolicyRejection} in {@link SignResult}.\n *\n * @example\n * ```ts\n * import { createLocalPolicyGatedSigner, PolicyGatedSignerConfigError } from \"kawasekit/signer\";\n *\n * try {\n * // @ts-expect-error — acknowledgeAdvisory is required\n * createLocalPolicyGatedSigner({ account, policy, asset });\n * } catch (error) {\n * if (error instanceof PolicyGatedSignerConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class PolicyGatedSignerConfigError extends Error {\n\t/** The offending config field. */\n\treadonly field: string;\n\t/** Short machine-readable reason. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid PolicyGatedSigner config (${field}): ${reason}`, options);\n\t\tthis.name = \"PolicyGatedSignerConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n","/**\n * The enforcement-level type-gate — the compile-time (and runtime) mechanism\n * that prevents an advisory signer from being substituted for an enforcing one.\n *\n * @packageDocumentation\n */\n\nimport { PolicyGatedSignerConfigError } from \"./errors\";\nimport type { NonBypassableEnforcement, PolicyGatedSigner } from \"./types\";\n\n/**\n * Compile-time gate: accepts only a non-bypassable signer\n * (`cryptographic` | `hardware`). Passing an `advisory` (or `integrator`) signer\n * is a **compile error**, because `PolicyGatedSigner<\"advisory\">` is not\n * assignable to `PolicyGatedSigner<NonBypassableEnforcement>` (covariant `E`).\n *\n * Use it at the boundary of a bounded/regulated flow so wiring an advisory\n * signer into it fails the build, not silently at runtime.\n *\n * @example\n * ```ts\n * function payBounded(signer: PolicyGatedSigner<NonBypassableEnforcement>) { ... }\n *\n * requireNonBypassable(mpc2pSigner); // ✓ ok — cryptographic\n * // requireNonBypassable(localSigner); // ✗ compile error — advisory\n * ```\n */\nexport function requireNonBypassable<E extends NonBypassableEnforcement>(\n\tsigner: PolicyGatedSigner<E>,\n): PolicyGatedSigner<E> {\n\treturn signer;\n}\n\n/**\n * Runtime mirror of {@link requireNonBypassable}, for plain-JS call sites and as\n * defense-in-depth. Throws {@link PolicyGatedSignerConfigError} if the signer is\n * advisory/integrator (i.e. bypassable). On success, narrows the signer type to\n * {@link NonBypassableEnforcement}.\n */\nexport function assertNonBypassable(\n\tsigner: PolicyGatedSigner,\n): asserts signer is PolicyGatedSigner<NonBypassableEnforcement> {\n\tif (signer.enforcement === \"advisory\" || signer.enforcement === \"integrator\") {\n\t\tthrow new PolicyGatedSignerConfigError(\n\t\t\t\"enforcement\",\n\t\t\t`expected a non-bypassable signer (cryptographic | hardware), got \"${signer.enforcement}\" — an ${signer.enforcement} signer's policy can be bypassed by a key-holder`,\n\t\t);\n\t}\n}\n","/**\n * Typed errors thrown by the `kawasekit/x402` modules.\n *\n * Centralised so that consumers can `instanceof`-discriminate without importing\n * deep paths. Additional error classes are added here as the corresponding\n * modules come online (server, facilitator, …).\n *\n * @packageDocumentation\n */\n\nimport type { PolicyRejection } from \"../signer/types\";\n\n/**\n * Thrown when an x402 wire-format payload is malformed: invalid base64, invalid\n * JSON, or a value that cannot represent the expected schema.\n *\n * Carries the offending header / context name so callers can produce actionable\n * log lines without re-parsing the message string.\n *\n * @example\n * ```ts\n * import { decodePaymentSignatureHeader, X402InvalidPayloadError } from \"kawasekit\";\n *\n * try {\n * decodePaymentSignatureHeader(headerValue);\n * } catch (error) {\n * if (error instanceof X402InvalidPayloadError) {\n * console.warn(`reject ${error.context}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidPayloadError extends Error {\n\t/** Logical name of the payload that failed (e.g. `\"PAYMENT-SIGNATURE\"`). */\n\treadonly context: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(context: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${context} payload: ${reason}`, options);\n\t\tthis.name = \"X402InvalidPayloadError\";\n\t\tthis.context = context;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when an x402 SDK construction-time configuration is invalid: an\n * unknown `asset.kind`, a known asset id that kawasekit does not ship a\n * domain for, missing required fields on an `unsafeOverride`, etc.\n *\n * Distinct from {@link X402InvalidPayloadError} (which describes wire-format\n * problems): config errors are integrator bugs, not adversarial inputs.\n *\n * @example\n * ```ts\n * import { createX402PaymentSigner, X402InvalidConfigError } from \"kawasekit\";\n *\n * try {\n * createX402PaymentSigner({\n * network: \"testnet\",\n * account,\n * // @ts-expect-error — kind: \"foo\" is not a known kind\n * asset: { kind: \"foo\" },\n * });\n * } catch (error) {\n * if (error instanceof X402InvalidConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidConfigError extends Error {\n\t/** Logical name of the config field that failed (e.g. `\"asset\"`). */\n\treadonly field: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${field} config: ${reason}`, options);\n\t\tthis.name = \"X402InvalidConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown by {@link createX402PaymentSigner} (the `signer` variant) when the bound\n * `PolicyGatedSigner` refuses to sign — i.e. its `sign()` returned\n * `{ ok: false }`. Carries the typed {@link PolicyRejection} so callers can\n * branch on `reason`. This is the policy-driven analog of the `account`\n * variant's `maxAmountPerSign` throw ({@link X402InvalidPayloadError}): the\n * `X402PaymentSigner.sign()` surface returns a payload or throws, unchanged.\n *\n * @example\n * ```ts\n * import { X402PolicyRejectedError } from \"kawasekit\";\n *\n * try {\n * await signer.sign({ paymentRequirements });\n * } catch (error) {\n * if (error instanceof X402PolicyRejectedError) {\n * console.warn(`policy refused: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402PolicyRejectedError extends Error {\n\t/** The policy rejection reason (e.g. `\"amount_exceeds_per_sign\"`). */\n\treadonly reason: PolicyRejection[\"reason\"];\n\t/** The full typed rejection (its `detail` never contains the nonce or signature). */\n\treadonly rejection: PolicyRejection;\n\n\tconstructor(rejection: PolicyRejection, options?: { cause?: unknown }) {\n\t\tsuper(`x402 payment rejected by policy: ${rejection.reason} (${rejection.detail})`, options);\n\t\tthis.name = \"X402PolicyRejectedError\";\n\t\tthis.reason = rejection.reason;\n\t\tthis.rejection = rejection;\n\t}\n}\n","/**\n * EIP-712 asset-domain resolution for x402 / EIP-3009 signing.\n *\n * Construction-time pinning of the EIP-712 domain (`name` / `version` /\n * `verifyingContract`) a signer will use. The integrator declares an\n * {@link X402AssetParam} — either a kawasekit-maintained `known` asset or a\n * loud `unsafeOverride` — and {@link resolveAssetParam} resolves it to a pinned\n * {@link ResolvedAsset}. The signer then trusts only this pinned domain and\n * refuses to sign for a mismatched advertised asset (Threat 1.4: misadvertised\n * EIP-712 domain).\n *\n * Token-domain concern, reused by both the x402 signer (`src/x402/client.ts`)\n * and the M6 PolicyGatedSigner (`src/signer/`).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { X402InvalidConfigError } from \"../x402/errors\";\nimport {\n\tgetKnownAssetDomain,\n\ttype KnownAssetDomain,\n\ttype KnownAssetId,\n\tlistKnownAssetIds,\n} from \"./known-assets\";\n\n/** EIP-712 token domain `name` / `version` pair. */\nexport interface X402TokenDomain {\n\treadonly name: string;\n\treadonly version: string;\n}\n\n/**\n * Asset binding for {@link createX402PaymentSigner} and the M6 PolicyGatedSigner.\n * Required, discriminated.\n *\n * **Default-on whitelist**: integrators MUST declare which asset they intend\n * to sign for. The `known` branch references a kawasekit-maintained\n * whitelist (see `src/tokens/known-assets.ts`); the `unsafeOverride` branch\n * is the deliberate escape hatch for any other asset and is named loudly so\n * it survives a code review. Either way, the signer pins the EIP-712 domain\n * at construction time and refuses to sign if `paymentRequirements.asset`\n * disagrees with the pinned `verifyingContract`.\n *\n * Closes Threat 1.4 (misadvertised EIP-712 domain): the server's advertised\n * `extra.name` / `extra.version` and `asset` are all ignored for signing\n * purposes — the signer trusts only what the integrator declared here.\n */\nexport type X402AssetParam =\n\t| {\n\t\t\t/** Use a kawasekit-maintained pinned EIP-712 domain. */\n\t\t\treadonly kind: \"known\";\n\t\t\t/** The asset id to pin. See {@link KnownAssetId} for the registry. */\n\t\t\treadonly id: KnownAssetId;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Use a caller-supplied EIP-712 domain for an asset NOT on the\n\t\t\t * kawasekit whitelist. The name is deliberately loud — pick this\n\t\t\t * branch only when you have separately audited the contract and its\n\t\t\t * `eip712Domain()` output.\n\t\t\t */\n\t\t\treadonly kind: \"unsafeOverride\";\n\t\t\treadonly domain: {\n\t\t\t\treadonly name: string;\n\t\t\t\treadonly version: string;\n\t\t\t\treadonly verifyingContract: Address;\n\t\t\t};\n\t };\n\n/** Construction-time resolution of an {@link X402AssetParam} to a pinned domain. */\nexport interface ResolvedAsset {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Resolve an {@link X402AssetParam} to a pinned {@link ResolvedAsset}.\n *\n * Throws {@link X402InvalidConfigError} for an unknown `known` id or a malformed\n * `unsafeOverride` domain. Pure / construction-time — no chain RPC.\n */\nexport function resolveAssetParam(asset: X402AssetParam): ResolvedAsset {\n\tif (asset.kind === \"known\") {\n\t\tconst entry: KnownAssetDomain | undefined = getKnownAssetDomain(asset.id);\n\t\tif (entry === undefined) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.id\",\n\t\t\t\t`unknown asset id ${JSON.stringify(asset.id)}. Supported: ${listKnownAssetIds()\n\t\t\t\t\t.map((id) => JSON.stringify(id))\n\t\t\t\t\t.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: entry.name,\n\t\t\tversion: entry.version,\n\t\t\tverifyingContract: entry.verifyingContract,\n\t\t};\n\t}\n\tif (asset.kind === \"unsafeOverride\") {\n\t\tconst { domain } = asset;\n\t\tif (typeof domain.name !== \"string\" || domain.name === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.name\",\n\t\t\t\t\"`unsafeOverride.domain.name` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (typeof domain.version !== \"string\" || domain.version === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.version\",\n\t\t\t\t\"`unsafeOverride.domain.version` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (!isAddress(domain.verifyingContract, { strict: false })) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.verifyingContract\",\n\t\t\t\t`\\`unsafeOverride.domain.verifyingContract\\` must be a valid address, got ${JSON.stringify(domain.verifyingContract)}`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: domain.name,\n\t\t\tversion: domain.version,\n\t\t\tverifyingContract: getAddress(domain.verifyingContract),\n\t\t};\n\t}\n\t// Defensive: TS exhaustiveness guarantees this is unreachable at compile\n\t// time, but a JS consumer could smuggle through an unknown kind.\n\tconst exhaustive = asset as { kind: string };\n\tthrow new X402InvalidConfigError(\n\t\t\"asset.kind\",\n\t\t`unsupported kind ${JSON.stringify(exhaustive.kind)}. Expected \"known\" or \"unsafeOverride\".`,\n\t);\n}\n","/**\n * EIP-3009 typed-data builders and signing helpers.\n *\n * Token-agnostic: works for any EIP-3009-compliant token (JPYC, USDC, USDP,\n * Centre FiatToken family). Pure off-chain construction — no chain RPC, no\n * submission. Submission is the caller's job (M3 x402 flow, or arbitrary\n * gas-paying relayer).\n *\n * @packageDocumentation\n */\n\nimport {\n\ttype Account,\n\ttype Address,\n\tgetAddress,\n\ttype Hex,\n\tkeccak256,\n\tparseSignature,\n\tstringToHex,\n} from \"viem\";\n\n// ---------------------------------------------------------------------------\n// Domain & typed-data shapes\n// ---------------------------------------------------------------------------\n\n/**\n * EIP-712 domain for an EIP-3009-compliant token.\n *\n * `name` and `version` MUST match the values the token used when computing\n * its `DOMAIN_SEPARATOR`. For JPYC see {@link JPYC_EIP712_DOMAIN_HINT}.\n */\nexport interface Eip3009Domain {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly chainId: number;\n\treadonly verifyingContract: Address;\n}\n\n/** Message body for {@link signTransferWithAuthorization}. */\nexport interface TransferWithAuthorizationMessage {\n\treadonly from: Address;\n\treadonly to: Address;\n\treadonly value: bigint;\n\treadonly validAfter: bigint;\n\treadonly validBefore: bigint;\n\t/** 32-byte random nonce. Generate with {@link generateAuthorizationNonce}. */\n\treadonly nonce: Hex;\n}\n\n/** Message body for {@link signReceiveWithAuthorization}. */\nexport type ReceiveWithAuthorizationMessage = TransferWithAuthorizationMessage;\n\n/** Message body for {@link signCancelAuthorization}. */\nexport interface CancelAuthorizationMessage {\n\treadonly authorizer: Address;\n\treadonly nonce: Hex;\n}\n\n/**\n * A signed EIP-3009 authorization, ready to be passed to the token's\n * `*WithAuthorization` entrypoint as `(v, r, s)`.\n */\nexport interface SignedAuthorization<TMessage> {\n\treadonly signature: Hex;\n\treadonly v: number;\n\treadonly r: Hex;\n\treadonly s: Hex;\n\treadonly domain: Eip3009Domain;\n\treadonly message: TMessage;\n}\n\n// ---------------------------------------------------------------------------\n// EIP-712 type definitions (must match EIP-3009 byte-for-byte)\n// ---------------------------------------------------------------------------\n\nconst transferWithAuthorizationTypes = {\n\tTransferWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\nconst receiveWithAuthorizationTypes = {\n\tReceiveWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\nconst cancelAuthorizationTypes = {\n\tCancelAuthorization: [\n\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Generates a cryptographically random 32-byte EIP-3009 nonce.\n *\n * The nonce only needs to be unique per `(authorizer, contract)` — duplicates\n * across different tokens are harmless because the contract scopes them.\n *\n * @example\n * ```ts\n * import { generateAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = generateAuthorizationNonce();\n * ```\n */\nexport function generateAuthorizationNonce(): Hex {\n\tconst bytes = new Uint8Array(32);\n\tcrypto.getRandomValues(bytes);\n\treturn `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")}` as Hex;\n}\n\n/** Domain tag separating the nonce preimage from any other keccak use in the SDK. */\nconst EIP3009_NONCE_DOMAIN_TAG = \"kawasekit/eip3009-nonce/1\";\n\n/**\n * Derives a **deterministic** 32-byte EIP-3009 nonce from a reasoning-step\n * idempotency key, scoped to `(from, verifyingContract, chainId)` so the same\n * key never collides across tokens or chains (M5-1, Half B).\n *\n * `nonce = keccak256(DOMAIN_TAG ‖ idempotencyKey ‖ from ‖ verifyingContract ‖\n * chainId)`. **No shared secret**: determinism across replicas / sub-agents\n * needs only a shared `conversationId` (the source of the key), not secret\n * distribution. A replayed key ⇒ identical nonce ⇒ the token contract's\n * `authorizationState` rejects the second settlement — the on-chain last line of\n * defence against re-signed same-intent duplicate payments. Use in place of\n * {@link generateAuthorizationNonce} only when a key is available.\n *\n * `chainId` is in the preimage, so the same JPYC address on Polygon / Avalanche\n * / Kaia / Ethereum yields distinct nonces (cross-chain replay safety).\n *\n * @example\n * ```ts\n * import { deriveAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = deriveAuthorizationNonce(\n * { idempotencyKey },\n * { from: account.address, verifyingContract, chainId },\n * );\n * ```\n */\nexport function deriveAuthorizationNonce(\n\tinput: { readonly idempotencyKey: string },\n\tscope: { readonly from: Address; readonly verifyingContract: Address; readonly chainId: number },\n): Hex {\n\tif (input.idempotencyKey === \"\") {\n\t\tthrow new Error(\"deriveAuthorizationNonce: idempotencyKey must be a non-empty string\");\n\t}\n\tconst preimage = JSON.stringify([\n\t\tEIP3009_NONCE_DOMAIN_TAG,\n\t\tinput.idempotencyKey,\n\t\tgetAddress(scope.from),\n\t\tgetAddress(scope.verifyingContract),\n\t\tscope.chainId,\n\t]);\n\treturn keccak256(stringToHex(preimage));\n}\n\n/**\n * Returns a `validBefore` UNIX timestamp `seconds` in the future.\n *\n * @param seconds - Lifetime of the authorization, in seconds.\n * @param nowSec - Optional override of \"now\" (defaults to {@link Date.now}).\n *\n * @example\n * ```ts\n * import { authorizationDeadlineFromNow } from \"kawasekit\";\n *\n * const validBefore = authorizationDeadlineFromNow(60 * 5); // 5 minutes\n * ```\n */\nexport function authorizationDeadlineFromNow(seconds: number, nowSec?: bigint): bigint {\n\tconst now = nowSec ?? BigInt(Math.floor(Date.now() / 1000));\n\treturn now + BigInt(seconds);\n}\n\nfunction requireSignTypedData(account: Account): NonNullable<Account[\"signTypedData\"]> {\n\tif (!account.signTypedData) {\n\t\tthrow new Error(\n\t\t\t`Account ${account.address} cannot sign typed data — pass a LocalAccount or a JsonRpcAccount bound to a WalletClient.`,\n\t\t);\n\t}\n\treturn account.signTypedData.bind(account);\n}\n\nfunction assertSignerMatches(account: Account, expectedFrom: Address, role: string): void {\n\tif (getAddress(account.address) !== getAddress(expectedFrom)) {\n\t\tthrow new Error(\n\t\t\t`EIP-3009 ${role} signature must come from \\`${role === \"cancel\" ? \"authorizer\" : \"from\"}\\`: account is ${account.address}, message says ${expectedFrom}.`,\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Signers\n// ---------------------------------------------------------------------------\n\n/**\n * Signs an EIP-3009 `TransferWithAuthorization` message.\n *\n * The signing account MUST equal `message.from` — EIP-3009 rejects signatures\n * from anyone else (the on-chain check is pure `ecrecover` against `from`).\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import {\n * authorizationDeadlineFromNow,\n * generateAuthorizationNonce,\n * JPYC_EIP712_DOMAIN_HINT,\n * polygon,\n * signTransferWithAuthorization,\n * } from \"kawasekit\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const signed = await signTransferWithAuthorization(account, {\n * ...JPYC_EIP712_DOMAIN_HINT,\n * chainId: polygon.id,\n * verifyingContract: \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\",\n * }, {\n * from: account.address,\n * to: \"0xBeef...\",\n * value: 100n * 10n ** 18n,\n * validAfter: 0n,\n * validBefore: authorizationDeadlineFromNow(300),\n * nonce: generateAuthorizationNonce(),\n * });\n * // → submit (v, r, s) to token.transferWithAuthorization(...)\n * ```\n */\nexport async function signTransferWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: TransferWithAuthorizationMessage,\n): Promise<SignedAuthorization<TransferWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"transfer\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: transferWithAuthorizationTypes,\n\t\tprimaryType: \"TransferWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `ReceiveWithAuthorization` message.\n *\n * Differs from {@link signTransferWithAuthorization} in two ways:\n * 1. Uses the `ReceiveWithAuthorization` EIP-712 type.\n * 2. The contract additionally enforces `msg.sender == to` at submission\n * time, so only `to` (or a relayer impersonating `to` — impossible in\n * practice) can land the tx.\n */\nexport async function signReceiveWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: ReceiveWithAuthorizationMessage,\n): Promise<SignedAuthorization<ReceiveWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"receive\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: receiveWithAuthorizationTypes,\n\t\tprimaryType: \"ReceiveWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `CancelAuthorization` message.\n *\n * Cancelling consumes the nonce so a later `transferWithAuthorization` or\n * `receiveWithAuthorization` with the same nonce will revert.\n */\nexport async function signCancelAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: CancelAuthorizationMessage,\n): Promise<SignedAuthorization<CancelAuthorizationMessage>> {\n\tassertSignerMatches(account, message.authorizer, \"cancel\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: cancelAuthorizationTypes,\n\t\tprimaryType: \"CancelAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\nfunction splitAuthorization<TMessage>(\n\tsignature: Hex,\n\tdomain: Eip3009Domain,\n\tmessage: TMessage,\n): SignedAuthorization<TMessage> {\n\tconst parsed = parseSignature(signature);\n\t// viem's parseSignature returns yParity ∈ {0, 1} as well as v when present.\n\tconst v = parsed.v !== undefined ? Number(parsed.v) : (parsed.yParity ?? 0) + 27;\n\treturn {\n\t\tsignature,\n\t\tv,\n\t\tr: parsed.r,\n\t\ts: parsed.s,\n\t\tdomain,\n\t\tmessage,\n\t};\n}\n","/**\n * x402 v2 wire-format types — the canonical shapes that travel over HTTP between\n * client, resource server, and facilitator.\n *\n * These types are deliberately **spec-faithful**: field names, optionality, and\n * value encoding (e.g. `uint256` as decimal string) match the x402 v2\n * specification verbatim so that payloads kawasekit produces are byte-equivalent\n * to those from `@x402/core` and other reference implementations. Where the\n * spec allows a string union (e.g. `network`, `scheme`), kawasekit narrows the\n * type to the values it actually supports — but every kawasekit type is\n * structurally assignable to its `@x402/core` counterpart.\n *\n * For the EVM `exact` scheme (the only scheme kawasekit implements in M3) the\n * settlement mechanism is EIP-3009 `transferWithAuthorization`. Permit2 and\n * ERC-7710 are deferred.\n *\n * See:\n * - x402 v2 spec: https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n * - exact-EVM scheme: https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md\n *\n * @packageDocumentation\n */\n\nimport type { Address, Hex } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { isSupportedChainId } from \"../chains\";\n\n// ---------------------------------------------------------------------------\n// Protocol version\n// ---------------------------------------------------------------------------\n\n/**\n * Current x402 protocol version implemented by kawasekit.\n *\n * v2 is the wire format that uses CAIP-2 network identifiers (`eip155:N`) and\n * separates {@link X402ResourceInfo} from {@link X402PaymentRequirements}. v1 is\n * deprecated and not supported.\n */\nexport const X402_VERSION = 2 as const;\n\n/** Literal type of {@link X402_VERSION}. */\nexport type X402Version = typeof X402_VERSION;\n\n// ---------------------------------------------------------------------------\n// Scheme & network\n// ---------------------------------------------------------------------------\n\n/**\n * Payment scheme identifier.\n *\n * Only `\"exact\"` is implemented in M3. The spec is extensible (`\"upto\"`,\n * `\"batch-settlement\"`, …); future kawasekit milestones may widen this union.\n */\nexport type X402Scheme = \"exact\";\n\n/**\n * CAIP-2 network identifier in `eip155:{chainId}` form, narrowed to chains\n * kawasekit supports.\n *\n * Adding a chain to {@link SupportedChainId} automatically extends this union.\n *\n * @example\n * ```ts\n * const net: X402Network = \"eip155:80002\"; // Polygon Amoy\n * ```\n */\nexport type X402Network = `eip155:${SupportedChainId}`;\n\n/**\n * Asset transfer method advertised inside `PaymentRequirements.extra` for the\n * EVM `exact` scheme.\n *\n * kawasekit M3 only implements `\"eip3009\"`. The other values exist so that\n * inbound payloads from interoperable servers can be parsed without losing\n * information, even though kawasekit will reject them at validation time.\n */\nexport type X402AssetTransferMethod = \"eip3009\" | \"permit2\" | \"erc7710\";\n\n/**\n * Conventional shape of `PaymentRequirements.extra` for the exact-EVM scheme.\n *\n * `name` and `version` MUST match the EIP-712 domain values used by the token\n * (for JPYC: `name = \"JPY Coin\"`, `version = \"1\"` — see\n * `JPYC_EIP712_DOMAIN_HINT`). Servers may include additional fields; this\n * interface is intentionally open via the index signature.\n */\nexport interface X402ExactEvmExtra {\n\treadonly assetTransferMethod?: X402AssetTransferMethod;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Resource & requirements\n// ---------------------------------------------------------------------------\n\n/**\n * Describes the resource being paid for.\n *\n * In v2 this object lives at the top level of {@link X402PaymentRequiredResponse}\n * (and is echoed back optionally inside {@link X402PaymentPayload}), so that a\n * single payment offer can describe one resource served at one URL.\n */\nexport interface X402ResourceInfo {\n\treadonly url: string;\n\treadonly description?: string;\n\treadonly mimeType?: string;\n\treadonly serviceName?: string;\n\treadonly tags?: readonly string[];\n\treadonly iconUrl?: string;\n}\n\n/**\n * One acceptable payment method, as advertised by the resource server.\n *\n * Field encoding follows the wire format exactly:\n * - `amount` is a **decimal string** of atomic token units (`uint256`-safe).\n * - `asset` and `payTo` are 0x-prefixed addresses; case is not normalised at\n * this layer (the verifier MUST checksum-compare).\n * - `maxTimeoutSeconds` is the max wall-clock time the client may take to\n * produce a signed payload after receiving the 402 response.\n *\n * `extra` is required (matching `@x402/core`) so that producers always provide\n * the EIP-712 domain hint needed for signature verification. The most common\n * shape is {@link X402ExactEvmExtra}.\n */\nexport interface X402PaymentRequirements {\n\treadonly scheme: X402Scheme;\n\treadonly network: X402Network;\n\treadonly amount: string;\n\treadonly asset: Address;\n\treadonly payTo: Address;\n\treadonly maxTimeoutSeconds: number;\n\treadonly extra: Record<string, unknown>;\n}\n\n/**\n * The JSON body returned by a resource server alongside the \"Payment Required\"\n * response (HTTP 402, or the transport equivalent).\n *\n * `accepts` is an OR-list: the client picks **one** entry and produces a\n * matching {@link X402PaymentPayload}.\n */\nexport interface X402PaymentRequiredResponse {\n\treadonly x402Version: X402Version;\n\treadonly error?: string;\n\treadonly resource: X402ResourceInfo;\n\treadonly accepts: readonly X402PaymentRequirements[];\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Payment payload (client → server)\n// ---------------------------------------------------------------------------\n\n/**\n * EIP-3009 `TransferWithAuthorization` parameters in **wire format**.\n *\n * Note that `value`, `validAfter`, and `validBefore` are decimal strings here\n * (uint256-safe over JSON), whereas the in-process EIP-712 signing helpers in\n * `src/tokens/eip3009.ts` use `bigint`. Converters between the two\n * representations live in `src/x402/encoding.ts`.\n *\n * `nonce` is a 0x-prefixed 32-byte hex string — generate one with\n * {@link generateAuthorizationNonce} from `src/tokens/eip3009.ts`.\n */\nexport interface X402ExactEvmAuthorization {\n\treadonly from: Address;\n\treadonly to: Address;\n\treadonly value: string;\n\treadonly validAfter: string;\n\treadonly validBefore: string;\n\treadonly nonce: Hex;\n}\n\n/**\n * Scheme-specific `payload` body for the exact-EVM scheme using EIP-3009.\n *\n * `signature` is the 65-byte EIP-712 signature over a\n * `TransferWithAuthorization` message, produced by\n * {@link signTransferWithAuthorization}.\n */\nexport interface X402ExactEvmPayload {\n\treadonly signature: Hex;\n\treadonly authorization: X402ExactEvmAuthorization;\n}\n\n/**\n * The JSON body the client sends to a paywalled resource (typically base64-\n * encoded inside an `X-PAYMENT` header — see `src/x402/encoding.ts`).\n *\n * `accepted` is the single {@link X402PaymentRequirements} entry the client\n * chose from the server's `accepts` list. `payload` is scheme-specific; for\n * the exact-EVM scheme it has the shape of {@link X402ExactEvmPayload}.\n *\n * `payload` is typed as the open `Record<string, unknown>` so that this\n * interface stays structurally compatible with `@x402/core`'s `PaymentPayload`.\n * Use a scheme-aware parser to narrow it.\n */\nexport interface X402PaymentPayload {\n\treadonly x402Version: X402Version;\n\treadonly resource?: X402ResourceInfo;\n\treadonly accepted: X402PaymentRequirements;\n\treadonly payload: Record<string, unknown>;\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Settlement response (server → client, after settlement)\n// ---------------------------------------------------------------------------\n\n/**\n * The JSON body the resource server returns once the facilitator has settled\n * the payment (typically base64-encoded inside an `X-PAYMENT-RESPONSE`\n * header).\n *\n * On failure, `transaction` is an empty string and `errorReason` is set.\n */\nexport interface X402SettlementResponse {\n\treadonly success: boolean;\n\treadonly errorReason?: string;\n\treadonly errorMessage?: string;\n\treadonly payer?: Address;\n\treadonly transaction: string;\n\treadonly network: X402Network;\n\treadonly amount?: string;\n\treadonly extensions?: Record<string, unknown>;\n\treadonly extra?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Facilitator HTTP API (server ↔ facilitator)\n// ---------------------------------------------------------------------------\n\n/**\n * Body of `POST /verify` — asks the facilitator whether a payment payload\n * would settle, without broadcasting anything.\n */\nexport interface X402VerifyRequest {\n\treadonly x402Version: X402Version;\n\treadonly paymentPayload: X402PaymentPayload;\n\treadonly paymentRequirements: X402PaymentRequirements;\n}\n\n/** Response from `POST /verify`. */\nexport interface X402VerifyResponse {\n\treadonly isValid: boolean;\n\treadonly invalidReason?: string;\n\treadonly invalidMessage?: string;\n\treadonly payer?: Address;\n\treadonly extensions?: Record<string, unknown>;\n\treadonly extra?: Record<string, unknown>;\n}\n\n/**\n * Body of `POST /settle` — same shape as {@link X402VerifyRequest}. The\n * facilitator broadcasts the transaction and returns an\n * {@link X402SettlementResponse}.\n */\nexport type X402SettleRequest = X402VerifyRequest;\n\n/** Response from `POST /settle`. Same shape as {@link X402SettlementResponse}. */\nexport type X402SettleResponse = X402SettlementResponse;\n\n/**\n * One supported (scheme, network) pair returned by `GET /supported`.\n *\n * `network` is intentionally typed as `string` (not {@link X402Network}) here:\n * the facilitator may advertise networks kawasekit has not yet whitelisted, and\n * `kawasekit/x402` must be able to read that response to gate features (e.g.\n * skip the Coinbase facilitator demo when Polygon Amoy is not listed).\n */\nexport interface X402SupportedKind {\n\treadonly x402Version: X402Version;\n\treadonly scheme: string;\n\treadonly network: string;\n\treadonly extra?: Record<string, unknown>;\n}\n\n/** Response from `GET /supported`. */\nexport interface X402SupportedResponse {\n\treadonly kinds: readonly X402SupportedKind[];\n\treadonly extensions: readonly string[];\n\treadonly signers: Readonly<Record<string, readonly Address[]>>;\n}\n\n/**\n * A facilitator endpoint kawasekit can talk to.\n *\n * Two implementations live in `src/x402/facilitator.ts`:\n * - `createHttpFacilitator()` — proxies `/verify` & `/settle` over HTTP to any\n * x402 v2-compliant endpoint (Coinbase CDP, a self-hosted mirror, etc.)\n * - `createSelfFacilitator()` — runs `transferWithAuthorization` from a\n * private key kawasekit holds locally (testnet / self-host case)\n *\n * `createX402Handler()` accepts any object satisfying this interface and is\n * agnostic to the underlying transport (HTTPS, in-process, mocked).\n */\nexport interface Facilitator {\n\t/** Verify a payment payload without broadcasting. */\n\tverify(request: X402VerifyRequest): Promise<X402VerifyResponse>;\n\t/** Settle a verified payment — broadcasts to the chain. */\n\tsettle(request: X402SettleRequest): Promise<X402SettleResponse>;\n\t/** List supported (scheme, network) pairs. */\n\tsupported(): Promise<X402SupportedResponse>;\n}\n\n// ---------------------------------------------------------------------------\n// SupportedChainId ↔ X402Network conversions\n// ---------------------------------------------------------------------------\n\nconst EIP155_PREFIX = \"eip155:\" as const;\n\n/**\n * Builds the CAIP-2 {@link X402Network} string for a kawasekit-supported chain.\n *\n * @example\n * ```ts\n * import { chainIdToX402Network, polygonAmoy } from \"kawasekit\";\n *\n * const network = chainIdToX402Network(polygonAmoy.id); // \"eip155:80002\"\n * ```\n */\nexport function chainIdToX402Network<TChainId extends SupportedChainId>(\n\tchainId: TChainId,\n): `eip155:${TChainId}` {\n\treturn `${EIP155_PREFIX}${chainId}` as `eip155:${TChainId}`;\n}\n\n/**\n * Type guard for {@link X402Network}.\n *\n * Accepts only `eip155:N` strings where `N` is a kawasekit-supported chain ID.\n * A facilitator response advertising e.g. `\"eip155:8453\"` (Base) returns\n * `false` and should be treated as out-of-scope by the caller.\n */\nexport function isX402Network(value: string): value is X402Network {\n\tif (!value.startsWith(EIP155_PREFIX)) {\n\t\treturn false;\n\t}\n\tconst rest = value.slice(EIP155_PREFIX.length);\n\tif (rest.length === 0 || /^0\\d/.test(rest)) {\n\t\treturn false;\n\t}\n\tconst parsed = Number(rest);\n\tif (!Number.isInteger(parsed) || parsed < 0) {\n\t\treturn false;\n\t}\n\treturn isSupportedChainId(parsed);\n}\n\n/**\n * Extracts the {@link SupportedChainId} from an {@link X402Network}.\n *\n * Total over the {@link X402Network} type: if the input is `eip155:80002` the\n * result is `80002`. Use {@link isX402Network} first to narrow an arbitrary\n * `string`.\n *\n * @example\n * ```ts\n * import { x402NetworkToChainId } from \"kawasekit\";\n *\n * const chainId = x402NetworkToChainId(\"eip155:80002\"); // 80002\n * ```\n */\nexport function x402NetworkToChainId(network: X402Network): SupportedChainId {\n\tconst rest = network.slice(EIP155_PREFIX.length);\n\treturn Number(rest) as SupportedChainId;\n}\n","/**\n * x402 v2 client-side signer.\n *\n * Given a server-issued {@link X402PaymentRequirements}, produce a\n * {@link X402PaymentPayload} the client can send back in the next request. This\n * is the first runtime consumer of the M2 EIP-3009 helpers\n * ({@link signTransferWithAuthorization}, {@link authorizationDeadlineFromNow},\n * {@link generateAuthorizationNonce}).\n *\n * Scope:\n * - **exact-EVM scheme only.** Permit2 / ERC-7710 are M4+.\n * - **EOA payer only.** EIP-3009 uses pure `ecrecover` (no ERC-1271 fallback)\n * so smart accounts cannot be `from`. The agent-account flow is\n * {@link transferJpyc} (UserOp), not x402.\n *\n * @packageDocumentation\n */\n\nimport type { Account, Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { getChain, isSupportedChainId } from \"../chains\";\nimport { assertNonBypassable } from \"../signer/gate\";\nimport type { NonBypassableEnforcement, PaymentIntent, PolicyGatedSigner } from \"../signer/types\";\nimport type { X402AssetParam, X402TokenDomain } from \"../tokens/asset-domain\";\nimport { resolveAssetParam } from \"../tokens/asset-domain\";\nimport {\n\tauthorizationDeadlineFromNow,\n\tderiveAuthorizationNonce,\n\tgenerateAuthorizationNonce,\n\tsignTransferWithAuthorization,\n} from \"../tokens/eip3009\";\nimport { X402InvalidPayloadError, X402PolicyRejectedError } from \"./errors\";\nimport type {\n\tX402ExactEvmPayload,\n\tX402PaymentPayload,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n} from \"./types\";\nimport { X402_VERSION, x402NetworkToChainId } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default authorization lifetime (`validBefore = now + this`) when the caller\n * does not pass an override. Capped per-sign by `paymentRequirements.maxTimeoutSeconds`.\n *\n * 300 s matches the M3 example app's tolerance for Polygon Amoy bundler\n * inclusion latency (see plan risk #6).\n */\nexport const X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS = 300;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n// `X402TokenDomain` and `X402AssetParam` were lifted to `../tokens/asset-domain`\n// (M6-0) so the PolicyGatedSigner can reuse the same pinned-domain resolution.\n// Re-exported here for back-compat — consumers still import them from this module.\nexport type { X402AssetParam, X402TokenDomain };\n\n/**\n * Parameters for the `account` (EOA) variant of {@link createX402PaymentSigner}.\n *\n * Kept as a named, extensible `interface` (consumers may `extends` /\n * declaration-merge it). `maxAmountPerSign` pins the per-sign ceiling; for richer\n * policy use the `signer` variant ({@link CreateX402PaymentSignerSignerParams}).\n */\nexport interface CreateX402PaymentSignerAccountParams {\n\t/**\n\t * Declared production-vs-test intent. Each `sign()` call verifies that\n\t * `paymentRequirements.network` resolves to a chain whose `isTestnet`\n\t * agrees with this value, and throws otherwise. The point is to refuse\n\t * to sign a real-funds payment when the signer was configured for testnet\n\t * (e.g. the server unexpectedly demanded `polygon-mainnet` instead of\n\t * `polygon-amoy`).\n\t */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/**\n\t * EOA / LocalAccount that signs the EIP-3009 `TransferWithAuthorization`.\n\t * MUST be the same address the requirements' `from` will name.\n\t */\n\treadonly account: Account;\n\t/**\n\t * Asset binding (required). Pins the EIP-712 domain at construction time\n\t * and cross-checks `paymentRequirements.asset` at every sign call.\n\t * See {@link X402AssetParam} for the discriminated-union shape.\n\t *\n\t * **Threat 1.4 mitigation**: the wire-format `extra.name` and\n\t * `extra.version` are NOT consulted; a malicious server cannot coerce a\n\t * mismatched signature through them.\n\t */\n\treadonly asset: X402AssetParam;\n\t/**\n\t * Default authorization lifetime in seconds. Bounded by each\n\t * requirement's `maxTimeoutSeconds` at sign time.\n\t * Defaults to {@link X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS}.\n\t */\n\treadonly defaultLifetimeSeconds?: number;\n\t/**\n\t * Optional per-signature value ceiling, in the asset's smallest unit\n\t * (`bigint`). When set, `sign()` throws {@link X402InvalidPayloadError} if a\n\t * server advertises `requirements.amount` greater than this — refusing to\n\t * sign an over-budget payment at the primitive.\n\t *\n\t * **Threat 1.14 mitigation.** {@link createX402PaymentSigner} is a public API\n\t * and the direct-signer path bypasses the `wrapFetch` `onPayment` guard; the\n\t * EOA-payer x402 flow is also not bounded by the Layer-4 session-key daily\n\t * limit. This pins the *amount* ceiling the way {@link X402AssetParam} pins\n\t * the *asset* (1.4) — production posture is to set it. Omit it for no ceiling\n\t * (backward-compatible default; the payer EOA balance is the only bound).\n\t */\n\treadonly maxAmountPerSign?: bigint;\n\t/** Discriminant: absent on this arm — use the `signer` variant for a PolicyGatedSigner. */\n\treadonly signer?: never;\n}\n\n/**\n * Parameters for the `signer` (PolicyGatedSigner) variant of\n * {@link createX402PaymentSigner}. Drives signing through a\n * {@link PolicyGatedSigner} (e.g. `createLocalPolicyGatedSigner`); the per-sign\n * ceiling and richer policy live in the signer, so `maxAmountPerSign` is not\n * accepted here.\n */\nexport interface CreateX402PaymentSignerSignerParams {\n\t/** Declared production-vs-test intent (same semantics as the `account` variant). */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/** The policy-gated signer that produces the EIP-3009 authorization. */\n\treadonly signer: PolicyGatedSigner;\n\t/** Asset binding — pins the EIP-712 domain and cross-checks `paymentRequirements.asset`. */\n\treadonly asset: X402AssetParam;\n\t/**\n\t * Default authorization lifetime in seconds. Bounded per-sign by\n\t * `paymentRequirements.maxTimeoutSeconds`. Defaults to\n\t * {@link X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS}.\n\t */\n\treadonly defaultLifetimeSeconds?: number;\n\t/**\n\t * When set, asserts at construction that `signer` is non-bypassable\n\t * (`cryptographic` | `hardware`) — the runtime mirror of the\n\t * `requireNonBypassable` type-gate. Throws for an advisory signer.\n\t */\n\treadonly requireEnforcement?: NonBypassableEnforcement;\n\t/** Discriminant: absent on this arm. */\n\treadonly account?: never;\n\t/** Subsumed by the signer's policy; not accepted on this arm. */\n\treadonly maxAmountPerSign?: never;\n}\n\n/**\n * Parameters for {@link createX402PaymentSigner} — a discriminated union of the\n * `account` (EOA) and `signer` (PolicyGatedSigner) variants.\n *\n * NOTE: type-level breaking change from the original `interface` (a union cannot\n * be `extends`-ed). Existing `{ account, asset, network }` callers are\n * value-assignable to the `account` arm and unaffected; consumers who `extends`\n * / declaration-merge should use {@link CreateX402PaymentSignerAccountParams}.\n */\nexport type CreateX402PaymentSignerParams =\n\t| CreateX402PaymentSignerAccountParams\n\t| CreateX402PaymentSignerSignerParams;\n\n/** Parameters for {@link X402PaymentSigner.sign}. */\nexport interface SignX402PaymentParams {\n\t/** The chosen entry from the server's `accepts` array. */\n\treadonly paymentRequirements: X402PaymentRequirements;\n\t/** Optional {@link X402ResourceInfo} to echo back in the payload. */\n\treadonly resource?: X402ResourceInfo;\n\t/** Unix-seconds override of `validAfter`. Defaults to `0n`. */\n\treadonly validAfter?: bigint;\n\t/**\n\t * Unix-seconds override of `validBefore`. Defaults to `now + lifetime`\n\t * where lifetime = `min(signer default, requirements.maxTimeoutSeconds)`.\n\t */\n\treadonly validBefore?: bigint;\n\t/**\n\t * Optional reasoning-step idempotency key (M5-1, Half B). When supplied, the\n\t * EIP-3009 nonce is **derived deterministically** from it (instead of random)\n\t * so a re-signed same-intent payment produces the same on-chain nonce — the\n\t * token contract's `authorizationState` then rejects the duplicate\n\t * settlement. For a byte-identical re-sign, also pin `validBefore`. Build the\n\t * key with `createIdempotencyKeyBuilder` from `kawasekit/idempotency`.\n\t */\n\treadonly idempotencyKey?: string;\n}\n\n/** Signer returned by {@link createX402PaymentSigner}. */\nexport interface X402PaymentSigner {\n\t/** Address of the EOA bound to this signer. */\n\treadonly address: Address;\n\t/** Sign a payment for one {@link X402PaymentRequirements}. */\n\tsign(params: SignX402PaymentParams): Promise<X402PaymentPayload>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst UINT256_DECIMAL = /^(0|[1-9][0-9]*)$/;\n\nfunction parseUintString(value: string, field: string): bigint {\n\tif (!UINT256_DECIMAL.test(value)) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` must be a non-negative decimal string, got ${JSON.stringify(value)}`,\n\t\t);\n\t}\n\tconst parsed = BigInt(value);\n\tif (parsed > UINT256_MAX) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` exceeds uint256, got ${value}`,\n\t\t);\n\t}\n\treturn parsed;\n}\n\nfunction assertAddress(value: string, field: string): Address {\n\tif (!isAddress(value, { strict: false })) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` is not a valid address: ${value}`,\n\t\t);\n\t}\n\treturn value as Address;\n}\n\nfunction validateRequirements(requirements: X402PaymentRequirements): {\n\treadonly chainId: number;\n\treadonly value: bigint;\n\treadonly asset: Address;\n\treadonly payTo: Address;\n} {\n\tif (requirements.scheme !== \"exact\") {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`unsupported scheme: ${requirements.scheme}`,\n\t\t);\n\t}\n\tconst chainId = x402NetworkToChainId(requirements.network);\n\tif (!isSupportedChainId(chainId)) {\n\t\t// Defensive: an inbound payload typed as X402PaymentRequirements that\n\t\t// nonetheless smuggled an unsupported chainId via type-cast.\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`unsupported network: ${requirements.network}`,\n\t\t);\n\t}\n\tconst value = parseUintString(requirements.amount, \"amount\");\n\tif (value === 0n) {\n\t\tthrow new X402InvalidPayloadError(\"PaymentRequirements\", \"`amount` must be positive\");\n\t}\n\tif (requirements.maxTimeoutSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`maxTimeoutSeconds\\` must be positive, got ${requirements.maxTimeoutSeconds}`,\n\t\t);\n\t}\n\tconst asset = assertAddress(requirements.asset, \"asset\");\n\tconst payTo = assertAddress(requirements.payTo, \"payTo\");\n\treturn { chainId, value, asset, payTo };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Build an {@link X402PaymentSigner} bound to a single signing account.\n *\n * The returned signer can produce many {@link X402PaymentPayload}s in\n * succession — one per accepted requirement. Each call generates a fresh\n * EIP-3009 nonce.\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { createX402PaymentSigner } from \"kawasekit\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const signer = createX402PaymentSigner({\n * network: \"testnet\",\n * account,\n * asset: { kind: \"known\", id: \"jpyc-v2\" },\n * });\n *\n * // ...after receiving a 402 with PAYMENT-REQUIRED header...\n * const paymentPayload = await signer.sign({ paymentRequirements });\n * ```\n */\nexport function createX402PaymentSigner(params: CreateX402PaymentSignerParams): X402PaymentSigner {\n\tif (params.signer !== undefined) {\n\t\treturn createSignerBackedX402PaymentSigner(params);\n\t}\n\tconst { account, network } = params;\n\tconst defaultLifetimeSeconds =\n\t\tparams.defaultLifetimeSeconds ?? X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS;\n\tif (defaultLifetimeSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`defaultLifetimeSeconds\\` must be positive, got ${defaultLifetimeSeconds}`,\n\t\t);\n\t}\n\tconst maxAmountPerSign = params.maxAmountPerSign;\n\tif (maxAmountPerSign !== undefined && maxAmountPerSign <= 0n) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`maxAmountPerSign\\` must be a positive bigint, got ${maxAmountPerSign}`,\n\t\t);\n\t}\n\tconst pinnedDomain = resolveAssetParam(params.asset);\n\n\treturn {\n\t\taddress: account.address,\n\t\tasync sign(signParams) {\n\t\t\tconst { paymentRequirements } = signParams;\n\t\t\tconst { chainId, value, asset, payTo } = validateRequirements(paymentRequirements);\n\t\t\tconst chain = getChain(chainId);\n\t\t\tif (network === \"mainnet\" && chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"mainnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a testnet`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (network === \"testnet\" && !chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"testnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a mainnet — refusing to sign payment for real funds`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (getAddress(asset) !== pinnedDomain.verifyingContract) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.asset (${getAddress(asset)}) does not match the signer's pinned verifyingContract (${pinnedDomain.verifyingContract}) — refusing to sign for an asset the signer was not configured to handle`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (maxAmountPerSign !== undefined && value > maxAmountPerSign) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.amount (${value}) exceeds the signer's \\`maxAmountPerSign\\` ceiling (${maxAmountPerSign}) — refusing to sign a payment above the configured per-signature limit (threat 1.14)`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst lifetime = Math.min(defaultLifetimeSeconds, paymentRequirements.maxTimeoutSeconds);\n\t\t\tconst validAfter = signParams.validAfter ?? 0n;\n\t\t\tconst validBefore = signParams.validBefore ?? authorizationDeadlineFromNow(lifetime);\n\t\t\tif (validBefore <= validAfter) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`\\`validBefore\\` (${validBefore}) must be greater than \\`validAfter\\` (${validAfter})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nonce =\n\t\t\t\tsignParams.idempotencyKey !== undefined\n\t\t\t\t\t? deriveAuthorizationNonce(\n\t\t\t\t\t\t\t{ idempotencyKey: signParams.idempotencyKey },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfrom: account.address,\n\t\t\t\t\t\t\t\tverifyingContract: pinnedDomain.verifyingContract,\n\t\t\t\t\t\t\t\tchainId,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateAuthorizationNonce();\n\t\t\tconst signed = await signTransferWithAuthorization(\n\t\t\t\taccount,\n\t\t\t\t{\n\t\t\t\t\tname: pinnedDomain.name,\n\t\t\t\t\tversion: pinnedDomain.version,\n\t\t\t\t\tchainId,\n\t\t\t\t\tverifyingContract: pinnedDomain.verifyingContract,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tfrom: account.address,\n\t\t\t\t\tto: payTo,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalidAfter,\n\t\t\t\t\tvalidBefore,\n\t\t\t\t\tnonce,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tconst payload: X402ExactEvmPayload = {\n\t\t\t\tsignature: signed.signature,\n\t\t\t\tauthorization: {\n\t\t\t\t\tfrom: signed.message.from,\n\t\t\t\t\tto: signed.message.to,\n\t\t\t\t\tvalue: signed.message.value.toString(),\n\t\t\t\t\tvalidAfter: signed.message.validAfter.toString(),\n\t\t\t\t\tvalidBefore: signed.message.validBefore.toString(),\n\t\t\t\t\tnonce: signed.message.nonce,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst result: X402PaymentPayload = signParams.resource\n\t\t\t\t? {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\tresource: signParams.resource,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t};\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n/**\n * The `signer` (PolicyGatedSigner) variant of {@link createX402PaymentSigner}.\n *\n * Shares the `account` path's validate / network / asset-pin / window / nonce\n * prologue (kept in sync deliberately — the two security checks must not drift),\n * then routes the EIP-3009 signing through the {@link PolicyGatedSigner}. A\n * policy denial (`sign()` → `{ ok: false }`) surfaces as a thrown\n * {@link X402PolicyRejectedError}, so the `X402PaymentSigner.sign()` contract is\n * unchanged (returns a payload or throws). The per-sign ceiling is the signer's\n * policy, so there is no `maxAmountPerSign` check here.\n */\nfunction createSignerBackedX402PaymentSigner(\n\tparams: CreateX402PaymentSignerSignerParams,\n): X402PaymentSigner {\n\tconst { signer, network } = params;\n\tconst defaultLifetimeSeconds =\n\t\tparams.defaultLifetimeSeconds ?? X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS;\n\tif (defaultLifetimeSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`defaultLifetimeSeconds\\` must be positive, got ${defaultLifetimeSeconds}`,\n\t\t);\n\t}\n\tif (params.requireEnforcement !== undefined) {\n\t\tassertNonBypassable(signer);\n\t}\n\tconst pinnedDomain = resolveAssetParam(params.asset);\n\tconst from = signer.from;\n\n\treturn {\n\t\taddress: from,\n\t\tasync sign(signParams) {\n\t\t\tconst { paymentRequirements } = signParams;\n\t\t\tconst { chainId, value, asset, payTo } = validateRequirements(paymentRequirements);\n\t\t\tconst chain = getChain(chainId);\n\t\t\tif (network === \"mainnet\" && chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"mainnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a testnet`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (network === \"testnet\" && !chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"testnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a mainnet — refusing to sign payment for real funds`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (getAddress(asset) !== pinnedDomain.verifyingContract) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.asset (${getAddress(asset)}) does not match the signer's pinned verifyingContract (${pinnedDomain.verifyingContract}) — refusing to sign for an asset the signer was not configured to handle`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst lifetime = Math.min(defaultLifetimeSeconds, paymentRequirements.maxTimeoutSeconds);\n\t\t\tconst validAfter = signParams.validAfter ?? 0n;\n\t\t\tconst validBefore = signParams.validBefore ?? authorizationDeadlineFromNow(lifetime);\n\t\t\tif (validBefore <= validAfter) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`\\`validBefore\\` (${validBefore}) must be greater than \\`validAfter\\` (${validAfter})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nonce =\n\t\t\t\tsignParams.idempotencyKey !== undefined\n\t\t\t\t\t? deriveAuthorizationNonce(\n\t\t\t\t\t\t\t{ idempotencyKey: signParams.idempotencyKey },\n\t\t\t\t\t\t\t{ from, verifyingContract: pinnedDomain.verifyingContract, chainId },\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateAuthorizationNonce();\n\n\t\t\tconst intent: PaymentIntent = {\n\t\t\t\ttoken: pinnedDomain.verifyingContract,\n\t\t\t\tchainId,\n\t\t\t\tfrom,\n\t\t\t\tto: payTo,\n\t\t\t\tvalue,\n\t\t\t\tvalidAfter,\n\t\t\t\tvalidBefore,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tconst signResult = await signer.sign(intent);\n\t\t\tif (!signResult.ok) {\n\t\t\t\tthrow new X402PolicyRejectedError(signResult.rejection);\n\t\t\t}\n\n\t\t\tconst payload: X402ExactEvmPayload = {\n\t\t\t\tsignature: signResult.signature,\n\t\t\t\tauthorization: {\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: payTo,\n\t\t\t\t\tvalue: value.toString(),\n\t\t\t\t\tvalidAfter: validAfter.toString(),\n\t\t\t\t\tvalidBefore: validBefore.toString(),\n\t\t\t\t\tnonce,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst result: X402PaymentPayload = signParams.resource\n\t\t\t\t? {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\tresource: signParams.resource,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t};\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","/**\n * Wire-format encoding for x402 v2 headers.\n *\n * Three pairs of `encode*` / `decode*` helpers, one per x402 v2 HTTP header:\n *\n * | Direction | Header | Payload type |\n * | ---------------- | ------------------- | -------------------------------- |\n * | server → client | `PAYMENT-REQUIRED` | {@link X402PaymentRequiredResponse} |\n * | client → server | `PAYMENT-SIGNATURE` | {@link X402PaymentPayload} |\n * | server → client | `PAYMENT-RESPONSE` | {@link X402SettlementResponse} |\n *\n * Encoding rules (match `@x402/core@2.13.0` byte-for-byte so kawasekit payloads\n * decode in any spec-compliant client / facilitator):\n *\n * - The payload is JSON-stringified, then UTF-8 → base64 encoded.\n * - **Standard base64** with `+` / `/` and `=` padding, **not** URL-safe base64.\n * (Header values flow through `Authorization`-style positions where `+` is\n * acceptable in the v2 spec.)\n * - The replacer used by `JSON.stringify` rewrites any stray `bigint` value to\n * its decimal string form, so kawasekit callers can hand a payload whose\n * `value` / `validAfter` / `validBefore` are bigints by mistake and the\n * encoder still produces a spec-conformant string — silent corruption\n * surfaces as a type error in `tsc`, not a runtime crash.\n *\n * Decoders are intentionally minimal: base64 syntax check + `JSON.parse` + a\n * \"must be a plain object\" sanity check. Schema-level validation lives one\n * layer up (in `server.ts` and `client.ts`) so that this module stays a small,\n * dependency-free wire codec.\n *\n * @packageDocumentation\n */\n\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentPayload,\n\tX402PaymentRequiredResponse,\n\tX402SettlementResponse,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// HTTP header names (x402 v2 transport spec)\n// ---------------------------------------------------------------------------\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402PaymentRequiredResponse} alongside the HTTP 402 status.\n */\nexport const X402_HEADER_PAYMENT_REQUIRED = \"PAYMENT-REQUIRED\" as const;\n\n/**\n * Name of the request header that carries the client's base64-encoded\n * {@link X402PaymentPayload}.\n *\n * Note: x402 v1 used `X-PAYMENT`. v2 drops the `X-` prefix. Servers may accept\n * both during transition; clients should send only this v2 name.\n */\nexport const X402_HEADER_PAYMENT_SIGNATURE = \"PAYMENT-SIGNATURE\" as const;\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402SettlementResponse} after a successful settlement.\n */\nexport const X402_HEADER_PAYMENT_RESPONSE = \"PAYMENT-RESPONSE\" as const;\n\n/**\n * Name of the optional request header that carries a reasoning-step idempotency\n * key (M5-1). Standard `Idempotency-Key` (IETF draft / Stripe-compatible). When\n * present, the x402 server deduplicates on this logical key; the EIP-3009 nonce\n * remains the on-chain fund backstop. See `docs/rfc/m5-1-reasoning-step-idempotency.md`.\n */\nexport const X402_HEADER_IDEMPOTENCY_KEY = \"Idempotency-Key\" as const;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n// Canonical base64 per RFC 4648 §4: encoded length is a multiple of 4 and the\n// only legal trailing forms are `XX==`, `XXX=`, or `XXXX` (no padding). The\n// outer prefix is zero or more 4-char groups; the optional inner alternation\n// matches a single final group of 4 chars or a properly padded 2-or-3 char\n// group. This shape rejects the non-canonical forms an adversary could try\n// to smuggle past the decoder — overlong padding (`X===`), misplaced padding\n// (`X=XX`), short tails (`XXX` with no `=`), or non-mod-4 lengths.\n//\n// See `docs/THREAT_MODEL.md` §6.7 for the M4 review trail and\n// `src/x402/encoding.test.ts` \"RFC 4648 canonical enforcement\" for the\n// adversarial corpus.\n/**\n * Strict RFC 4648 §4 canonical base64 matcher. Exported for the\n * property-based test in `encoding.test.ts` (Threat 1.7 / §6.7\n * regex-vs-decoder agreement); not intended as part of the public API.\n *\n * @internal\n */\nexport const BASE64_REGEX =\n\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})?$/;\n\nfunction bigIntReplacer(_key: string, value: unknown): unknown {\n\treturn typeof value === \"bigint\" ? value.toString() : value;\n}\n\nfunction stringifyBigIntSafe(value: unknown): string {\n\treturn JSON.stringify(value, bigIntReplacer);\n}\n\nfunction utf8ToBase64(input: string): string {\n\t// Cross-env: prefer `btoa` (browsers, Workers, Bun, modern Node 18+) and\n\t// fall back to `Buffer` for older Node where `btoa` was Latin-1-only.\n\tif (typeof globalThis.btoa === \"function\") {\n\t\tconst bytes = new TextEncoder().encode(input);\n\t\tlet binary = \"\";\n\t\tfor (const byte of bytes) {\n\t\t\tbinary += String.fromCharCode(byte);\n\t\t}\n\t\treturn globalThis.btoa(binary);\n\t}\n\treturn Buffer.from(input, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Internal helper exported for the regex-vs-decoder property-based test.\n * Not part of the public API.\n *\n * @internal\n */\nexport function base64ToUtf8(input: string): string {\n\tif (typeof globalThis.atob === \"function\") {\n\t\tconst binary = globalThis.atob(input);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i);\n\t\t}\n\t\treturn new TextDecoder(\"utf-8\").decode(bytes);\n\t}\n\treturn Buffer.from(input, \"base64\").toString(\"utf8\");\n}\n\nfunction decodeHeader<T>(headerName: string, headerValue: string): T {\n\tif (!BASE64_REGEX.test(headerValue)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"header is not valid base64\");\n\t}\n\tlet json: string;\n\ttry {\n\t\tjson = base64ToUtf8(headerValue);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"base64 decode failed\", { cause });\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not valid JSON\", { cause });\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not a JSON object\");\n\t}\n\treturn parsed as T;\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-REQUIRED\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentRequiredResponse} as a base64 string suitable\n * for the `PAYMENT-REQUIRED` response header.\n *\n * @example\n * ```ts\n * import { encodePaymentRequiredHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentRequiredHeader({\n * x402Version: 2,\n * resource: { url: \"https://api.example.com/data\" },\n * accepts: [],\n * });\n * res.setHeader(\"PAYMENT-REQUIRED\", headerValue);\n * ```\n */\nexport function encodePaymentRequiredHeader(payload: X402PaymentRequiredResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-REQUIRED` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentRequiredHeader(headerValue: string): X402PaymentRequiredResponse {\n\treturn decodeHeader<X402PaymentRequiredResponse>(X402_HEADER_PAYMENT_REQUIRED, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-SIGNATURE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentPayload} as a base64 string suitable for the\n * `PAYMENT-SIGNATURE` request header.\n *\n * @example\n * ```ts\n * import { encodePaymentSignatureHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentSignatureHeader(paymentPayload);\n * await fetch(url, { headers: { \"PAYMENT-SIGNATURE\": headerValue } });\n * ```\n */\nexport function encodePaymentSignatureHeader(payload: X402PaymentPayload): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-SIGNATURE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentSignatureHeader(headerValue: string): X402PaymentPayload {\n\treturn decodeHeader<X402PaymentPayload>(X402_HEADER_PAYMENT_SIGNATURE, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-RESPONSE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402SettlementResponse} as a base64 string suitable for\n * the `PAYMENT-RESPONSE` response header.\n */\nexport function encodePaymentResponseHeader(payload: X402SettlementResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-RESPONSE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentResponseHeader(headerValue: string): X402SettlementResponse {\n\treturn decodeHeader<X402SettlementResponse>(X402_HEADER_PAYMENT_RESPONSE, headerValue);\n}\n","/**\n * Observability hooks — the base interface that the kawasekit core surfaces\n * (facilitator, x402 handler, wrapFetch) emit events to. Operators wire metrics\n * / logs / traces by passing one of:\n *\n * - their own callback set (zero new dependencies, full control)\n * - one of the optional adapters at `kawasekit/observability/prometheus` or\n * `kawasekit/observability/otlp` (push-button Prometheus / OTLP metrics)\n *\n * Design points worth reading before writing an adapter:\n *\n * - **All hooks are fire-and-forget.** {@link invokeHookSafely} swallows both\n * synchronous throws and rejected Promises so hook misbehaviour cannot\n * destabilise the kawasekit hot path. Adapters should still wrap any\n * external I/O (HTTP exporter pushes, etc.) in their own resilience layer.\n *\n * - **Events carry timing.** Every event extends {@link ObservabilityEventBase}\n * with a `startedAtMs` wall-clock timestamp and a `durationMs` measurement\n * so histograms (Prometheus, OTLP) can be derived without the adapter\n * needing to thread its own clocks.\n *\n * - **No private data leaks.** Hooks intentionally omit signatures, nonces,\n * and authorization bytes. They expose only the public-after-broadcast\n * metadata (payer, amount, network, tx hash, x402 error code) — enough for\n * dashboards, not enough to replay a payment.\n *\n * - **Failure events carry x402 spec error codes verbatim.** The\n * `invalidReason` / `errorReason` fields are the canonical x402 v2 codes\n * (e.g. `insufficient_funds`, `invalid_exact_evm_payload_signature`). This\n * gives adapters a stable label vocabulary that Grafana / Datadog can group\n * by without ad-hoc parsing.\n *\n * @packageDocumentation\n */\n\nimport type { Address, Hex } from \"viem\";\nimport type { X402Network, X402PaymentRequirements } from \"../x402/types\";\n\n// ---------------------------------------------------------------------------\n// Event types\n// ---------------------------------------------------------------------------\n\n/** Fields shared by every observability event. */\nexport interface ObservabilityEventBase {\n\t/** Wall-clock unix milliseconds when the observed operation started. */\n\treadonly startedAtMs: number;\n\t/** Wall-clock duration of the observed operation in milliseconds. */\n\treadonly durationMs: number;\n}\n\n/** Emitted by {@link createSelfFacilitator} after every `verify()` call. */\nexport type VerifyEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"verify\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer: Address;\n\t\t\t/** Authorization amount in token-base units (wei for 18-decimal JPYC). */\n\t\t\treadonly amount: string;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"verify\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly network: X402Network;\n\t\t\t/** Payer address if it was recoverable before the failure. */\n\t\t\treadonly payer?: Address;\n\t\t\t/** x402 v2 invalidReason code (e.g. `invalid_payload`). */\n\t\t\treadonly invalidReason: string;\n\t\t\t/** Human-readable detail; never includes private credentials. */\n\t\t\treadonly invalidMessage?: string;\n\t });\n\n/** Emitted by {@link createSelfFacilitator} after every `settle()` call. */\nexport type SettleEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"settle\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer: Address;\n\t\t\treadonly amount: string;\n\t\t\t/** On-chain transaction hash of the broadcast settlement. */\n\t\t\treadonly transaction: Hex;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"settle\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer?: Address;\n\t\t\t/** x402 v2 errorReason code (e.g. `insufficient_funds`). */\n\t\t\treadonly errorReason: string;\n\t\t\treadonly errorMessage?: string;\n\t\t\t/** Tx hash if the broadcast succeeded but the receipt reverted. */\n\t\t\treadonly transaction?: Hex;\n\t });\n\n/** Emitted by {@link createX402Handler} when it returns HTTP 402. */\nexport interface PaymentRequiredEvent extends ObservabilityEventBase {\n\treadonly kind: \"payment_required\";\n\t/** The URL that triggered the paywall, taken from `Request.url`. */\n\treadonly requestUrl: string;\n\t/** Networks listed in the `accepts` array, in order. */\n\treadonly acceptedNetworks: readonly X402Network[];\n}\n\n/** Emitted by {@link createX402Handler} when settlement unlocks the inner handler. */\nexport interface PaymentAcceptedEvent extends ObservabilityEventBase {\n\treadonly kind: \"payment_accepted\";\n\treadonly requestUrl: string;\n\treadonly payer: Address;\n\treadonly amount: string;\n\treadonly network: X402Network;\n\treadonly transaction: Hex;\n}\n\n/** Emitted by {@link wrapFetch} after each paywall round-trip. */\nexport type ClientPaymentEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"client_payment\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly requestUrl: string;\n\t\t\treadonly payer: Address;\n\t\t\treadonly amount: string;\n\t\t\treadonly network: X402Network;\n\t\t\t/** Settlement tx hash if the server echoed it back in PAYMENT-RESPONSE. */\n\t\t\treadonly transaction?: Hex;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"client_payment\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly requestUrl: string;\n\t\t\t/** Short label: `onPayment_declined` / `no_acceptable_requirement` / `settle_rejected` / `http_error`. */\n\t\t\treadonly reason: string;\n\t\t\treadonly httpStatus?: number;\n\t });\n\n/** Discriminated union of every event the hook surface may emit. */\nexport type ObservabilityEvent =\n\t| VerifyEvent\n\t| SettleEvent\n\t| PaymentRequiredEvent\n\t| PaymentAcceptedEvent\n\t| ClientPaymentEvent;\n\n// ---------------------------------------------------------------------------\n// Hook callback shapes\n// ---------------------------------------------------------------------------\n\n/** Generic shape of a hook callback. Async hooks are fire-and-forget. */\nexport type HookCallback<TEvent> = (event: TEvent) => void | Promise<void>;\n\n/**\n * The complete kawasekit observability surface. All fields are optional —\n * pass only the hooks for the events you care about.\n *\n * @example\n * ```ts\n * import { createSelfFacilitator } from \"kawasekit\";\n *\n * const facilitator = createSelfFacilitator({\n * network: \"testnet\",\n * walletClient,\n * publicClient,\n * hooks: {\n * onSettle: (event) => {\n * if (event.result === \"success\") {\n * console.log(\"settled\", event.network, event.amount, event.transaction);\n * } else {\n * console.warn(\"settle failed\", event.errorReason);\n * }\n * },\n * },\n * });\n * ```\n */\nexport interface ObservabilityHooks {\n\t/** Fired after every facilitator `verify()`. Discriminate on `event.result`. */\n\treadonly onVerify?: HookCallback<VerifyEvent>;\n\t/** Fired after every facilitator `settle()`. Discriminate on `event.result`. */\n\treadonly onSettle?: HookCallback<SettleEvent>;\n\t/** Fired when the x402 handler returns 402 (no payment yet). */\n\treadonly onPaymentRequired?: HookCallback<PaymentRequiredEvent>;\n\t/** Fired when a settled payment unlocks the inner x402 handler. */\n\treadonly onPaymentAccepted?: HookCallback<PaymentAcceptedEvent>;\n\t/** Fired by `wrapFetch` after each paywall round-trip. */\n\treadonly onClientPayment?: HookCallback<ClientPaymentEvent>;\n}\n\n// ---------------------------------------------------------------------------\n// Safe invocation helper\n// ---------------------------------------------------------------------------\n\n/**\n * Invokes a single optional hook and swallows both synchronous throws and\n * rejected Promises. Use this at every site where the kawasekit core surfaces\n * call user-provided callbacks — it is the contract that guarantees hooks\n * cannot destabilise verify / settle / fetch flows.\n *\n * If a hook misbehaves, the error is discarded silently — kawasekit's\n * observability promise is \"best-effort, never blocking\". Future work\n * (planned in plan D12) may route discarded errors to a structured logger so\n * operators can see hook bugs without paying for them in hot paths.\n *\n * @example\n * ```ts\n * import { invokeHookSafely } from \"kawasekit/observability\";\n *\n * invokeHookSafely(hooks.onSettle, {\n * kind: \"settle\",\n * result: \"success\",\n * startedAtMs,\n * durationMs: Date.now() - startedAtMs,\n * network: \"eip155:80002\",\n * payer,\n * amount,\n * transaction: txHash,\n * });\n * ```\n */\nexport function invokeHookSafely<TEvent>(\n\thook: HookCallback<TEvent> | undefined,\n\tevent: TEvent,\n): void {\n\tif (hook === undefined) return;\n\ttry {\n\t\tconst result = hook(event);\n\t\tif (result instanceof Promise) {\n\t\t\tresult.catch(() => {\n\t\t\t\t// Discard async rejection — observability hooks are fire-and-forget.\n\t\t\t});\n\t\t}\n\t} catch {\n\t\t// Discard sync throw — observability hooks are fire-and-forget.\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Helpers for adapter authors\n// ---------------------------------------------------------------------------\n\n/**\n * Type-safe pluck of the `accepts` network list from a\n * {@link X402PaymentRequirements} array. Adapter authors can use this to build\n * `acceptedNetworks` for {@link PaymentRequiredEvent} without re-implementing\n * the narrow.\n *\n * @example\n * ```ts\n * import { extractAcceptedNetworks } from \"kawasekit/observability\";\n *\n * const acceptedNetworks = extractAcceptedNetworks(requirements);\n * ```\n */\nexport function extractAcceptedNetworks(\n\trequirements: readonly X402PaymentRequirements[],\n): readonly X402Network[] {\n\treturn requirements.map((req) => req.network);\n}\n","/**\n * Facilitator implementations: local viem-backed (`createSelfFacilitator`) and\n * HTTP-proxied (`createHttpFacilitator`).\n *\n * Both expose the same {@link Facilitator} interface — `verify` / `settle` /\n * `supported` — so {@link createX402Handler} can swap one for the other based\n * on environment (testnet vs. mainnet, self-hosted vs. Coinbase CDP).\n *\n * Spec references:\n * - Error codes: x402 v2 spec §9 (Error Handling)\n * - Verification steps: scheme_exact_evm.md §1 Phase 2\n * - Facilitator HTTP API: x402 v2 spec §7\n *\n * @packageDocumentation\n */\n\nimport type { Account, Address, Chain, Hex, PublicClient, Transport, WalletClient } from \"viem\";\nimport { getAddress, parseSignature, recoverTypedDataAddress } from \"viem\";\nimport { getChain, isSupportedChainId, type KawaseChain, type SupportedChainId } from \"../chains\";\nimport {\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n\ttype SettleEvent,\n\ttype VerifyEvent,\n} from \"../observability/hooks\";\nimport { JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS, jpycAbi } from \"../tokens/jpyc\";\nimport type {\n\tFacilitator,\n\tX402PaymentRequirements,\n\tX402SettleRequest,\n\tX402SettleResponse,\n\tX402SupportedKind,\n\tX402SupportedResponse,\n\tX402VerifyRequest,\n\tX402VerifyResponse,\n} from \"./types\";\nimport { chainIdToX402Network, X402_VERSION, x402NetworkToChainId } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Error code vocabulary (x402 v2 §9)\n// ---------------------------------------------------------------------------\n\n/**\n * Standard x402 v2 error codes used as `invalidReason` (verify) and\n * `errorReason` (settle). Kept as string literals so that consumers can\n * `switch` on the union; values match the spec verbatim.\n */\nexport const X402_FACILITATOR_ERROR_CODES = {\n\tinsufficient_funds: \"insufficient_funds\",\n\tinvalid_exact_evm_payload_authorization_valid_after:\n\t\t\"invalid_exact_evm_payload_authorization_valid_after\",\n\tinvalid_exact_evm_payload_authorization_valid_before:\n\t\t\"invalid_exact_evm_payload_authorization_valid_before\",\n\tinvalid_exact_evm_payload_authorization_value_mismatch:\n\t\t\"invalid_exact_evm_payload_authorization_value_mismatch\",\n\tinvalid_exact_evm_payload_recipient_mismatch: \"invalid_exact_evm_payload_recipient_mismatch\",\n\tinvalid_exact_evm_payload_signature: \"invalid_exact_evm_payload_signature\",\n\tinvalid_network: \"invalid_network\",\n\tinvalid_payload: \"invalid_payload\",\n\tinvalid_scheme: \"invalid_scheme\",\n\tinvalid_transaction_state: \"invalid_transaction_state\",\n\tunexpected_settle_error: \"unexpected_settle_error\",\n\tunexpected_verify_error: \"unexpected_verify_error\",\n} as const;\n\ntype X402FacilitatorErrorCode =\n\t(typeof X402_FACILITATOR_ERROR_CODES)[keyof typeof X402_FACILITATOR_ERROR_CODES];\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\ninterface NarrowExactEvmPayload {\n\treadonly signature: Hex;\n\treadonly authorization: {\n\t\treadonly from: Address;\n\t\treadonly to: Address;\n\t\treadonly value: string;\n\t\treadonly validAfter: string;\n\t\treadonly validBefore: string;\n\t\treadonly nonce: Hex;\n\t};\n}\n\nfunction isHex(value: unknown): value is Hex {\n\treturn typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n}\n\nfunction isAddressLike(value: unknown): value is Address {\n\treturn typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value);\n}\n\nfunction isDecimalString(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^(0|[1-9][0-9]*)$/.test(value);\n}\n\nfunction narrowExactEvmPayload(payload: Record<string, unknown>): NarrowExactEvmPayload | null {\n\tconst p = payload as { signature?: unknown; authorization?: unknown };\n\tif (!isHex(p.signature)) return null;\n\tif (typeof p.authorization !== \"object\" || p.authorization === null) return null;\n\tconst a = p.authorization as {\n\t\tfrom?: unknown;\n\t\tto?: unknown;\n\t\tvalue?: unknown;\n\t\tvalidAfter?: unknown;\n\t\tvalidBefore?: unknown;\n\t\tnonce?: unknown;\n\t};\n\tif (!isAddressLike(a.from)) return null;\n\tif (!isAddressLike(a.to)) return null;\n\tif (!isDecimalString(a.value)) return null;\n\tif (!isDecimalString(a.validAfter)) return null;\n\tif (!isDecimalString(a.validBefore)) return null;\n\tif (!isHex(a.nonce)) return null;\n\treturn {\n\t\tsignature: p.signature,\n\t\tauthorization: {\n\t\t\tfrom: a.from,\n\t\t\tto: a.to,\n\t\t\tvalue: a.value,\n\t\t\tvalidAfter: a.validAfter,\n\t\t\tvalidBefore: a.validBefore,\n\t\t\tnonce: a.nonce,\n\t\t},\n\t};\n}\n\nconst TRANSFER_AUTHORIZATION_TYPES = {\n\tTransferWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\nfunction resolveDomain(requirements: X402PaymentRequirements): {\n\treadonly name: string;\n\treadonly version: string;\n} {\n\tconst extra = requirements.extra as { name?: unknown; version?: unknown };\n\tif (typeof extra.name === \"string\" && typeof extra.version === \"string\") {\n\t\treturn { name: extra.name, version: extra.version };\n\t}\n\tif (getAddress(requirements.asset) === getAddress(JPYC_V2_ADDRESS)) {\n\t\treturn JPYC_EIP712_DOMAIN_HINT;\n\t}\n\tthrow new Error(\n\t\t\"resolveDomain: `extra.name` and `extra.version` are required for non-JPYC assets\",\n\t);\n}\n\nfunction failVerify(\n\treason: X402FacilitatorErrorCode,\n\tmessage?: string,\n\tpayer?: Address,\n): X402VerifyResponse {\n\tif (message !== undefined && payer !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, invalidMessage: message, payer };\n\t}\n\tif (message !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, invalidMessage: message };\n\t}\n\tif (payer !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, payer };\n\t}\n\treturn { isValid: false, invalidReason: reason };\n}\n\nfunction failSettle(\n\tnetwork: X402SettleResponse[\"network\"],\n\treason: X402FacilitatorErrorCode,\n\toptions: { message?: string; payer?: Address; transaction?: string } = {},\n): X402SettleResponse {\n\tconst transaction = options.transaction ?? \"\";\n\tconst base: X402SettleResponse = {\n\t\tsuccess: false,\n\t\terrorReason: reason,\n\t\ttransaction,\n\t\tnetwork,\n\t};\n\tif (options.message !== undefined && options.payer !== undefined) {\n\t\treturn { ...base, errorMessage: options.message, payer: options.payer };\n\t}\n\tif (options.message !== undefined) {\n\t\treturn { ...base, errorMessage: options.message };\n\t}\n\tif (options.payer !== undefined) {\n\t\treturn { ...base, payer: options.payer };\n\t}\n\treturn base;\n}\n\n// ---------------------------------------------------------------------------\n// Self-facilitator (local viem-backed)\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link createSelfFacilitator}. */\nexport interface CreateSelfFacilitatorParams {\n\t/**\n\t * Declared production-vs-test intent. MUST agree with `walletClient.chain`:\n\t * - `\"mainnet\"` requires a kawasekit chain with `isTestnet === false`.\n\t * - `\"testnet\"` requires a kawasekit chain with `isTestnet === true`.\n\t *\n\t * The check is enforced at construction time and throws a fatal error on\n\t * disagreement. The point is to make accidentally pointing a testnet\n\t * configuration at a mainnet RPC (or vice versa) impossible — that mistake\n\t * would broadcast real-fund transactions silently.\n\t */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/**\n\t * Pre-configured wallet client that broadcasts settlement transactions.\n\t * The bound account pays gas. `walletClient.chain.id` determines the only\n\t * chain this facilitator serves, and `walletClient.chain.isTestnet` MUST\n\t * agree with the declared {@link network}.\n\t */\n\treadonly walletClient: WalletClient<Transport, Chain, Account>;\n\t/**\n\t * Pre-configured public client on the same chain as `walletClient`. Used\n\t * for balance and authorization-state reads during verify.\n\t */\n\treadonly publicClient: PublicClient<Transport, Chain>;\n\t/**\n\t * Timeout (ms) for `waitForTransactionReceipt` during settle.\n\t * Defaults to 60_000.\n\t */\n\treadonly receiptTimeoutMs?: number;\n\t/**\n\t * Number of block confirmations to wait past the settle tx inclusion\n\t * before considering settlement final. Mitigates threat 2.8 (settle\n\t * tx reorg producing a \"content delivered, payment reverted\" state)\n\t * by raising the bar past Polygon PoS's typical reorg depth.\n\t *\n\t * Chain-aware defaults if omitted:\n\t * - testnet (Polygon Amoy): `1` — fast feedback for dev loops, no\n\t * real funds at risk\n\t * - mainnet (Polygon): `4` — roughly ~8 s of soft finality at\n\t * Polygon's ~2 s block time, suitable for the small-value paywall\n\t * hits kawasekit targets (sub-100 JPYC per call)\n\t *\n\t * For high-value merchants — or any deployment uncomfortable with\n\t * shallow reorg risk — raise this to 32+ and bump\n\t * {@link receiptTimeoutMs} so the timeout still accommodates the\n\t * wait. See `docs/THREAT_MODEL.md` §2.8 / §6.6.\n\t */\n\treadonly confirmations?: number;\n\t/**\n\t * Optional observability callbacks. Hooks are fire-and-forget — any throw\n\t * or rejection inside a hook is silently discarded and never propagates to\n\t * the verify / settle return path. See {@link ObservabilityHooks}.\n\t *\n\t * The facilitator emits `onVerify` after every `verify()` call (including\n\t * the internal re-verify that runs at the start of `settle()`) and\n\t * `onSettle` after every `settle()` call.\n\t */\n\treadonly hooks?: ObservabilityHooks;\n}\n\nconst RECEIPT_TIMEOUT_FLOOR_MS = 60_000;\nconst RECEIPT_INCLUSION_MS = 15_000;\nconst RECEIPT_TIMEOUT_SLACK = 1.5;\n\n/**\n * Auto-sizes the settle receipt timeout to a confirmation depth and the chain's\n * block time: `max(60_000, 15_000 + confirmations × blockTimeMs × 1.5)`. This is\n * the default {@link CreateSelfFacilitatorParams.receiptTimeoutMs} when the\n * operator does not pass one, so a deep-confirmation chain (Ethereum's `32` ×\n * ~12 s ≈ 10 min) does not time out at the flat 60 s floor, while shallow chains\n * (Polygon) keep the floor. Exposed so operators tuning `confirmations` per the\n * finality recipe (`docs/recipes/facilitator-finality-tuning.md`) can compute a\n * matching timeout.\n *\n * @example\n * ```ts\n * import { deriveReceiptTimeoutMs, ethereum } from \"kawasekit\";\n *\n * deriveReceiptTimeoutMs(ethereum, 32); // ≈ 591_000 ms\n * ```\n */\nexport function deriveReceiptTimeoutMs(chain: KawaseChain, confirmations: number): number {\n\tconst wallMs = RECEIPT_INCLUSION_MS + confirmations * chain.blockTimeMs * RECEIPT_TIMEOUT_SLACK;\n\treturn Math.max(RECEIPT_TIMEOUT_FLOOR_MS, Math.ceil(wallMs));\n}\n\n/**\n * Builds a facilitator that verifies and broadcasts exact-EVM EIP-3009\n * payments using a locally-held EOA private key (gas payer).\n *\n * Intended for self-hosted paywalls and testnet (Polygon Amoy) where the\n * Coinbase CDP facilitator is not guaranteed to support the chain.\n *\n * **Concurrent settle() calls**: under any meaningful load (e.g. an LLM\n * agent fan-out) you will issue multiple `transferWithAuthorization`\n * broadcasts from the same facilitator EOA in parallel. Without local nonce\n * sequencing those broadcasts race for the same on-chain nonce and only\n * one lands. Pass viem's `nonceManager` when constructing the facilitator\n * account to make this safe — see `@example` below.\n *\n * @example\n * ```ts\n * import { createPublicClient, createWalletClient, http } from \"viem\";\n * import { nonceManager, privateKeyToAccount } from \"viem/accounts\";\n * import { createSelfFacilitator, polygonAmoy } from \"kawasekit\";\n *\n * // `nonceManager` is REQUIRED whenever you expect concurrent settlements.\n * const account = privateKeyToAccount(\n * process.env.FACILITATOR_PK as `0x${string}`,\n * { nonceManager },\n * );\n * const transport = http(process.env.RPC_URL);\n * const facilitator = createSelfFacilitator({\n * network: \"testnet\", // must agree with polygonAmoy.isTestnet === true\n * walletClient: createWalletClient({ chain: polygonAmoy, transport, account }),\n * publicClient: createPublicClient({ chain: polygonAmoy, transport }),\n * });\n * ```\n */\nexport function createSelfFacilitator(params: CreateSelfFacilitatorParams): Facilitator {\n\tconst { walletClient, publicClient } = params;\n\tconst facilitatorChainId = walletClient.chain.id;\n\tif (!isSupportedChainId(facilitatorChainId)) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: walletClient.chain.id ${facilitatorChainId} is not a kawasekit-supported chain`,\n\t\t);\n\t}\n\tconst supportedChainId: SupportedChainId = facilitatorChainId;\n\tconst chain = getChain(supportedChainId);\n\tif (params.network === \"mainnet\" && chain.isTestnet) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: network=\"mainnet\" but walletClient.chain \"${chain.name}\" (chainId ${supportedChainId}) is a testnet`,\n\t\t);\n\t}\n\tif (params.network === \"testnet\" && !chain.isTestnet) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: network=\"testnet\" but walletClient.chain \"${chain.name}\" (chainId ${supportedChainId}) is a mainnet — refusing to broadcast with real funds`,\n\t\t);\n\t}\n\t// Chain-aware confirmation depth (threat 2.8 / §6.6), sourced from the chain\n\t// config (config-as-data): probabilistic chains need depth, deterministic-\n\t// finality chains (Avalanche Snowman / Kaia IBFT) need 1-2, Ethereum ~32.\n\t// Operators override via `params.confirmations`.\n\tconst confirmations = params.confirmations ?? chain.defaultConfirmations;\n\t// `receiptTimeoutMs` auto-sizes to the depth so a deep-confirmation chain does\n\t// not time out at the flat 60 s floor (e.g. Ethereum's 32×12 s). Shallow chains\n\t// (Polygon) keep the 60 s floor. Override to extend further.\n\tconst receiptTimeoutMs = params.receiptTimeoutMs ?? deriveReceiptTimeoutMs(chain, confirmations);\n\n\t// Threat 2.2 (concurrent settle nonce race) enforcement. The facilitator\n\t// will broadcast `transferWithAuthorization` calls in parallel under any\n\t// fan-out workload (LLM agent tool calls are the canonical example).\n\t// Without viem's nonceManager attached, every parallel `writeContract`\n\t// reads the same on-chain nonce and only one tx lands — settlements\n\t// silently dropped. Enforcing this at construction time means the\n\t// failure mode shows up at boot, not at the first parallel hit in\n\t// production. See `docs/THREAT_MODEL.md#22-concurrent-settle-nonce-race`.\n\tif (walletClient.account.nonceManager === undefined) {\n\t\tthrow new Error(\n\t\t\t'createSelfFacilitator: walletClient.account must be constructed with viem\\'s `nonceManager` to serialise nonces under concurrent settle(). Example:\\n import { nonceManager, privateKeyToAccount } from \"viem/accounts\";\\n const account = privateKeyToAccount(pk, { nonceManager });\\n const walletClient = createWalletClient({ chain, transport, account });',\n\t\t);\n\t}\n\n\tconst network = chainIdToX402Network(supportedChainId);\n\tconst hooks = params.hooks;\n\n\tfunction buildVerifyEvent(\n\t\treq: X402VerifyRequest,\n\t\tresponse: X402VerifyResponse,\n\t\tstartedAtMs: number,\n\t): VerifyEvent {\n\t\tconst durationMs = Date.now() - startedAtMs;\n\t\tconst eventNetwork = req.paymentRequirements.network;\n\t\tif (response.isValid && response.payer !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"verify\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tpayer: response.payer,\n\t\t\t\tamount: req.paymentRequirements.amount,\n\t\t\t};\n\t\t}\n\t\tif (response.isValid) {\n\t\t\t// verifyCore always sets payer on success, but the X402VerifyResponse\n\t\t\t// type permits it to be absent; downgrade to a synthetic failure\n\t\t\t// event so the discriminated union remains sound for adapters.\n\t\t\treturn {\n\t\t\t\tkind: \"verify\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tinvalidReason: \"unexpected_verify_error\",\n\t\t\t\tinvalidMessage: \"verify succeeded but payer was not surfaced\",\n\t\t\t};\n\t\t}\n\t\tconst base = {\n\t\t\tkind: \"verify\" as const,\n\t\t\tresult: \"failure\" as const,\n\t\t\tstartedAtMs,\n\t\t\tdurationMs,\n\t\t\tnetwork: eventNetwork,\n\t\t\tinvalidReason: response.invalidReason ?? \"unexpected_verify_error\",\n\t\t};\n\t\tif (response.payer !== undefined && response.invalidMessage !== undefined) {\n\t\t\treturn { ...base, payer: response.payer, invalidMessage: response.invalidMessage };\n\t\t}\n\t\tif (response.payer !== undefined) {\n\t\t\treturn { ...base, payer: response.payer };\n\t\t}\n\t\tif (response.invalidMessage !== undefined) {\n\t\t\treturn { ...base, invalidMessage: response.invalidMessage };\n\t\t}\n\t\treturn base;\n\t}\n\n\tfunction buildSettleEvent(\n\t\treq: X402SettleRequest,\n\t\tresponse: X402SettleResponse,\n\t\tstartedAtMs: number,\n\t): SettleEvent {\n\t\tconst durationMs = Date.now() - startedAtMs;\n\t\tconst eventNetwork = req.paymentRequirements.network;\n\t\tif (response.success && response.payer !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"settle\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tpayer: response.payer,\n\t\t\t\tamount: req.paymentRequirements.amount,\n\t\t\t\ttransaction: response.transaction as Hex,\n\t\t\t};\n\t\t}\n\t\tif (response.success) {\n\t\t\t// settleCore always sets payer on success; the spec response type\n\t\t\t// permits it to be absent so we downgrade to a synthetic failure\n\t\t\t// rather than emit a malformed event.\n\t\t\treturn {\n\t\t\t\tkind: \"settle\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\terrorReason: \"unexpected_settle_error\",\n\t\t\t\terrorMessage: \"settle succeeded but payer was not surfaced\",\n\t\t\t\ttransaction: response.transaction as Hex,\n\t\t\t};\n\t\t}\n\t\tconst base = {\n\t\t\tkind: \"settle\" as const,\n\t\t\tresult: \"failure\" as const,\n\t\t\tstartedAtMs,\n\t\t\tdurationMs,\n\t\t\tnetwork: eventNetwork,\n\t\t\terrorReason: response.errorReason ?? \"unexpected_settle_error\",\n\t\t};\n\t\tconst withPayer = response.payer !== undefined ? { ...base, payer: response.payer } : base;\n\t\tconst withMessage =\n\t\t\tresponse.errorMessage !== undefined\n\t\t\t\t? { ...withPayer, errorMessage: response.errorMessage }\n\t\t\t\t: withPayer;\n\t\tif (response.transaction !== \"\" && response.transaction !== undefined) {\n\t\t\treturn { ...withMessage, transaction: response.transaction as Hex };\n\t\t}\n\t\treturn withMessage;\n\t}\n\n\tasync function verifyCore(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\t// 1. Scheme / network gates\n\t\tif (req.paymentRequirements.scheme !== \"exact\") {\n\t\t\treturn failVerify(\"invalid_scheme\");\n\t\t}\n\t\tif (req.paymentPayload.accepted.scheme !== \"exact\") {\n\t\t\treturn failVerify(\"invalid_scheme\");\n\t\t}\n\t\tconst reqChainId = x402NetworkToChainId(req.paymentRequirements.network);\n\t\tif (reqChainId !== supportedChainId) {\n\t\t\treturn failVerify(\"invalid_network\");\n\t\t}\n\t\tif (req.paymentPayload.accepted.network !== req.paymentRequirements.network) {\n\t\t\treturn failVerify(\"invalid_network\");\n\t\t}\n\n\t\t// 2. Narrow scheme-specific payload\n\t\tconst exact = narrowExactEvmPayload(req.paymentPayload.payload);\n\t\tif (exact === null) {\n\t\t\treturn failVerify(\"invalid_payload\");\n\t\t}\n\t\tconst auth = exact.authorization;\n\n\t\t// 3. Parameter matching against requirements\n\t\tif (auth.value !== req.paymentRequirements.amount) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_value_mismatch\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (getAddress(auth.to) !== getAddress(req.paymentRequirements.payTo)) {\n\t\t\treturn failVerify(\"invalid_exact_evm_payload_recipient_mismatch\", undefined, auth.from);\n\t\t}\n\n\t\t// 4. Time window\n\t\tconst now = BigInt(Math.floor(Date.now() / 1000));\n\t\tconst validAfter = BigInt(auth.validAfter);\n\t\tconst validBefore = BigInt(auth.validBefore);\n\t\tif (now < validAfter) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_valid_after\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (now >= validBefore) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_valid_before\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Signature recovery\n\t\tlet recovered: Address;\n\t\ttry {\n\t\t\tconst domain = resolveDomain(req.paymentRequirements);\n\t\t\trecovered = await recoverTypedDataAddress({\n\t\t\t\tdomain: {\n\t\t\t\t\tname: domain.name,\n\t\t\t\t\tversion: domain.version,\n\t\t\t\t\tchainId: reqChainId,\n\t\t\t\t\tverifyingContract: req.paymentRequirements.asset,\n\t\t\t\t},\n\t\t\t\ttypes: TRANSFER_AUTHORIZATION_TYPES,\n\t\t\t\tprimaryType: \"TransferWithAuthorization\",\n\t\t\t\tmessage: {\n\t\t\t\t\tfrom: auth.from,\n\t\t\t\t\tto: auth.to,\n\t\t\t\t\tvalue: BigInt(auth.value),\n\t\t\t\t\tvalidAfter,\n\t\t\t\t\tvalidBefore,\n\t\t\t\t\tnonce: auth.nonce,\n\t\t\t\t},\n\t\t\t\tsignature: exact.signature,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn failVerify(\n\t\t\t\t\"unexpected_verify_error\",\n\t\t\t\tcause instanceof Error ? cause.message : String(cause),\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (getAddress(recovered) !== getAddress(auth.from)) {\n\t\t\treturn failVerify(\"invalid_exact_evm_payload_signature\", undefined, auth.from);\n\t\t}\n\n\t\t// 6. On-chain reads: balance + nonce-not-used\n\t\ttry {\n\t\t\tconst [balance, used] = await Promise.all([\n\t\t\t\tpublicClient.readContract({\n\t\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\t\tabi: jpycAbi,\n\t\t\t\t\tfunctionName: \"balanceOf\",\n\t\t\t\t\targs: [auth.from],\n\t\t\t\t}),\n\t\t\t\tpublicClient.readContract({\n\t\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\t\tabi: jpycAbi,\n\t\t\t\t\tfunctionName: \"authorizationState\",\n\t\t\t\t\targs: [auth.from, auth.nonce],\n\t\t\t\t}),\n\t\t\t]);\n\t\t\tif (used) {\n\t\t\t\treturn failVerify(\"invalid_payload\", \"authorization nonce already used\", auth.from);\n\t\t\t}\n\t\t\tif ((balance as bigint) < BigInt(auth.value)) {\n\t\t\t\treturn failVerify(\"insufficient_funds\", undefined, auth.from);\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\treturn failVerify(\n\t\t\t\t\"unexpected_verify_error\",\n\t\t\t\tcause instanceof Error ? cause.message : String(cause),\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\n\t\treturn { isValid: true, payer: auth.from };\n\t}\n\n\tasync function settleCore(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\t// Re-verify before broadcasting. The wrapped `verify` is used so the\n\t\t// internal re-verify also emits onVerify; operators can dedupe in their\n\t\t// hook if they don't want the extra event.\n\t\tconst verifyResult = await verify(req);\n\t\tif (!verifyResult.isValid) {\n\t\t\treturn failSettle(\n\t\t\t\treq.paymentRequirements.network,\n\t\t\t\t(verifyResult.invalidReason as X402FacilitatorErrorCode) ?? \"unexpected_settle_error\",\n\t\t\t\t{\n\t\t\t\t\t...(verifyResult.invalidMessage !== undefined\n\t\t\t\t\t\t? { message: verifyResult.invalidMessage }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(verifyResult.payer !== undefined ? { payer: verifyResult.payer } : {}),\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst exact = narrowExactEvmPayload(req.paymentPayload.payload);\n\t\tif (exact === null) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"invalid_payload\");\n\t\t}\n\t\tconst auth = exact.authorization;\n\t\tconst parsed = parseSignature(exact.signature);\n\t\tconst v = parsed.v !== undefined ? Number(parsed.v) : (parsed.yParity ?? 0) + 27;\n\n\t\tlet txHash: Hex;\n\t\ttry {\n\t\t\ttxHash = await walletClient.writeContract({\n\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\tabi: jpycAbi,\n\t\t\t\tfunctionName: \"transferWithAuthorization\",\n\t\t\t\targs: [\n\t\t\t\t\tauth.from,\n\t\t\t\t\tauth.to,\n\t\t\t\t\tBigInt(auth.value),\n\t\t\t\t\tBigInt(auth.validAfter),\n\t\t\t\t\tBigInt(auth.validBefore),\n\t\t\t\t\tauth.nonce,\n\t\t\t\t\tv,\n\t\t\t\t\tparsed.r,\n\t\t\t\t\tparsed.s,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"unexpected_settle_error\", {\n\t\t\t\tmessage: cause instanceof Error ? cause.message : String(cause),\n\t\t\t\tpayer: auth.from,\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst receipt = await publicClient.waitForTransactionReceipt({\n\t\t\t\thash: txHash,\n\t\t\t\ttimeout: receiptTimeoutMs,\n\t\t\t\tconfirmations,\n\t\t\t});\n\t\t\tif (receipt.status !== \"success\") {\n\t\t\t\treturn failSettle(req.paymentRequirements.network, \"invalid_transaction_state\", {\n\t\t\t\t\ttransaction: txHash,\n\t\t\t\t\tpayer: auth.from,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"unexpected_settle_error\", {\n\t\t\t\tmessage: cause instanceof Error ? cause.message : String(cause),\n\t\t\t\tpayer: auth.from,\n\t\t\t\ttransaction: txHash,\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\ttransaction: txHash,\n\t\t\tnetwork: req.paymentRequirements.network,\n\t\t\tpayer: auth.from,\n\t\t\tamount: auth.value,\n\t\t};\n\t}\n\n\tasync function verify(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\tconst startedAtMs = Date.now();\n\t\tconst result = await verifyCore(req);\n\t\tinvokeHookSafely(hooks?.onVerify, buildVerifyEvent(req, result, startedAtMs));\n\t\treturn result;\n\t}\n\n\tasync function settle(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\tconst startedAtMs = Date.now();\n\t\tconst result = await settleCore(req);\n\t\tinvokeHookSafely(hooks?.onSettle, buildSettleEvent(req, result, startedAtMs));\n\t\treturn result;\n\t}\n\n\tasync function supportedInternal(): Promise<X402SupportedResponse> {\n\t\tconst kind: X402SupportedKind = {\n\t\t\tx402Version: X402_VERSION,\n\t\t\tscheme: \"exact\",\n\t\t\tnetwork,\n\t\t};\n\t\treturn {\n\t\t\tkinds: [kind],\n\t\t\textensions: [],\n\t\t\tsigners: { \"eip155:*\": [walletClient.account.address] },\n\t\t};\n\t}\n\n\treturn {\n\t\tverify,\n\t\tsettle,\n\t\tsupported: supportedInternal,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// HTTP-proxied facilitator (Coinbase CDP and any other x402 v2-compliant\n// facilitator endpoint)\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link createHttpFacilitator}. */\nexport interface CreateHttpFacilitatorParams {\n\t/**\n\t * Base URL of the facilitator service (Coinbase CDP, your own host, any\n\t * x402 v2-compliant endpoint). Endpoints `/verify`, `/settle`, `/supported`\n\t * are POST / POST / GET respectively relative to this URL. Trailing slash\n\t * is stripped.\n\t */\n\treadonly baseUrl: string;\n\t/**\n\t * Optional callback invoked per request that returns headers to merge\n\t * into the outbound request (typically `Authorization`). Receives the\n\t * endpoint name so the caller can compute distinct signatures per route.\n\t */\n\treadonly getAuthHeaders?: (\n\t\tendpoint: \"verify\" | \"settle\" | \"supported\",\n\t) => Promise<Record<string, string>> | Record<string, string>;\n\t/**\n\t * Override the global `fetch` (e.g. for in-process testing or to inject\n\t * an `undici` Agent in Node).\n\t */\n\treadonly fetch?: typeof fetch;\n}\n\n/**\n * Builds a facilitator that proxies all RPC over HTTP to a remote endpoint,\n * matching the request / response shapes of x402 v2 spec §7.\n *\n * Works with any x402 v2-compliant facilitator — Coinbase CDP, your own\n * self-hosted facilitator behind nginx, a regional mirror — as long as it\n * exposes `/verify`, `/settle`, and `/supported` per the spec.\n *\n * If your target facilitator doesn't support the chain you need, fall back\n * to {@link createSelfFacilitator} (in-process viem broadcaster).\n *\n * @example\n * ```ts\n * import { createHttpFacilitator } from \"kawasekit\";\n *\n * const facilitator = createHttpFacilitator({\n * baseUrl: process.env.X402_FACILITATOR_URL!, // e.g. Coinbase CDP endpoint\n * getAuthHeaders: () => ({ Authorization: `Bearer ${apiKey}` }),\n * });\n * ```\n */\nexport function createHttpFacilitator(params: CreateHttpFacilitatorParams): Facilitator {\n\tconst baseUrl = params.baseUrl.replace(/\\/$/, \"\");\n\tconst fetchImpl = params.fetch ?? fetch;\n\tconst getAuthHeaders = params.getAuthHeaders;\n\n\tasync function post<TResponse>(endpoint: \"verify\" | \"settle\", body: unknown): Promise<TResponse> {\n\t\tconst headers: Record<string, string> = { \"content-type\": \"application/json\" };\n\t\tif (getAuthHeaders) {\n\t\t\tObject.assign(headers, await getAuthHeaders(endpoint));\n\t\t}\n\t\tconst response = await fetchImpl(`${baseUrl}/${endpoint}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\t\tconst text = await response.text();\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = text === \"\" ? null : JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator ${endpoint} returned non-JSON (status ${response.status}): ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator ${endpoint} failed (status ${response.status}): ${JSON.stringify(parsed).slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\treturn parsed as TResponse;\n\t}\n\n\tasync function verifyInternal(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\treturn post<X402VerifyResponse>(\"verify\", {\n\t\t\tx402Version: req.x402Version,\n\t\t\tpaymentPayload: req.paymentPayload,\n\t\t\tpaymentRequirements: req.paymentRequirements,\n\t\t});\n\t}\n\n\tasync function settleInternal(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\treturn post<X402SettleResponse>(\"settle\", {\n\t\t\tx402Version: req.x402Version,\n\t\t\tpaymentPayload: req.paymentPayload,\n\t\t\tpaymentRequirements: req.paymentRequirements,\n\t\t});\n\t}\n\n\tasync function supportedInternal(): Promise<X402SupportedResponse> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (getAuthHeaders) {\n\t\t\tObject.assign(headers, await getAuthHeaders(\"supported\"));\n\t\t}\n\t\tconst response = await fetchImpl(`${baseUrl}/supported`, { method: \"GET\", headers });\n\t\tconst text = await response.text();\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = text === \"\" ? null : JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator supported returned non-JSON (status ${response.status}): ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator supported failed (status ${response.status}): ${JSON.stringify(parsed).slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\treturn parsed as X402SupportedResponse;\n\t}\n\n\treturn {\n\t\tverify: verifyInternal,\n\t\tsettle: settleInternal,\n\t\tsupported: supportedInternal,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases (M3-era names)\n//\n// The HTTP-proxied facilitator used to be called `createCoinbaseFacilitator`\n// because the only x402 v2-compliant endpoint we tested against at the time\n// was Coinbase CDP. The function was never Coinbase-specific — it speaks the\n// raw x402 v2 HTTP shape — and the rename to `createHttpFacilitator` lands in\n// v0.1.0-alpha to make that obvious before the npm publish freezes the API.\n//\n// The aliases below preserve M3-era call sites for the v0.1.x line. Calling\n// `createCoinbaseFacilitator` emits a one-shot Node DeprecationWarning. The\n// aliases will be removed in v0.2.0.\n// ---------------------------------------------------------------------------\n\n/**\n * @deprecated Renamed to {@link CreateHttpFacilitatorParams} in v0.1.0-alpha.\n * The HTTP facilitator works with any x402 v2-compliant endpoint, not only\n * Coinbase CDP. This alias will be removed in v0.2.0.\n */\nexport type CreateCoinbaseFacilitatorParams = CreateHttpFacilitatorParams;\n\nlet warnedCreateCoinbaseFacilitator = false;\n\n/**\n * @deprecated Renamed to {@link createHttpFacilitator} in v0.1.0-alpha.\n * This alias delegates to the new function and emits one\n * `DeprecationWarning` per process on first call. It will be removed in\n * v0.2.0.\n */\nexport function createCoinbaseFacilitator(params: CreateHttpFacilitatorParams): Facilitator {\n\tif (!warnedCreateCoinbaseFacilitator) {\n\t\twarnedCreateCoinbaseFacilitator = true;\n\t\tprocess.emitWarning(\n\t\t\t\"createCoinbaseFacilitator() is deprecated and will be removed in kawasekit v0.2.0. Use createHttpFacilitator() instead — the function works with any x402 v2-compliant HTTP endpoint, not only Coinbase CDP.\",\n\t\t\t{ type: \"DeprecationWarning\", code: \"KAWASEKIT_DEP_001\" },\n\t\t);\n\t}\n\treturn createHttpFacilitator(params);\n}\n","/**\n * `wrapFetch()` — turn any WHATWG `fetch` implementation into an x402-aware\n * client.\n *\n * The returned function makes a first request as usual. If the server replies\n * with `402 Payment Required`, the wrapper decodes the `PAYMENT-REQUIRED`\n * header (or response body as a fallback), picks one entry from `accepts`,\n * signs it with the configured {@link X402PaymentSigner}, and retries the\n * same request with a `PAYMENT-SIGNATURE` header. Non-402 responses are\n * returned unchanged.\n *\n * The wrapper does **not** poll or back off — the latency budget (Polygon Amoy\n * bundler inclusion can take ~60 s) lives entirely on the server side, which\n * holds the connection open while it broadcasts and waits for the receipt.\n * If the second attempt still fails the wrapper returns that response so the\n * caller can decide how to recover.\n *\n * Streaming request bodies are not retry-safe; the wrapper passes `init.body`\n * through verbatim, so callers who need retry must pass a buffered body\n * (string / Uint8Array / ArrayBuffer / FormData).\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport {\n\ttype ClientPaymentEvent,\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n} from \"../observability/hooks\";\nimport type { X402PaymentSigner } from \"./client\";\nimport {\n\tdecodePaymentRequiredHeader,\n\tdecodePaymentResponseHeader,\n\tencodePaymentSignatureHeader,\n\tX402_HEADER_IDEMPOTENCY_KEY,\n\tX402_HEADER_PAYMENT_REQUIRED,\n\tX402_HEADER_PAYMENT_RESPONSE,\n\tX402_HEADER_PAYMENT_SIGNATURE,\n} from \"./encoding\";\nimport type { X402PaymentRequiredResponse, X402PaymentRequirements } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Function shape matching the WHATWG `fetch` global. */\nexport type X402Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/** Parameters for {@link wrapFetch}. */\nexport interface WrapFetchParams {\n\t/**\n\t * The signer used to produce {@link X402PaymentPayload}s when the server\n\t * returns 402. Bound to one EOA.\n\t */\n\treadonly signer: X402PaymentSigner;\n\t/**\n\t * Optional underlying fetch implementation. Defaults to `globalThis.fetch`.\n\t */\n\treadonly fetch?: X402Fetch;\n\t/**\n\t * Optional policy for choosing one entry from the server's `accepts` list.\n\t * Defaults to the first entry. Return `null` to abort — the original 402\n\t * response is returned without retry.\n\t */\n\treadonly selectRequirements?: (\n\t\taccepts: readonly X402PaymentRequirements[],\n\t\tresponse: Response,\n\t) => X402PaymentRequirements | null;\n\t/**\n\t * Required gate invoked just before the retry request goes out. Receives\n\t * the chosen requirements and the parsed 402 body so the caller can log\n\t * spending, prompt the user, or enforce a budget.\n\t *\n\t * Returning `false` aborts the retry — the original 402 is returned.\n\t * Returning `true` (or `undefined`) proceeds with the signed retry.\n\t *\n\t * This callback is **required** at the type level: a 402 retry transfers\n\t * real funds, and kawasekit refuses to default to \"always pay\" silently.\n\t * If your caller already enforces a budget elsewhere, return `true`\n\t * explicitly — the empty function `() => true` is a deliberate opt-in.\n\t *\n\t * See `docs/THREAT_MODEL.md` Threat 1.8 / §6.1.\n\t */\n\treadonly onPayment: (\n\t\trequirements: X402PaymentRequirements,\n\t\tpaymentRequired: X402PaymentRequiredResponse,\n\t) => boolean | undefined | Promise<boolean | undefined>;\n\t/**\n\t * Optional observability callbacks. {@link wrapFetch} emits an\n\t * `onClientPayment` event for every paywall round-trip — `success` when the\n\t * retry returns 2xx with a PAYMENT-RESPONSE header, `failure` otherwise\n\t * (including `onPayment` declining the retry).\n\t */\n\treadonly hooks?: ObservabilityHooks;\n\t/**\n\t * Optional mapper from a request to a reasoning-step idempotency key (M5-1).\n\t * When it returns a key, the key is (a) sent as the `Idempotency-Key` request\n\t * header so the server can deduplicate, and (b) forwarded into the signer so\n\t * the EIP-3009 nonce is derived deterministically (on-chain backstop). Return\n\t * `undefined` to fall back to today's random-nonce behaviour. Build keys with\n\t * `createIdempotencyKeyBuilder` from `kawasekit/idempotency` at the agent\n\t * harness's tool-execution boundary, where the reasoning-step intent is visible.\n\t */\n\treadonly idempotencyKeyFor?: (\n\t\tinput: string | URL | Request,\n\t\trequirements: X402PaymentRequirements,\n\t\tpaymentRequired: X402PaymentRequiredResponse,\n\t) => string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function readPaymentRequired(\n\tresponse: Response,\n): Promise<X402PaymentRequiredResponse | null> {\n\tconst headerValue = response.headers.get(X402_HEADER_PAYMENT_REQUIRED);\n\tif (headerValue !== null && headerValue !== \"\") {\n\t\ttry {\n\t\t\treturn decodePaymentRequiredHeader(headerValue);\n\t\t} catch {\n\t\t\t// Fall through to body parse — the header was malformed but the\n\t\t\t// body might still be intact (or vice versa).\n\t\t}\n\t}\n\ttry {\n\t\tconst body = await response.clone().text();\n\t\tif (body === \"\") return null;\n\t\tconst parsed = JSON.parse(body) as unknown;\n\t\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn parsed as X402PaymentRequiredResponse;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction defaultSelectRequirements(\n\taccepts: readonly X402PaymentRequirements[],\n): X402PaymentRequirements | null {\n\treturn accepts[0] ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Returns an x402-aware `fetch` that pays for `402` responses on the caller's\n * behalf using the provided signer.\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { createX402PaymentSigner, wrapFetch } from \"kawasekit\";\n *\n * const signer = createX402PaymentSigner({\n * account: privateKeyToAccount(process.env.PAYER_PK as `0x${string}`),\n * });\n *\n * let spent = 0n;\n * const MAX_SPEND = 100_000n; // 100 JPYC (6 decimals)\n * const fetch402 = wrapFetch({\n * signer,\n * onPayment: (req) => {\n * const next = spent + BigInt(req.amount);\n * if (next > MAX_SPEND) return false; // budget exhausted\n * spent = next;\n * return true;\n * },\n * });\n *\n * const res = await fetch402(\"https://api.example.com/weather?city=Tokyo\");\n * console.log(await res.json());\n * ```\n */\nexport function wrapFetch(params: WrapFetchParams): X402Fetch {\n\tconst baseFetch: X402Fetch = params.fetch ?? ((input, init) => fetch(input, init));\n\tconst selectRequirements = params.selectRequirements ?? defaultSelectRequirements;\n\tconst onPayment = params.onPayment;\n\tconst hooks = params.hooks;\n\n\treturn async function x402Fetch(input, init) {\n\t\tconst startedAtMs = Date.now();\n\t\tconst requestUrl =\n\t\t\ttypeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\n\t\tconst emitFailure = (reason: string, httpStatus: number | undefined): void => {\n\t\t\tconst event: ClientPaymentEvent = {\n\t\t\t\tkind: \"client_payment\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl,\n\t\t\t\treason,\n\t\t\t\t...(httpStatus !== undefined ? { httpStatus } : {}),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onClientPayment, event);\n\t\t};\n\n\t\tconst initialResponse = await baseFetch(input, init);\n\t\tif (initialResponse.status !== 402) {\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst paymentRequired = await readPaymentRequired(initialResponse);\n\t\tif (paymentRequired === null || paymentRequired.accepts.length === 0) {\n\t\t\temitFailure(\"no_acceptable_requirement\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst chosen = selectRequirements(paymentRequired.accepts, initialResponse);\n\t\tif (chosen === null) {\n\t\t\temitFailure(\"no_acceptable_requirement\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst proceed = await onPayment(chosen, paymentRequired);\n\t\tif (proceed === false) {\n\t\t\temitFailure(\"onPayment_declined\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst idempotencyKey = params.idempotencyKeyFor?.(input, chosen, paymentRequired);\n\n\t\tconst paymentPayload = await params.signer.sign({\n\t\t\tpaymentRequirements: chosen,\n\t\t\t...(paymentRequired.resource ? { resource: paymentRequired.resource } : {}),\n\t\t\t...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n\t\t});\n\n\t\tconst retryHeaders = new Headers(init?.headers);\n\t\tretryHeaders.set(X402_HEADER_PAYMENT_SIGNATURE, encodePaymentSignatureHeader(paymentPayload));\n\t\tif (idempotencyKey !== undefined) {\n\t\t\tretryHeaders.set(X402_HEADER_IDEMPOTENCY_KEY, idempotencyKey);\n\t\t}\n\n\t\tconst retryResponse = await baseFetch(input, { ...init, headers: retryHeaders });\n\n\t\tif (retryResponse.status >= 200 && retryResponse.status < 300) {\n\t\t\tconst settlementHeader = retryResponse.headers.get(X402_HEADER_PAYMENT_RESPONSE);\n\t\t\tlet transaction: Hex | undefined;\n\t\t\tif (settlementHeader !== null && settlementHeader !== \"\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst settlement = decodePaymentResponseHeader(settlementHeader);\n\t\t\t\t\tif (settlement.transaction !== \"\") {\n\t\t\t\t\t\ttransaction = settlement.transaction as Hex;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// PAYMENT-RESPONSE header malformed — the retry still\n\t\t\t\t\t// succeeded so we treat that as a (degraded) success event.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst successEvent: ClientPaymentEvent = {\n\t\t\t\tkind: \"client_payment\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl,\n\t\t\t\tpayer: params.signer.address,\n\t\t\t\tamount: chosen.amount,\n\t\t\t\tnetwork: chosen.network,\n\t\t\t\t...(transaction !== undefined ? { transaction } : {}),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onClientPayment, successEvent);\n\t\t} else {\n\t\t\temitFailure(\n\t\t\t\tretryResponse.status === 402 ? \"settle_rejected\" : \"http_error\",\n\t\t\t\tretryResponse.status,\n\t\t\t);\n\t\t}\n\n\t\treturn retryResponse;\n\t};\n}\n","/**\n * Server-side builders for x402 v2 `PAYMENT-REQUIRED` payloads.\n *\n * `buildPaymentRequirements()` produces one accepted-payment entry; servers\n * call it once per (chain × asset) they want to advertise. `buildPaymentRequiredResponse()`\n * wraps a list of those entries into the full body the server returns alongside\n * an HTTP 402 status (typically also encoded into the `PAYMENT-REQUIRED`\n * header — see `src/x402/encoding.ts`).\n *\n * These factories live on the **server** side. The mirror-image client-side\n * factory is `createX402PaymentSigner()` in `client.ts`.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { JPYC_V2_ADDRESS } from \"../tokens/jpyc\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentRequiredResponse,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n} from \"./types\";\nimport { chainIdToX402Network, X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default value for `maxTimeoutSeconds` when {@link BuildPaymentRequirementsParams.maxTimeoutSeconds}\n * is not supplied. Matches the x402 spec example for short-lived authorizations.\n *\n * Increase to 300 (the client-side default) when targeting Polygon Amoy in the\n * M3 demo — bundler inclusion latency can spike above 60 s on testnet.\n */\nexport const X402_DEFAULT_MAX_TIMEOUT_SECONDS = 60;\n\n/** Default `extra` payload kawasekit injects when the asset is JPYC. */\nconst JPYC_EXACT_EVM_EXTRA = {\n\tassetTransferMethod: \"eip3009\",\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link buildPaymentRequirements}. */\nexport interface BuildPaymentRequirementsParams {\n\t/** Numeric chain ID; converted to the CAIP-2 `eip155:{chainId}` form. */\n\treadonly chainId: SupportedChainId;\n\t/** ERC-20 contract address of the token to be transferred. */\n\treadonly asset: Address;\n\t/** Recipient wallet address. */\n\treadonly payTo: Address;\n\t/** Atomic-unit amount. Accepts `bigint` (preferred) or a decimal `string`. */\n\treadonly amount: bigint | string;\n\t/**\n\t * Optional. Defaults to {@link X402_DEFAULT_MAX_TIMEOUT_SECONDS}.\n\t *\n\t * The maximum wall-clock time the client may take to produce a signed\n\t * payload after receiving this 402 response.\n\t */\n\treadonly maxTimeoutSeconds?: number;\n\t/**\n\t * Optional explicit `extra` payload. When omitted and `asset` is JPYC,\n\t * kawasekit injects a default `{ assetTransferMethod: \"eip3009\", name: \"JPY Coin\", version: \"1\" }`.\n\t * For non-JPYC assets `extra` is required (the client needs at least\n\t * `name` / `version` to reconstruct the EIP-712 domain).\n\t */\n\treadonly extra?: Record<string, unknown>;\n}\n\n/** Parameters for {@link buildPaymentRequiredResponse}. */\nexport interface BuildPaymentRequiredResponseParams {\n\t/** The protected resource the client is being asked to pay for. */\n\treadonly resource: X402ResourceInfo;\n\t/** One or more acceptable payment methods. */\n\treadonly accepts: readonly X402PaymentRequirements[];\n\t/** Optional human-readable reason for the 402, echoed in the response body. */\n\treadonly error?: string;\n\t/** Optional protocol extensions (advanced; rarely set). */\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst UINT256_DECIMAL = /^(0|[1-9][0-9]*)$/;\n\nfunction coerceAmount(amount: bigint | string): string {\n\tif (typeof amount === \"bigint\") {\n\t\tif (amount <= 0n) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` must be positive, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\tif (amount > UINT256_MAX) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\treturn amount.toString();\n\t}\n\tif (!UINT256_DECIMAL.test(amount)) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` must be a non-negative decimal string, got ${JSON.stringify(amount)}`,\n\t\t);\n\t}\n\tconst parsed = BigInt(amount);\n\tif (parsed === 0n) {\n\t\tthrow new X402InvalidPayloadError(\"PaymentRequirements\", \"`amount` must be positive\");\n\t}\n\tif (parsed > UINT256_MAX) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t);\n\t}\n\treturn amount;\n}\n\nfunction assertAddress(value: string, field: string): Address {\n\tif (!isAddress(value, { strict: false })) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` is not a valid address: ${value}`,\n\t\t);\n\t}\n\treturn value as Address;\n}\n\nfunction resolveExtra(\n\tasset: Address,\n\texplicit: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\tif (getAddress(asset) === getAddress(JPYC_V2_ADDRESS)) {\n\t\treturn { ...JPYC_EXACT_EVM_EXTRA };\n\t}\n\tthrow new X402InvalidPayloadError(\n\t\t\"PaymentRequirements\",\n\t\t\"`extra` is required for non-JPYC assets (clients need at least `name` and `version` for EIP-712 domain reconstruction)\",\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds one {@link X402PaymentRequirements} entry suitable for the `accepts`\n * array of a `PAYMENT-REQUIRED` response.\n *\n * @example Single-chain JPYC (defaults extra automatically)\n * ```ts\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const requirements = buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * });\n * ```\n */\nexport function buildPaymentRequirements(\n\tparams: BuildPaymentRequirementsParams,\n): X402PaymentRequirements {\n\tconst asset = assertAddress(params.asset, \"asset\");\n\tconst payTo = assertAddress(params.payTo, \"payTo\");\n\tconst amount = coerceAmount(params.amount);\n\tconst maxTimeoutSeconds = params.maxTimeoutSeconds ?? X402_DEFAULT_MAX_TIMEOUT_SECONDS;\n\tif (maxTimeoutSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`maxTimeoutSeconds\\` must be positive, got ${maxTimeoutSeconds}`,\n\t\t);\n\t}\n\tconst extra = resolveExtra(asset, params.extra);\n\n\treturn {\n\t\tscheme: \"exact\",\n\t\tnetwork: chainIdToX402Network(params.chainId),\n\t\tamount,\n\t\tasset,\n\t\tpayTo,\n\t\tmaxTimeoutSeconds,\n\t\textra,\n\t};\n}\n\n/**\n * Builds the full {@link X402PaymentRequiredResponse} body the server returns\n * alongside HTTP 402.\n *\n * @example\n * ```ts\n * import {\n * buildPaymentRequiredResponse,\n * buildPaymentRequirements,\n * encodePaymentRequiredHeader,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const response = buildPaymentRequiredResponse({\n * resource: { url: \"https://api.example.com/weather\", description: \"Real-time weather\" },\n * accepts: [\n * buildPaymentRequirements({ chainId: polygonAmoy.id, ... }),\n * ],\n * error: \"PAYMENT-SIGNATURE header is required\",\n * });\n *\n * res.statusCode = 402;\n * res.setHeader(\"PAYMENT-REQUIRED\", encodePaymentRequiredHeader(response));\n * res.setHeader(\"content-type\", \"application/json\");\n * res.end(JSON.stringify(response));\n * ```\n */\nexport function buildPaymentRequiredResponse(\n\tparams: BuildPaymentRequiredResponseParams,\n): X402PaymentRequiredResponse {\n\tif (params.accepts.length === 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequired\",\n\t\t\t\"`accepts` must contain at least one PaymentRequirements entry\",\n\t\t);\n\t}\n\t// Object literal is built conditionally so optional fields are *absent* (not\n\t// `undefined`) when not provided — required by `exactOptionalPropertyTypes`.\n\tconst base: Pick<X402PaymentRequiredResponse, \"x402Version\" | \"resource\" | \"accepts\"> = {\n\t\tx402Version: X402_VERSION,\n\t\tresource: params.resource,\n\t\taccepts: params.accepts,\n\t};\n\tif (params.error !== undefined && params.extensions !== undefined) {\n\t\treturn { ...base, error: params.error, extensions: params.extensions };\n\t}\n\tif (params.error !== undefined) {\n\t\treturn { ...base, error: params.error };\n\t}\n\tif (params.extensions !== undefined) {\n\t\treturn { ...base, extensions: params.extensions };\n\t}\n\treturn base;\n}\n","/**\n * Typed errors for the reasoning-step idempotency layer (M5-1).\n *\n * Mirrors the kawasekit error convention: plain `extends Error`, a stable\n * `this.name`, public `readonly` discriminant fields, and an optional\n * `{ cause }` options bag forwarded to `super`. Consumers discriminate via\n * `instanceof`, never a string `.code`.\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown at construction / configuration time when an idempotency primitive is\n * wired up incorrectly (e.g. a non-positive LRU cap, an empty key). This is an\n * integrator bug, not an adversarial input — analogous to\n * {@link X402InvalidConfigError}.\n *\n * @example\n * ```ts\n * import { IdempotencyConfigError } from \"kawasekit/idempotency\";\n *\n * try {\n * createInMemoryIdempotencyStore({ maxEntries: 0 });\n * } catch (err) {\n * if (err instanceof IdempotencyConfigError) {\n * console.error(err.field, err.reason);\n * }\n * }\n * ```\n */\nexport class IdempotencyConfigError extends Error {\n\treadonly field: string;\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid idempotency config (${field}): ${reason}`, options);\n\t\tthis.name = \"IdempotencyConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when {@link parseIdempotencyRecord} cannot decode a persisted record\n * (malformed JSON, missing/!mistyped field). Carries a machine-readable\n * `reason` and the underlying `cause` when available.\n *\n * @example\n * ```ts\n * import { IdempotencyRecordParseError, parseIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * try {\n * parseIdempotencyRecord(rawFromRedis);\n * } catch (err) {\n * if (err instanceof IdempotencyRecordParseError) {\n * // drop the corrupt entry; treat the request as fresh\n * }\n * }\n * ```\n */\nexport class IdempotencyRecordParseError extends Error {\n\treadonly reason: string;\n\n\tconstructor(reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Failed to parse idempotency record: ${reason}`, options);\n\t\tthis.name = \"IdempotencyRecordParseError\";\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when a persisted record's `kawasekitVersion` does not match the\n * version this build understands. Distinct from a parse error so a forward /\n * backward migration can be detected and handled explicitly (the version is a\n * string so future variants like `\"2\"` do not break parser ordering).\n *\n * @example\n * ```ts\n * import { IdempotencyRecordVersionError } from \"kawasekit/idempotency\";\n * // expected \"1\", received \"2\" → caller decides to ignore or migrate\n * ```\n */\nexport class IdempotencyRecordVersionError extends Error {\n\treadonly expected: string;\n\treadonly received: unknown;\n\n\tconstructor(expected: string, received: unknown) {\n\t\tsuper(\n\t\t\t`Unsupported idempotency record version: expected ${expected}, received ${JSON.stringify(received)}`,\n\t\t);\n\t\tthis.name = \"IdempotencyRecordVersionError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n","/**\n * The persisted idempotency record + its (de)serialization (M5-1).\n *\n * Follows the `session/envelope` convention: a bigint/`Address`-friendly PUBLIC\n * type and a SEPARATE private `…Json` wire shape with bigints as decimal\n * strings, validated on parse via small `assert*` helpers, output as plain\n * UTF-8 JSON. The string `kawasekitVersion` + dedicated `…VersionError` keep a\n * future schema bump a clean, typed migration.\n *\n * A record is dedup *metadata*, never funds — it stores enough to **replay** a\n * prior settlement (the on-chain `txHash` and an optional response snapshot),\n * not to move value.\n *\n * @packageDocumentation\n */\n\nimport { type Address, getAddress, type Hex } from \"viem\";\nimport { isX402Network, type X402Network } from \"../x402/types\";\nimport { IdempotencyRecordParseError, IdempotencyRecordVersionError } from \"./errors\";\n\n/** Current idempotency-record schema version. String, so `\"2\"`, `\"1-jwe\"`, … never break parser ordering. */\nexport const KAWASEKIT_IDEMPOTENCY_RECORD_VERSION = \"1\" as const;\n\n/** The schema version literal type. */\nexport type KawasekitIdempotencyRecordVersion = typeof KAWASEKIT_IDEMPOTENCY_RECORD_VERSION;\n\n/**\n * A byte-faithful, credential-safe snapshot of the paid response, so a\n * duplicate request can be replayed without re-running settlement or the inner\n * handler. Headers are an allowlist captured by the server (hop-by-hop /\n * `Set-Cookie` / auth headers are stripped); the body is base64.\n */\nexport interface IdempotencyResponseSnapshot {\n\treadonly status: number;\n\treadonly headers: ReadonlyArray<readonly [string, string]>;\n\treadonly bodyBase64: string;\n}\n\n/**\n * A completed reasoning-step settlement, keyed by the idempotency key. Retained\n * until `expiresAt` (anchored to the authorization `validBefore`, never beyond).\n */\nexport interface IdempotencyRecord {\n\treadonly kawasekitVersion: KawasekitIdempotencyRecordVersion;\n\t/** The idempotency key this record is stored under. */\n\treadonly key: string;\n\t/** The on-chain settlement tx hash (replayed in the `PAYMENT-RESPONSE` header). */\n\treadonly txHash: Hex;\n\t/** The payer EOA recovered at settlement. */\n\treadonly payer: Address;\n\t/** Settled amount, decimal string (uint256-safe). */\n\treadonly amount: string;\n\t/** x402 network the settlement landed on. */\n\treadonly network: X402Network;\n\t/** Optional captured response for byte-identical replay. */\n\treadonly responseSnapshot?: IdempotencyResponseSnapshot;\n\t/** Unix-seconds expiry. The record MUST NOT outlive the authorization `validBefore`. */\n\treadonly expiresAt: bigint;\n}\n\ninterface IdempotencyResponseSnapshotJson {\n\treadonly status: number;\n\treadonly headers: ReadonlyArray<readonly [string, string]>;\n\treadonly bodyBase64: string;\n}\n\ninterface IdempotencyRecordJson {\n\treadonly kawasekitVersion: string;\n\treadonly key: string;\n\treadonly txHash: string;\n\treadonly payer: string;\n\treadonly amount: string;\n\treadonly network: string;\n\treadonly responseSnapshot?: IdempotencyResponseSnapshotJson;\n\treadonly expiresAt: string;\n}\n\nconst UINT_DECIMAL = /^(0|[1-9][0-9]*)$/;\nconst HEX = /^0x[0-9a-fA-F]*$/;\n\nfunction assertString(value: unknown, field: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a string`);\n\t}\n\treturn value;\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): string {\n\tconst s = assertString(value, field);\n\tif (s === \"\") {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must not be empty`);\n\t}\n\treturn s;\n}\n\nfunction assertNumber(value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a finite number`);\n\t}\n\treturn value;\n}\n\nfunction assertHex(value: unknown, field: string): Hex {\n\tconst s = assertString(value, field);\n\tif (!HEX.test(s) || s.length % 2 !== 0) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be 0x-prefixed even-length hex`);\n\t}\n\t// Narrowed to viem's Hex by the regex above; the cast carries no extra trust.\n\treturn s as Hex;\n}\n\nfunction parseBigIntString(value: unknown, field: string): bigint {\n\tconst s = assertString(value, field);\n\tif (!UINT_DECIMAL.test(s)) {\n\t\tthrow new IdempotencyRecordParseError(\n\t\t\t`field \"${field}\" must be a non-negative decimal integer string`,\n\t\t);\n\t}\n\treturn BigInt(s);\n}\n\nfunction assertAddress(value: unknown, field: string): Address {\n\tconst s = assertString(value, field);\n\ttry {\n\t\treturn getAddress(s);\n\t} catch (cause) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a valid address`, { cause });\n\t}\n}\n\nfunction assertNetwork(value: unknown, field: string): X402Network {\n\tconst s = assertString(value, field);\n\tif (!isX402Network(s)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a valid x402 network`);\n\t}\n\treturn s;\n}\n\nfunction assertSnapshot(value: unknown): IdempotencyResponseSnapshot {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"responseSnapshot\" must be an object`);\n\t}\n\tconst raw = value as {\n\t\tstatus?: unknown;\n\t\theaders?: unknown;\n\t\tbodyBase64?: unknown;\n\t};\n\tconst status = assertNumber(raw.status, \"responseSnapshot.status\");\n\tif (!Array.isArray(raw.headers)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"responseSnapshot.headers\" must be an array`);\n\t}\n\tconst headers = raw.headers.map((pair, i): readonly [string, string] => {\n\t\tif (!Array.isArray(pair) || pair.length !== 2) {\n\t\t\tthrow new IdempotencyRecordParseError(\n\t\t\t\t`field \"responseSnapshot.headers[${i}]\" must be a [name, value] pair`,\n\t\t\t);\n\t\t}\n\t\treturn [\n\t\t\tassertString(pair[0], `responseSnapshot.headers[${i}][0]`),\n\t\t\tassertString(pair[1], `responseSnapshot.headers[${i}][1]`),\n\t\t];\n\t});\n\tconst bodyBase64 = assertString(raw.bodyBase64, \"responseSnapshot.bodyBase64\");\n\treturn { status, headers, bodyBase64 };\n}\n\n/**\n * Serializes a record to a plain UTF-8 JSON string (base64 / transport is the\n * caller's concern). Bigints become decimal strings.\n *\n * @example\n * ```ts\n * import { serializeIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * const json = serializeIdempotencyRecord(record);\n * ```\n */\nexport function serializeIdempotencyRecord(record: IdempotencyRecord): string {\n\tconst json: IdempotencyRecordJson = {\n\t\tkawasekitVersion: record.kawasekitVersion,\n\t\tkey: record.key,\n\t\ttxHash: record.txHash,\n\t\tpayer: record.payer,\n\t\tamount: record.amount,\n\t\tnetwork: record.network,\n\t\t...(record.responseSnapshot !== undefined ? { responseSnapshot: record.responseSnapshot } : {}),\n\t\texpiresAt: record.expiresAt.toString(),\n\t};\n\treturn JSON.stringify(json);\n}\n\n/**\n * Parses a serialized record. Throws {@link IdempotencyRecordVersionError} on a\n * version mismatch and {@link IdempotencyRecordParseError} on any structural /\n * field error (so a corrupt entry can be dropped and the request treated as\n * fresh — fund-correctness still rests on the on-chain nonce, not this cache).\n *\n * @example\n * ```ts\n * import { parseIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * const record = parseIdempotencyRecord(jsonFromStore);\n * ```\n */\nexport function parseIdempotencyRecord(input: string): IdempotencyRecord {\n\tlet raw: unknown;\n\ttry {\n\t\traw = JSON.parse(input);\n\t} catch (cause) {\n\t\tthrow new IdempotencyRecordParseError(\"input is not valid JSON\", { cause });\n\t}\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new IdempotencyRecordParseError(\"input must be a JSON object\");\n\t}\n\t// Narrow to a per-field `unknown` shape (not an index signature) so each field\n\t// is validated by an assert* helper and dot-access stays lint-clean.\n\tconst obj = raw as {\n\t\treadonly kawasekitVersion?: unknown;\n\t\treadonly key?: unknown;\n\t\treadonly txHash?: unknown;\n\t\treadonly payer?: unknown;\n\t\treadonly amount?: unknown;\n\t\treadonly network?: unknown;\n\t\treadonly responseSnapshot?: unknown;\n\t\treadonly expiresAt?: unknown;\n\t};\n\n\tconst version = assertString(obj.kawasekitVersion, \"kawasekitVersion\");\n\tif (version !== KAWASEKIT_IDEMPOTENCY_RECORD_VERSION) {\n\t\tthrow new IdempotencyRecordVersionError(KAWASEKIT_IDEMPOTENCY_RECORD_VERSION, version);\n\t}\n\n\tconst snapshotRaw = obj.responseSnapshot;\n\treturn {\n\t\tkawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n\t\tkey: assertNonEmptyString(obj.key, \"key\"),\n\t\ttxHash: assertHex(obj.txHash, \"txHash\"),\n\t\tpayer: assertAddress(obj.payer, \"payer\"),\n\t\tamount: parseBigIntString(obj.amount, \"amount\").toString(),\n\t\tnetwork: assertNetwork(obj.network, \"network\"),\n\t\t...(snapshotRaw !== undefined ? { responseSnapshot: assertSnapshot(snapshotRaw) } : {}),\n\t\texpiresAt: parseBigIntString(obj.expiresAt, \"expiresAt\"),\n\t};\n}\n","/**\n * The idempotency store abstraction + the default in-memory implementation\n * (M5-1).\n *\n * The store is an **injected** dependency (mirroring how `Facilitator` / `hooks`\n * are injected), never a module global — kawasekit holds no ambient state. The\n * default {@link createInMemoryIdempotencyStore} is single-process; durable /\n * cross-replica backends (Redis, SQL) are operator territory, shipped as\n * optional-peer-dep adapters that implement this same interface.\n *\n * **Correctness vs. telemetry.** Unlike observability hooks (fire-and-forget),\n * store calls are correctness-relevant and are awaited; their errors are NOT\n * swallowed. Fund-correctness, however, never *depends* on the store — the\n * on-chain EIP-3009 nonce is the backstop — so a cold/missing store degrades\n * response replay, not safety.\n *\n * @packageDocumentation\n */\n\nimport { IdempotencyConfigError } from \"./errors\";\nimport type { IdempotencyRecord } from \"./record\";\n\n/** A fence token proving ownership of an in-flight slot, carrying its expiry. */\nexport interface IdempotencyLease {\n\treadonly token: string;\n\t/** Unix-seconds; after this the lease is reclaimable as `fresh` (crash recovery). */\n\treadonly expiresAt: bigint;\n}\n\n/** The outcome of {@link IdempotencyStore.begin}. */\nexport type IdempotencyLookupResult =\n\t| { readonly status: \"fresh\"; readonly lease: IdempotencyLease }\n\t| { readonly status: \"in_flight\" }\n\t| { readonly status: \"completed\"; readonly record: IdempotencyRecord };\n\n/**\n * Reasoning-step idempotency store. Implementations MUST make {@link begin}\n * atomic: a single caller wins the `fresh` lease; concurrent callers see\n * `in_flight`; an *expired* in-flight lease is reclaimable as `fresh` so a\n * crashed holder cannot strand a key forever.\n */\nexport interface IdempotencyStore {\n\t/** Atomically lease a fresh slot, or report in-flight / completed. */\n\tbegin(key: string): Promise<IdempotencyLookupResult>;\n\t/** Extend an owned lease while a settlement runs long. Rejects if the lease was lost. */\n\trenew(key: string, lease: IdempotencyLease): Promise<IdempotencyLease>;\n\t/** Persist the completed record (no-op if the lease was reclaimed/superseded). */\n\tcomplete(key: string, record: IdempotencyRecord, lease: IdempotencyLease): Promise<void>;\n\t/** Release an owned in-flight slot so the step can be retried (idempotent). */\n\tabandon(key: string, lease: IdempotencyLease): Promise<void>;\n}\n\n/** Parameters for {@link createInMemoryIdempotencyStore}. */\nexport interface CreateInMemoryIdempotencyStoreParams {\n\t/** LRU cap on retained entries (memory-DoS bound, T-I9). Default 10_000. */\n\treadonly maxEntries?: number;\n\t/** In-flight lease TTL in seconds (crash-recovery window, H3). Default 90. */\n\treadonly leaseTtlSeconds?: number;\n\t/** Unix-seconds clock (override for tests). */\n\treadonly now?: () => bigint;\n\t/** Lease-token source (override for tests). */\n\treadonly generateLeaseToken?: () => string;\n\t/** Suppress the one-time single-process warning (default emits it). */\n\treadonly warnOnConstruct?: boolean;\n}\n\ntype Entry =\n\t| { readonly state: \"in_flight\"; readonly lease: IdempotencyLease }\n\t| { readonly state: \"completed\"; readonly record: IdempotencyRecord };\n\nfunction entryExpiry(entry: Entry): bigint {\n\treturn entry.state === \"in_flight\" ? entry.lease.expiresAt : entry.record.expiresAt;\n}\n\nfunction defaultNow(): bigint {\n\treturn BigInt(Math.floor(Date.now() / 1000));\n}\n\nfunction defaultLeaseToken(): string {\n\tconst bytes = new Uint8Array(16);\n\tcrypto.getRandomValues(bytes);\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nlet warnedSingleProcess = false;\n\nfunction warnSingleProcessOnce(): void {\n\tif (warnedSingleProcess) {\n\t\treturn;\n\t}\n\twarnedSingleProcess = true;\n\tif (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n\t\tprocess.emitWarning(\n\t\t\t\"createInMemoryIdempotencyStore: in-memory dedup is single-process and does NOT \" +\n\t\t\t\t\"deduplicate across replicas. Multi-replica deployments require a shared store \" +\n\t\t\t\t\"(Redis/SQL adapter) or the client-side derived nonce for the guarantee.\",\n\t\t\t{ type: \"Warning\", code: \"KAWASEKIT_IDEMPOTENCY_001\" },\n\t\t);\n\t}\n}\n\n/**\n * In-memory, single-process idempotency store: a bounded LRU with a leased\n * in-flight state machine and lazy TTL eviction. The default the SDK ships;\n * safe for one process, NOT for multiple replicas (see the construct-time\n * warning).\n *\n * @example\n * ```ts\n * import { createInMemoryIdempotencyStore } from \"kawasekit/idempotency\";\n *\n * const store = createInMemoryIdempotencyStore({ maxEntries: 50_000 });\n * const result = await store.begin(key);\n * if (result.status === \"completed\") {\n * // replay result.record\n * }\n * ```\n */\nexport function createInMemoryIdempotencyStore(\n\tparams: CreateInMemoryIdempotencyStoreParams = {},\n): IdempotencyStore {\n\tconst maxEntries = params.maxEntries ?? 10_000;\n\tif (!Number.isInteger(maxEntries) || maxEntries < 1) {\n\t\tthrow new IdempotencyConfigError(\"maxEntries\", \"must be a positive integer\");\n\t}\n\tconst leaseTtlSeconds = params.leaseTtlSeconds ?? 90;\n\tif (!Number.isInteger(leaseTtlSeconds) || leaseTtlSeconds < 1) {\n\t\tthrow new IdempotencyConfigError(\"leaseTtlSeconds\", \"must be a positive integer\");\n\t}\n\tconst now = params.now ?? defaultNow;\n\tconst mintToken = params.generateLeaseToken ?? defaultLeaseToken;\n\n\tif (params.warnOnConstruct !== false) {\n\t\twarnSingleProcessOnce();\n\t}\n\n\t// Map preserves insertion order; we delete+set on access to move the entry\n\t// to the tail, so the head is always the least-recently-used.\n\tconst entries = new Map<string, Entry>();\n\n\t/** Read an entry, treating an expired one as absent (and evicting it). */\n\tfunction live(key: string): Entry | undefined {\n\t\tconst entry = entries.get(key);\n\t\tif (entry === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (entryExpiry(entry) <= now()) {\n\t\t\tentries.delete(key);\n\t\t\treturn undefined;\n\t\t}\n\t\t// LRU touch.\n\t\tentries.delete(key);\n\t\tentries.set(key, entry);\n\t\treturn entry;\n\t}\n\n\tfunction set(key: string, entry: Entry): void {\n\t\tentries.delete(key);\n\t\tentries.set(key, entry);\n\t\twhile (entries.size > maxEntries) {\n\t\t\tconst oldest = entries.keys().next().value;\n\t\t\tif (oldest === undefined) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tentries.delete(oldest);\n\t\t}\n\t}\n\n\treturn {\n\t\tasync begin(key: string): Promise<IdempotencyLookupResult> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry === undefined) {\n\t\t\t\tconst lease: IdempotencyLease = {\n\t\t\t\t\ttoken: mintToken(),\n\t\t\t\t\texpiresAt: now() + BigInt(leaseTtlSeconds),\n\t\t\t\t};\n\t\t\t\tset(key, { state: \"in_flight\", lease });\n\t\t\t\treturn { status: \"fresh\", lease };\n\t\t\t}\n\t\t\tif (entry.state === \"completed\") {\n\t\t\t\treturn { status: \"completed\", record: entry.record };\n\t\t\t}\n\t\t\treturn { status: \"in_flight\" };\n\t\t},\n\n\t\tasync renew(key: string, lease: IdempotencyLease): Promise<IdempotencyLease> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry === undefined || entry.state !== \"in_flight\" || entry.lease.token !== lease.token) {\n\t\t\t\tthrow new IdempotencyConfigError(\n\t\t\t\t\t\"lease\",\n\t\t\t\t\t\"renew called without an owned in-flight lease (lost or reclaimed)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst renewed: IdempotencyLease = {\n\t\t\t\ttoken: lease.token,\n\t\t\t\texpiresAt: now() + BigInt(leaseTtlSeconds),\n\t\t\t};\n\t\t\tset(key, { state: \"in_flight\", lease: renewed });\n\t\t\treturn renewed;\n\t\t},\n\n\t\tasync complete(key: string, record: IdempotencyRecord, lease: IdempotencyLease): Promise<void> {\n\t\t\tconst entry = live(key);\n\t\t\t// Only the lease holder may write. If the lease was reclaimed (expired)\n\t\t\t// or another holder superseded it, do NOT clobber — fund-correctness is\n\t\t\t// guaranteed on-chain regardless; this only affects response replay.\n\t\t\tif (entry === undefined || entry.state !== \"in_flight\" || entry.lease.token !== lease.token) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tset(key, { state: \"completed\", record });\n\t\t},\n\n\t\tasync abandon(key: string, lease: IdempotencyLease): Promise<void> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry !== undefined && entry.state === \"in_flight\" && entry.lease.token === lease.token) {\n\t\t\t\tentries.delete(key);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * `createX402Handler()` — framework-agnostic x402 v2 resource-server adapter.\n *\n * The returned function maps any WHATWG `Request` to a `Response`, gating the\n * caller-supplied inner handler behind an x402 payment flow:\n *\n * 1. Compute requirements for the request (via `requirementsFor`).\n * `null` / empty array → no payment, pass through to inner handler.\n * 2. Look for the `PAYMENT-SIGNATURE` header. If missing or malformed →\n * `402 Payment Required` with a `PAYMENT-REQUIRED` header carrying the\n * encoded {@link X402PaymentRequiredResponse}.\n * 3. The client's `paymentPayload.accepted` must match one entry in our\n * requirements list (scheme / network / amount / asset / payTo).\n * 4. Call `facilitator.verify`. On failure → 402 with a reason.\n * 5. Call `facilitator.settle`. On failure → 402 with a reason. On success →\n * invoke the inner handler, attach the `PAYMENT-RESPONSE` header, return.\n *\n * Because the contract is `Request → Response`, the handler runs unchanged on\n * Node (via `@hono/node-server` or a hand-rolled adapter), Bun, Deno, Cloudflare\n * Workers, and Vercel Edge.\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport { getAddress } from \"viem\";\nimport {\n\tcreateInMemoryIdempotencyStore,\n\ttype IdempotencyLease,\n\ttype IdempotencyLookupResult,\n\ttype IdempotencyRecord,\n\ttype IdempotencyResponseSnapshot,\n\ttype IdempotencyStore,\n\tKAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n} from \"../idempotency\";\nimport {\n\textractAcceptedNetworks,\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n\ttype PaymentAcceptedEvent,\n\ttype PaymentRequiredEvent,\n} from \"../observability/hooks\";\nimport {\n\tdecodePaymentSignatureHeader,\n\tencodePaymentRequiredHeader,\n\tencodePaymentResponseHeader,\n\tX402_HEADER_IDEMPOTENCY_KEY,\n\tX402_HEADER_PAYMENT_REQUIRED,\n\tX402_HEADER_PAYMENT_RESPONSE,\n\tX402_HEADER_PAYMENT_SIGNATURE,\n} from \"./encoding\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport { buildPaymentRequiredResponse } from \"./payment-requirements\";\nimport type {\n\tFacilitator,\n\tX402PaymentPayload,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n\tX402SettlementResponse,\n} from \"./types\";\nimport { X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Context passed to the inner handler **after** a payment has been verified\n * and settled. `null` when the request bypassed the payment flow because\n * `requirementsFor` returned `null` / `[]`.\n */\nexport interface X402HandlerContext {\n\t/** The client's signed payment payload. */\n\treadonly paymentPayload: X402PaymentPayload;\n\t/** The matching requirements entry the client targeted. */\n\treadonly matchedRequirements: X402PaymentRequirements;\n\t/** Facilitator's settlement response (broadcast already happened). */\n\treadonly settlement: X402SettlementResponse;\n}\n\n/**\n * The inner business-logic handler. Receives the same `Request` plus a context\n * that is present when a payment was made for this request, and `null`\n * otherwise (pass-through case).\n */\nexport type X402InnerHandler = (\n\trequest: Request,\n\tcontext: X402HandlerContext | null,\n) => Promise<Response> | Response;\n\n/** Parameters for {@link createX402Handler}. */\nexport interface CreateX402HandlerParams {\n\t/** Facilitator that performs verify and settle (self or HTTP-proxied). */\n\treadonly facilitator: Facilitator;\n\t/**\n\t * Returns the {@link X402PaymentRequirements} that apply to this request.\n\t *\n\t * - Return one or more entries to require payment (client picks one).\n\t * - Return `null` or `[]` to skip the payment flow entirely for this\n\t * request — the inner handler is invoked with `context = null`.\n\t */\n\treadonly requirementsFor: (\n\t\trequest: Request,\n\t) =>\n\t\t| Promise<readonly X402PaymentRequirements[] | null>\n\t\t| readonly X402PaymentRequirements[]\n\t\t| null;\n\t/** The protected business-logic handler. Invoked after settlement. */\n\treadonly handler: X402InnerHandler;\n\t/**\n\t * Optional builder for the {@link X402ResourceInfo} echoed in the 402\n\t * response. Defaults to `{ url: request.url }`.\n\t */\n\treadonly resourceFor?: (request: Request) => Promise<X402ResourceInfo> | X402ResourceInfo;\n\t/**\n\t * Optional observability callbacks. The handler emits `onPaymentRequired`\n\t * each time it returns a 402, and `onPaymentAccepted` after a settled\n\t * payment unlocks the inner handler. Hooks are fire-and-forget — see\n\t * {@link ObservabilityHooks}.\n\t */\n\treadonly hooks?: ObservabilityHooks;\n\t/**\n\t * Reasoning-step idempotency (M5-1, Half A). **Default-on**: when omitted, an\n\t * in-memory store deduplicates re-sent / concurrent paid requests — replaying\n\t * the cached response and closing the verify→settle TOCTOU. Pass\n\t * `{ store: \"none\" }` to disable, or a shared store (Redis/SQL adapter) for\n\t * multi-replica deployments (the in-memory default is single-process).\n\t * Fund-correctness never depends on this store — the on-chain EIP-3009 nonce\n\t * is the backstop.\n\t */\n\treadonly idempotency?: IdempotencyServerConfig;\n}\n\n/** Server-side idempotency configuration (M5-1). See {@link CreateX402HandlerParams.idempotency}. */\nexport interface IdempotencyServerConfig {\n\t/** The store, or `\"none\"` to disable. Default: a fresh in-memory bounded LRU. */\n\treadonly store?: IdempotencyStore | \"none\";\n\t/**\n\t * What to do when a concurrent request holds the in-flight lease for the same\n\t * key. `\"reject\"` (default) returns a `payment_in_progress` 402 (the client\n\t * retries and gets the cached result); `\"await\"` polls briefly for the twin\n\t * to complete, then replays its response.\n\t */\n\treadonly inFlight?: \"await\" | \"reject\";\n\t/** Max captured response body size for replay, in bytes. Default 65536 (64 KiB). */\n\treadonly maxSnapshotBytes?: number;\n\t/** Fallback record TTL in seconds when the authorization `validBefore` is unreadable. Default 86400. */\n\treadonly fallbackTtlSeconds?: number;\n}\n\n/** The function returned by {@link createX402Handler}. */\nexport type X402RequestHandler = (request: Request) => Promise<Response>;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultResource(request: Request): X402ResourceInfo {\n\treturn { url: request.url };\n}\n\nfunction isSameRequirements(\n\toffered: X402PaymentRequirements,\n\tchosen: X402PaymentRequirements,\n): boolean {\n\treturn (\n\t\toffered.scheme === chosen.scheme &&\n\t\toffered.network === chosen.network &&\n\t\toffered.amount === chosen.amount &&\n\t\tgetAddress(offered.asset) === getAddress(chosen.asset) &&\n\t\tgetAddress(offered.payTo) === getAddress(chosen.payTo)\n\t);\n}\n\nasync function paymentRequired(\n\trequest: Request,\n\trequirements: readonly X402PaymentRequirements[],\n\tresourceFor: ((r: Request) => Promise<X402ResourceInfo> | X402ResourceInfo) | undefined,\n\terror: string,\n): Promise<Response> {\n\tconst resource = resourceFor ? await resourceFor(request) : defaultResource(request);\n\tconst body = buildPaymentRequiredResponse({ resource, accepts: requirements, error });\n\tconst headers = new Headers({ \"content-type\": \"application/json\" });\n\theaders.set(X402_HEADER_PAYMENT_REQUIRED, encodePaymentRequiredHeader(body));\n\treturn new Response(JSON.stringify(body), { status: 402, headers });\n}\n\nfunction internalError(reason: string, cause: unknown): Response {\n\tconst message = cause instanceof Error ? cause.message : String(cause);\n\treturn new Response(JSON.stringify({ error: reason, message }), {\n\t\tstatus: 500,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction withPaymentResponseHeader(\n\tinnerResponse: Response,\n\tsettlement: X402SettlementResponse,\n): Response {\n\tconst headers = new Headers(innerResponse.headers);\n\theaders.set(X402_HEADER_PAYMENT_RESPONSE, encodePaymentResponseHeader(settlement));\n\treturn new Response(innerResponse.body, {\n\t\tstatus: innerResponse.status,\n\t\tstatusText: innerResponse.statusText,\n\t\theaders,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Idempotency (M5-1) helpers\n// ---------------------------------------------------------------------------\n\n/** Credential-safe header allowlist preserved in a replayed response. */\nconst SNAPSHOT_HEADER_ALLOWLIST = [\"content-type\", X402_HEADER_PAYMENT_RESPONSE];\nconst IDEMPOTENCY_REPLAYED_HEADER = \"Idempotency-Replayed\";\nconst DEFAULT_MAX_SNAPSHOT_BYTES = 64 * 1024;\nconst DEFAULT_FALLBACK_TTL_SECONDS = 86_400;\n\ninterface ResolvedIdempotency {\n\treadonly store: IdempotencyStore;\n\treadonly inFlight: \"await\" | \"reject\";\n\treadonly maxSnapshotBytes: number;\n\treadonly fallbackTtlSeconds: number;\n}\n\n/** Resolve the (default-on) idempotency config once per handler construction. */\nfunction resolveIdempotency(\n\tconfig: IdempotencyServerConfig | undefined,\n): ResolvedIdempotency | null {\n\tif (config?.store === \"none\") {\n\t\treturn null;\n\t}\n\treturn {\n\t\tstore: config?.store ?? createInMemoryIdempotencyStore(),\n\t\tinFlight: config?.inFlight ?? \"reject\",\n\t\tmaxSnapshotBytes: config?.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES,\n\t\tfallbackTtlSeconds: config?.fallbackTtlSeconds ?? DEFAULT_FALLBACK_TTL_SECONDS,\n\t};\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const b of bytes) {\n\t\tbinary += String.fromCharCode(b);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n\tconst binary = atob(b64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i += 1) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\n/** Defensively read the EIP-3009 nonce + validBefore from an opaque payload. */\nfunction readAuthorization(\n\tpayload: X402PaymentPayload,\n): { readonly nonce: string; readonly validBefore: bigint } | null {\n\tconst inner = payload.payload;\n\tif (typeof inner !== \"object\" || inner === null) {\n\t\treturn null;\n\t}\n\tconst auth = (inner as { authorization?: unknown }).authorization;\n\tif (typeof auth !== \"object\" || auth === null) {\n\t\treturn null;\n\t}\n\tconst a = auth as { nonce?: unknown; validBefore?: unknown };\n\tif (typeof a.nonce !== \"string\" || a.nonce === \"\") {\n\t\treturn null;\n\t}\n\tconst validBefore =\n\t\ttypeof a.validBefore === \"string\" && /^[0-9]+$/.test(a.validBefore)\n\t\t\t? BigInt(a.validBefore)\n\t\t\t: 0n;\n\treturn { nonce: a.nonce, validBefore };\n}\n\n/**\n * The server dedup key: the client `Idempotency-Key` header when present (the\n * logical reasoning-step key, working even for signers that cannot derive a\n * nonce), else the EIP-3009 nonce — both namespaced by (network, payTo, asset)\n * for cross-tenant isolation. `null` ⇒ no key can be formed; dedup is skipped\n * (the on-chain nonce still backstops fund-correctness).\n */\nfunction computeServerKey(\n\trequest: Request,\n\trequirements: X402PaymentRequirements,\n\tauth: { readonly nonce: string } | null,\n): string | null {\n\tconst header = request.headers.get(X402_HEADER_IDEMPOTENCY_KEY);\n\tlet material: string;\n\tif (header !== null && header !== \"\") {\n\t\tmaterial = `hdr:${header}`;\n\t} else if (auth !== null) {\n\t\tmaterial = `nonce:${auth.nonce}`;\n\t} else {\n\t\treturn null;\n\t}\n\treturn JSON.stringify([\n\t\trequirements.network,\n\t\tgetAddress(requirements.payTo),\n\t\tgetAddress(requirements.asset),\n\t\tmaterial,\n\t]);\n}\n\n/**\n * Snapshot a response for replay, reading from a clone so the original body\n * stays intact. `undefined` if the body exceeds `maxBytes` (the record then\n * stores only the settlement for a minimal replay).\n */\nasync function snapshotResponse(\n\tresponse: Response,\n\tmaxBytes: number,\n): Promise<IdempotencyResponseSnapshot | undefined> {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null && Number(contentLength) > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst buffer = await response.clone().arrayBuffer();\n\tif (buffer.byteLength > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst headers: Array<readonly [string, string]> = [];\n\tfor (const name of SNAPSHOT_HEADER_ALLOWLIST) {\n\t\tconst value = response.headers.get(name);\n\t\tif (value !== null) {\n\t\t\theaders.push([name, value]);\n\t\t}\n\t}\n\treturn { status: response.status, headers, bodyBase64: bytesToBase64(new Uint8Array(buffer)) };\n}\n\n/** Rebuild a response from a completed record (replay path), tagged for clients. */\nfunction replayResponse(record: IdempotencyRecord): Response {\n\tconst snapshot = record.responseSnapshot;\n\tif (snapshot !== undefined) {\n\t\tconst headers = new Headers();\n\t\tfor (const [name, value] of snapshot.headers) {\n\t\t\theaders.set(name, value);\n\t\t}\n\t\theaders.set(IDEMPOTENCY_REPLAYED_HEADER, \"true\");\n\t\treturn new Response(base64ToBytes(snapshot.bodyBase64), { status: snapshot.status, headers });\n\t}\n\tconst headers = new Headers({ [IDEMPOTENCY_REPLAYED_HEADER]: \"true\" });\n\theaders.set(\n\t\tX402_HEADER_PAYMENT_RESPONSE,\n\t\tencodePaymentResponseHeader({\n\t\t\tsuccess: true,\n\t\t\ttransaction: record.txHash,\n\t\t\tnetwork: record.network,\n\t\t\tpayer: record.payer,\n\t\t\tamount: record.amount,\n\t\t}),\n\t);\n\treturn new Response(null, { status: 200, headers });\n}\n\nfunction buildRecord(\n\tkey: string,\n\tsettlement: X402SettlementResponse,\n\trequirements: X402PaymentRequirements,\n\tvalidBefore: bigint,\n\tfallbackTtlSeconds: number,\n\tsnapshot: IdempotencyResponseSnapshot | undefined,\n): IdempotencyRecord | null {\n\tif (settlement.transaction === \"\" || settlement.payer === undefined) {\n\t\treturn null;\n\t}\n\tconst nowSec = BigInt(Math.floor(Date.now() / 1000));\n\tconst expiresAt = validBefore > nowSec ? validBefore : nowSec + BigInt(fallbackTtlSeconds);\n\treturn {\n\t\tkawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n\t\tkey,\n\t\t// settlement.transaction is the on-chain tx hash (0x-hex) the facilitator broadcast.\n\t\ttxHash: settlement.transaction as Hex,\n\t\tpayer: settlement.payer,\n\t\tamount: settlement.amount ?? requirements.amount,\n\t\tnetwork: requirements.network,\n\t\t...(snapshot !== undefined ? { responseSnapshot: snapshot } : {}),\n\t\texpiresAt,\n\t};\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, ms);\n\t});\n}\n\nconst IN_FLIGHT_POLL_MS = 100;\nconst IN_FLIGHT_MAX_POLLS = 50; // ~5s bounded wait for the \"await\" policy\n\n/** Release an owned in-flight lease so the step can be retried (best-effort). */\nasync function releaseLease(\n\tidem: ResolvedIdempotency | null,\n\tkey: string | null,\n\tlease: IdempotencyLease | null,\n): Promise<void> {\n\tif (idem !== null && key !== null && lease !== null) {\n\t\ttry {\n\t\t\tawait idem.store.abandon(key, lease);\n\t\t} catch {\n\t\t\t// best-effort: the lease will also expire on its own (crash-recovery TTL).\n\t\t}\n\t}\n}\n\n/**\n * For the `\"await\"` in-flight policy, poll briefly for a concurrent twin to\n * complete. Returns its record to replay, or `null` to fall back to the reject\n * path (twin still running past the budget, or it died and freed the slot).\n */\nasync function resolveInFlight(\n\tidem: ResolvedIdempotency,\n\tkey: string,\n): Promise<IdempotencyRecord | null> {\n\tif (idem.inFlight !== \"await\") {\n\t\treturn null;\n\t}\n\tfor (let i = 0; i < IN_FLIGHT_MAX_POLLS; i += 1) {\n\t\tawait sleep(IN_FLIGHT_POLL_MS);\n\t\tlet lookup: IdempotencyLookupResult;\n\t\ttry {\n\t\t\tlookup = await idem.store.begin(key);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (lookup.status === \"completed\") {\n\t\t\treturn lookup.record;\n\t\t}\n\t\tif (lookup.status === \"fresh\") {\n\t\t\t// The twin died and we now hold the lease; release it and let the\n\t\t\t// caller reject (the client retries and settles cleanly).\n\t\t\tawait releaseLease(idem, key, lookup.lease);\n\t\t\treturn null;\n\t\t}\n\t\t// still in_flight → keep polling\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds an {@link X402RequestHandler} that wraps `params.handler` with the\n * x402 payment flow.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * createSelfFacilitator,\n * createX402Handler,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const handler = createX402Handler({\n * facilitator: createSelfFacilitator({ walletClient, publicClient }),\n * requirementsFor: (req) =>\n * new URL(req.url).pathname.startsWith(\"/weather\")\n * ? [buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x...\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * })]\n * : null,\n * handler: async (req) => new Response(JSON.stringify({ weather: \"sunny\" }), {\n * headers: { \"content-type\": \"application/json\" },\n * }),\n * });\n *\n * // Mount on any framework that exposes WHATWG Request → Response.\n * ```\n */\nexport function createX402Handler(params: CreateX402HandlerParams): X402RequestHandler {\n\tconst { facilitator, requirementsFor, handler, resourceFor, hooks } = params;\n\t// Resolved ONCE so the in-memory store persists across requests (the Hono\n\t// adapter rebuilds the handler per request, so this must live in the closure).\n\tconst idempotency = resolveIdempotency(params.idempotency);\n\n\treturn async function x402Handler(request: Request): Promise<Response> {\n\t\tconst startedAtMs = Date.now();\n\n\t\tconst emitPaymentRequired = (\n\t\t\treqs: readonly X402PaymentRequirements[],\n\t\t\terror: string,\n\t\t): Promise<Response> => {\n\t\t\tconst event: PaymentRequiredEvent = {\n\t\t\t\tkind: \"payment_required\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tacceptedNetworks: extractAcceptedNetworks(reqs),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentRequired, event);\n\t\t\treturn paymentRequired(request, reqs, resourceFor, error);\n\t\t};\n\n\t\t// 1. Resolve requirements (or pass through)\n\t\tlet requirements: readonly X402PaymentRequirements[] | null;\n\t\ttry {\n\t\t\trequirements = await requirementsFor(request);\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"requirements_resolution_failed\", cause);\n\t\t}\n\t\tif (requirements === null || requirements.length === 0) {\n\t\t\treturn handler(request, null);\n\t\t}\n\n\t\t// 2. Read the PAYMENT-SIGNATURE header\n\t\tconst headerValue = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);\n\t\tif (headerValue === null || headerValue === \"\") {\n\t\t\treturn emitPaymentRequired(requirements, \"PAYMENT-SIGNATURE header is required\");\n\t\t}\n\n\t\t// 3. Decode the payment payload\n\t\tlet paymentPayload: X402PaymentPayload;\n\t\ttry {\n\t\t\tpaymentPayload = decodePaymentSignatureHeader(headerValue);\n\t\t} catch (cause) {\n\t\t\tconst reason =\n\t\t\t\tcause instanceof X402InvalidPayloadError\n\t\t\t\t\t? cause.reason\n\t\t\t\t\t: \"invalid PAYMENT-SIGNATURE header\";\n\t\t\treturn emitPaymentRequired(requirements, reason);\n\t\t}\n\n\t\t// 4. Match chosen requirements to an offered entry\n\t\tconst matchedRequirements = requirements.find((offered) =>\n\t\t\tisSameRequirements(offered, paymentPayload.accepted),\n\t\t);\n\t\tif (!matchedRequirements) {\n\t\t\treturn emitPaymentRequired(\n\t\t\t\trequirements,\n\t\t\t\t\"paymentPayload.accepted does not match any offered requirements\",\n\t\t\t);\n\t\t}\n\n\t\t// 5. Verify\n\t\tlet verifyResult: Awaited<ReturnType<Facilitator[\"verify\"]>>;\n\t\ttry {\n\t\t\tverifyResult = await facilitator.verify({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"facilitator_verify_failed\", cause);\n\t\t}\n\t\tif (!verifyResult.isValid) {\n\t\t\treturn emitPaymentRequired(requirements, verifyResult.invalidReason ?? \"verify failed\");\n\t\t}\n\n\t\t// 5b. Reasoning-step idempotency gate (M5-1, Half A). Runs AFTER verify so a\n\t\t// cached response is only released against a re-verified authorization.\n\t\tconst auth = readAuthorization(paymentPayload);\n\t\tconst idemKey =\n\t\t\tidempotency !== null ? computeServerKey(request, matchedRequirements, auth) : null;\n\t\tlet lease: IdempotencyLease | null = null;\n\t\tif (idempotency !== null && idemKey !== null) {\n\t\t\tlet lookup: IdempotencyLookupResult;\n\t\t\ttry {\n\t\t\t\tlookup = await idempotency.store.begin(idemKey);\n\t\t\t} catch (cause) {\n\t\t\t\treturn internalError(\"idempotency_store_failed\", cause);\n\t\t\t}\n\t\t\tif (lookup.status === \"completed\") {\n\t\t\t\treturn replayResponse(lookup.record);\n\t\t\t}\n\t\t\tif (lookup.status === \"in_flight\") {\n\t\t\t\tconst awaited = await resolveInFlight(idempotency, idemKey);\n\t\t\t\tif (awaited !== null) {\n\t\t\t\t\treturn replayResponse(awaited);\n\t\t\t\t}\n\t\t\t\treturn emitPaymentRequired(requirements, \"payment_in_progress\");\n\t\t\t}\n\t\t\tlease = lookup.lease;\n\t\t}\n\n\t\t// 6. Settle\n\t\tlet settleResult: Awaited<ReturnType<Facilitator[\"settle\"]>>;\n\t\ttry {\n\t\t\tsettleResult = await facilitator.settle({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn internalError(\"facilitator_settle_failed\", cause);\n\t\t}\n\t\tif (!settleResult.success) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn emitPaymentRequired(requirements, settleResult.errorReason ?? \"settle failed\");\n\t\t}\n\n\t\t// 7. Settled — emit onPaymentAccepted then invoke inner handler.\n\t\tif (settleResult.payer !== undefined) {\n\t\t\tconst acceptedEvent: PaymentAcceptedEvent = {\n\t\t\t\tkind: \"payment_accepted\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tpayer: settleResult.payer,\n\t\t\t\tamount: settleResult.amount ?? matchedRequirements.amount,\n\t\t\t\tnetwork: matchedRequirements.network,\n\t\t\t\ttransaction: settleResult.transaction as Hex,\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentAccepted, acceptedEvent);\n\t\t}\n\n\t\t// Inner handler errors propagate — settlement has already happened.\n\t\tconst context: X402HandlerContext = {\n\t\t\tpaymentPayload,\n\t\t\tmatchedRequirements,\n\t\t\tsettlement: settleResult,\n\t\t};\n\t\tconst innerResponse = await handler(request, context);\n\t\tconst finalResponse = withPaymentResponseHeader(innerResponse, settleResult);\n\n\t\t// 7b. Record the settled response for replay-on-duplicate (best-effort —\n\t\t// fund-correctness is guaranteed on-chain regardless of the store).\n\t\tif (idempotency !== null && idemKey !== null && lease !== null) {\n\t\t\tconst snapshot = await snapshotResponse(finalResponse, idempotency.maxSnapshotBytes);\n\t\t\tconst record = buildRecord(\n\t\t\t\tidemKey,\n\t\t\t\tsettleResult,\n\t\t\t\tmatchedRequirements,\n\t\t\t\tauth?.validBefore ?? 0n,\n\t\t\t\tidempotency.fallbackTtlSeconds,\n\t\t\t\tsnapshot,\n\t\t\t);\n\t\t\tif (record !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idempotency.store.complete(idemKey, record, lease);\n\t\t\t\t} catch {\n\t\t\t\t\t// Completing the cache is best-effort; on-chain nonce is the backstop.\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\t}\n\t\t}\n\t\treturn finalResponse;\n\t};\n}\n"]}
1
+ {"version":3,"sources":["../../src/chains/avalanche.ts","../../src/chains/ethereum.ts","../../src/chains/kaia.ts","../../src/chains/polygon.ts","../../src/chains/index.ts","../../src/tokens/jpyc.ts","../../src/tokens/known-assets.ts","../../src/signer/errors.ts","../../src/signer/gate.ts","../../src/x402/errors.ts","../../src/tokens/asset-domain.ts","../../src/tokens/eip3009.ts","../../src/x402/types.ts","../../src/x402/client.ts","../../src/x402/encoding.ts","../../src/observability/hooks.ts","../../src/x402/facilitator.ts","../../src/x402/fetch.ts","../../src/x402/payment-requirements.ts","../../src/idempotency/errors.ts","../../src/idempotency/record.ts","../../src/idempotency/store.ts","../../src/x402/server.ts"],"names":["viemAvalanche","viemAvalancheFuji","viemMainnet","viemSepolia","viemKaia","viemKairos","viemPolygon","viemPolygonAmoy","getAddress","isAddress","keccak256","stringToHex","parseSignature","recoverTypedDataAddress","paymentRequired","UINT256_MAX","UINT256_DECIMAL","assertAddress","headers"],"mappings":";;;;;;AAaO,IAAM,SAAA,GAAY;AAAA,EACxB,GAAGA,gBAAA;AAAA,EACH,SAAA,EAAW,KAAA;AAAA,EACX,oBAAA,EAAsB,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A;AAAA,QACA,mBAAA;AAAA,QACA,MAAM,WAAA,IAAe,EAAA;AAAA,QACrB,WAAA,CAAY,kBAAA;AAAA,QACZ;AAAA,OACD;AACA,MAAA,IAAI,WAAW,IAAA,EAAM;AACpB,QAAA,IAAI;AACH,UAAA,MAAM,WAAA,CAAY,KAAA,CAAM,QAAA,CAAS,OAAA,EAAS,QAAQ,KAAK,CAAA;AAAA,QACxD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACD,CAAA,MAAO;AACN,QAAA,MAAM,YAAA,CAAa,WAAA,EAAa,OAAA,EAAS,KAAK,CAAA;AAAA,MAC/C;AAAA,IACD;AACA,IAAA,OAAO,aAAA;AAAA,EACR,CAAA;AACD","file":"index.cjs","sourcesContent":["import { avalanche as viemAvalanche, avalancheFuji as viemAvalancheFuji } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Avalanche C-Chain — priority 3 production chain.\n *\n * Snowman BFT gives sub-`2 s` **deterministic finality**, so\n * `defaultConfirmations` of `2` is ample — deep confirmations add latency for\n * no extra safety. JPYC is live at the same address as the other chains.\n *\n * The x402 EOA-payer path works today; the smart-account path via ZeroDev is\n * not yet verified on Avalanche.\n */\nexport const avalanche = {\n\t...viemAvalanche,\n\tisTestnet: false,\n\tdefaultConfirmations: 2,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n\n/**\n * Avalanche Fuji testnet. JPYC is live at the same address as the other chains\n * (confirmed via a read-only on-chain `name()` == \"JPY Coin\" / `symbol()` ==\n * \"JPYC\" check, 2026-05-31). Real x402 settlement here has not been exercised.\n */\nexport const avalancheFuji = {\n\t...viemAvalancheFuji,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n","import { mainnet as viemMainnet, sepolia as viemSepolia } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Ethereum mainnet — priority 4 production chain (institutional use cases).\n *\n * Casper FFG finalises in epochs (~12.8 min). `defaultConfirmations` of `32`\n * (~6.4 min at ~12 s blocks) gives finalised-grade safety. **Do NOT use\n * Polygon's `4` here** — 4 blocks (~48 s) is nowhere near finalised, and would\n * re-open the settle-reorg gap (threat 2.8). The facilitator auto-sizes\n * `receiptTimeoutMs` from this depth (~10 min), so the default does not time\n * out. JPYC is live at the same address as the other chains.\n */\nexport const ethereum = {\n\t...viemMainnet,\n\tisTestnet: false,\n\tdefaultConfirmations: 32,\n\tblockTimeMs: 12_000,\n} satisfies KawaseChain;\n\n/**\n * Sepolia — Ethereum testnet. JPYC is live at the same address as the other\n * chains (confirmed via a read-only on-chain `name()` == \"JPY Coin\" / `symbol()`\n * == \"JPYC\" check, 2026-05-31). Real x402 settlement here has not been exercised.\n */\nexport const sepolia = {\n\t...viemSepolia,\n\tisTestnet: true,\n\tdefaultConfirmations: 4,\n\tblockTimeMs: 12_000,\n} satisfies KawaseChain;\n","import { kaia as viemKaia, kairos as viemKairos } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Kaia mainnet — priority 2 production chain.\n *\n * Kaia (Klaytn + Finschia) runs IBFT consensus with **immediate finality** — a\n * single confirmed block is final — so `defaultConfirmations` is `1` (do NOT\n * copy Polygon's `4`). JPYC is live at the same address as the other chains\n * (`src/tokens/jpyc.ts`).\n *\n * Note: ZeroDev does not support Kaia, so the **smart-account path** (session\n * keys, sponsored UserOps) is not yet available here — it is planned via\n * Pimlico (M5-3 Phase 2). The **x402 EOA-payer path** works today.\n */\nexport const kaia = {\n\t...viemKaia,\n\tisTestnet: false,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 1_000,\n} satisfies KawaseChain;\n\n/**\n * Kairos — Kaia testnet. JPYC is available via the Kaia faucet at the same\n * address as mainnet; suitable for the same Amoy→Polygon-style testnet→mainnet\n * verification pattern.\n */\nexport const kairos = {\n\t...viemKairos,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 1_000,\n} satisfies KawaseChain;\n","import { polygon as viemPolygon, polygonAmoy as viemPolygonAmoy } from \"viem/chains\";\nimport type { KawaseChain } from \"./types\";\n\n/**\n * Polygon mainnet — priority 1 production chain.\n *\n * Built on viem's `polygon` definition (official RPC URLs, block explorers,\n * and `POL` native currency) plus kawasekit metadata. Polygon PoS is\n * probabilistic; the default `4` confirmations ≈ ~8 s of soft finality.\n */\nexport const polygon = {\n\t...viemPolygon,\n\tisTestnet: false,\n\tdefaultConfirmations: 4,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n\n/**\n * Polygon Amoy testnet — the primary kawasekit development target.\n *\n * Built on viem's `polygonAmoy` definition. JPYC is also live on Amoy at the\n * same address as mainnet; see `src/tokens/jpyc.ts`.\n */\nexport const polygonAmoy = {\n\t...viemPolygonAmoy,\n\tisTestnet: true,\n\tdefaultConfirmations: 1,\n\tblockTimeMs: 2_000,\n} satisfies KawaseChain;\n","import { avalanche, avalancheFuji } from \"./avalanche\";\nimport { ethereum, sepolia } from \"./ethereum\";\nimport { kaia, kairos } from \"./kaia\";\nimport { polygon, polygonAmoy } from \"./polygon\";\nimport { type KawaseChain, zerodevRpcUrl } from \"./types\";\n\nexport {\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\ttype KawaseChain,\n\tkaia,\n\tkairos,\n\tpolygon,\n\tpolygonAmoy,\n\tsepolia,\n\tzerodevRpcUrl,\n};\n\n/**\n * All chains kawasekit supports, in priority order (CLAUDE.md chain priority:\n * Polygon → Kaia → Avalanche → Ethereum, each with its testnet).\n *\n * Exposed as a `readonly` tuple — **not** a `Map` — so that bundlers can\n * tree-shake chains a consumer never references.\n *\n * JPYC liveness is a separate axis (`src/tokens/jpyc.ts`): a chain can be\n * supported here while JPYC is not yet live on it (Avalanche Fuji / Sepolia).\n *\n * @example\n * ```ts\n * import { supportedChains } from \"kawasekit\";\n *\n * for (const chain of supportedChains) {\n * \tconsole.log(chain.id, chain.name);\n * }\n * ```\n */\nexport const supportedChains = [\n\tpolygon,\n\tpolygonAmoy,\n\tkaia,\n\tkairos,\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\tsepolia,\n] as const;\n\n/**\n * Union of every chain ID kawasekit supports\n * (`137 | 80002 | 8217 | 1001 | 43114 | 43113 | 1 | 11155111`).\n *\n * Derived from {@link supportedChains}, so adding a chain there extends this\n * type automatically.\n */\nexport type SupportedChainId = (typeof supportedChains)[number][\"id\"];\n\n/** A single member of {@link supportedChains}, with its literal `id`. */\ntype SupportedChain = (typeof supportedChains)[number];\n\n/**\n * Internal chain lookup, built once at module scope.\n *\n * This `Map` is an implementation detail and is intentionally **not**\n * exported: the public API exposes the {@link supportedChains} tuple instead,\n * so importing one chain does not pull in all of them.\n */\nconst chainsById: ReadonlyMap<number, SupportedChain> = new Map(\n\tsupportedChains.map((chain) => [chain.id, chain]),\n);\n\n/**\n * Error thrown when a chain ID kawasekit does not support is requested.\n *\n * @example\n * ```ts\n * import { ChainNotSupportedError, getChain } from \"kawasekit\";\n *\n * try {\n * \tgetChain(1);\n * } catch (error) {\n * \tif (error instanceof ChainNotSupportedError) {\n * \t\tconsole.error(error.message);\n * \t}\n * }\n * ```\n */\nexport class ChainNotSupportedError extends Error {\n\tconstructor(chainId: number) {\n\t\tconst supported = supportedChains.map((chain) => chain.id).join(\", \");\n\t\tsuper(\n\t\t\t`Chain ID ${chainId} is not supported by kawasekit. ` + `Supported chain IDs: ${supported}.`,\n\t\t);\n\t\tthis.name = \"ChainNotSupportedError\";\n\t}\n}\n\n/**\n * Type guard that narrows an arbitrary chain ID to a {@link SupportedChainId}.\n *\n * @param chainId - The numeric chain ID to test.\n * @returns `true` if kawasekit supports this chain ID.\n *\n * @example\n * ```ts\n * import { isSupportedChainId } from \"kawasekit\";\n *\n * const id = 80002;\n * if (isSupportedChainId(id)) {\n * \t// `id` is now narrowed to SupportedChainId\n * }\n * ```\n */\nexport function isSupportedChainId(chainId: number): chainId is SupportedChainId {\n\treturn chainsById.has(chainId);\n}\n\n/**\n * Looks up a supported chain by its numeric chain ID.\n *\n * The returned chain's `id` is narrowed to {@link SupportedChainId}.\n *\n * @param chainId - The numeric chain ID to look up.\n * @returns The matching {@link KawaseChain}.\n * @throws {ChainNotSupportedError} If `chainId` is not supported.\n *\n * @example\n * ```ts\n * import { getChain } from \"kawasekit\";\n *\n * const chain = getChain(80002); // Polygon Amoy\n * console.log(chain.name);\n * ```\n */\nexport function getChain(chainId: number): SupportedChain {\n\tconst chain = chainsById.get(chainId);\n\tif (chain === undefined) {\n\t\tthrow new ChainNotSupportedError(chainId);\n\t}\n\treturn chain;\n}\n","/**\n * JPYC stablecoin metadata, deployments, and ABI.\n *\n * JPYC is a Japanese yen-pegged stablecoin issued by JPYC Inc. under the\n * revised Payment Services Act as 電子決済手段 (electronic payment\n * instrument). The new (\"v2\") JPYC, launched 2025-10, lives at the same\n * address on every chain where it is deployed.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport {\n\tavalanche,\n\tavalancheFuji,\n\tethereum,\n\tkaia,\n\tkairos,\n\tpolygon,\n\tpolygonAmoy,\n\tsepolia,\n} from \"../chains\";\n\n/** ERC-20 decimals for JPYC. Constant across every chain. */\nexport const JPYC_DECIMALS = 18;\n\n/**\n * EIP-712 domain hint for off-chain authorization signing (EIP-3009, EIP-2612).\n *\n * The real JPYC contract does not expose `version()` publicly — it lives in an\n * `internal VERSION` state variable set during proxy initialization. The\n * canonical value is `\"1\"`, matching the FiatToken lineage; the\n * {@link signTransferWithAuthorization} helper accepts an override if a future\n * deployment changes this.\n *\n * `name` is \"JPY Coin\" — the on-chain `name()` value on every live deployment.\n */\nexport const JPYC_EIP712_DOMAIN_HINT = {\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n/**\n * Address shared by every live JPYC deployment.\n *\n * Verified on:\n * - Ethereum : https://etherscan.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * - Polygon : https://polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Polygon Amoy : https://amoy.polygonscan.com/token/0xe7c3d8c9a439fede00d2600032d5db0be71c3c29\n * - Avalanche : https://snowtrace.io/token/0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n *\n * Do NOT confuse with the legacy 前払式支払手段 JPYC at `0x431D5dFF...`.\n */\nexport const JPYC_V2_ADDRESS: Address = \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\";\n\n/** A JPYC deployment on a single chain. */\nexport interface JpycDeployment {\n\treadonly chainId: SupportedChainId;\n\treadonly address: Address;\n\t/** `true` if the token is live on this chain right now. */\n\treadonly isLive: boolean;\n}\n\n/**\n * JPYC deployments keyed by chain.\n *\n * JPYC v2 uses the **same address** (`JPYC_V2_ADDRESS`) on every chain where it\n * is live. `isLive` is the separate \"is JPYC actually deployed here yet?\" axis.\n * All eight supported chains are live at this address: the four mainnets\n * (Polygon, Kaia, Avalanche, Ethereum) + Amoy + Kairos + Avalanche Fuji +\n * Sepolia. Kaia/Kairos/Avalanche/Fuji/Sepolia were confirmed by a read-only\n * on-chain check (`name() == \"JPY Coin\"`, `symbol() == \"JPYC\"` at `0xE7C3…`,\n * 2026-05-31); Polygon/Amoy/Ethereum are established. `isLive: false` + the\n * {@link JpycNotAvailableError} path remain for any future chain added before\n * its JPYC deployment lands.\n */\nexport const jpycDeployments: { readonly [chainId in SupportedChainId]: JpycDeployment } = {\n\t[polygon.id]: { chainId: polygon.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[polygonAmoy.id]: { chainId: polygonAmoy.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[kaia.id]: { chainId: kaia.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[kairos.id]: { chainId: kairos.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[avalanche.id]: { chainId: avalanche.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[ethereum.id]: { chainId: ethereum.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[avalancheFuji.id]: { chainId: avalancheFuji.id, address: JPYC_V2_ADDRESS, isLive: true },\n\t[sepolia.id]: { chainId: sepolia.id, address: JPYC_V2_ADDRESS, isLive: true },\n};\n\n/**\n * Thrown when JPYC is not deployed on the requested chain.\n *\n * Today this is unreachable (every {@link SupportedChainId} has a live\n * deployment), but the error class is exported for future chains (Kaia) where\n * JPYC is still in development.\n */\nexport class JpycNotAvailableError extends Error {\n\tconstructor(chainId: number) {\n\t\tsuper(`JPYC is not yet deployed on chain ID ${chainId}.`);\n\t\tthis.name = \"JpycNotAvailableError\";\n\t}\n}\n\n/**\n * Returns the JPYC contract address for a kawasekit-supported chain.\n *\n * @param chainId - A {@link SupportedChainId}.\n * @returns The JPYC contract address on that chain.\n * @throws {JpycNotAvailableError} If JPYC is not live on the chain.\n *\n * @example\n * ```ts\n * import { getJpycAddress, polygonAmoy } from \"kawasekit\";\n *\n * const address = getJpycAddress(polygonAmoy.id);\n * ```\n */\nexport function getJpycAddress(chainId: SupportedChainId): Address {\n\tconst deployment = jpycDeployments[chainId];\n\tif (!deployment.isLive) {\n\t\tthrow new JpycNotAvailableError(chainId);\n\t}\n\treturn deployment.address;\n}\n\n/**\n * Minimal JPYC ABI: ERC-20 + EIP-3009 surface that kawasekit needs.\n *\n * Excludes permit / mint / blocklist / pause — kawasekit only reads balance,\n * sends `transfer()` via UserOp, and constructs / submits EIP-3009\n * authorizations. Bringing in the full FiatTokenV1 ABI would be wasted bytes.\n */\nexport const jpycAbi = [\n\t// ----- ERC-20 read -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"name\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"symbol\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"string\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"decimals\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint8\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"totalSupply\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"balanceOf\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [{ name: \"account\", type: \"address\" }],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"allowance\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\" },\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"uint256\" }],\n\t},\n\t// ----- ERC-20 write -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transfer\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferFrom\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"approve\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"spender\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- EIP-3009 -----\n\t{\n\t\ttype: \"function\",\n\t\tname: \"transferWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"receiveWithAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\" },\n\t\t\t{ name: \"to\", type: \"address\" },\n\t\t\t{ name: \"value\", type: \"uint256\" },\n\t\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"cancelAuthorization\",\n\t\tstateMutability: \"nonpayable\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t\t{ name: \"v\", type: \"uint8\" },\n\t\t\t{ name: \"r\", type: \"bytes32\" },\n\t\t\t{ name: \"s\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [],\n\t},\n\t{\n\t\ttype: \"function\",\n\t\tname: \"authorizationState\",\n\t\tstateMutability: \"view\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t\t],\n\t\toutputs: [{ name: \"\", type: \"bool\" }],\n\t},\n\t// ----- Events kawasekit needs to decode -----\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Transfer\",\n\t\tinputs: [\n\t\t\t{ name: \"from\", type: \"address\", indexed: true },\n\t\t\t{ name: \"to\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"Approval\",\n\t\tinputs: [\n\t\t\t{ name: \"owner\", type: \"address\", indexed: true },\n\t\t\t{ name: \"spender\", type: \"address\", indexed: true },\n\t\t\t{ name: \"value\", type: \"uint256\", indexed: false },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationUsed\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n\t{\n\t\ttype: \"event\",\n\t\tname: \"AuthorizationCanceled\",\n\t\tinputs: [\n\t\t\t{ name: \"authorizer\", type: \"address\", indexed: true },\n\t\t\t{ name: \"nonce\", type: \"bytes32\", indexed: true },\n\t\t],\n\t},\n] as const;\n","/**\n * Known-asset registry for {@link createX402PaymentSigner}'s\n * `asset: { kind: \"known\", id }` discriminated-union branch.\n *\n * kawasekit only ships pinned EIP-712 domain definitions for assets it has\n * verified empirically against the deployed contracts. Adding a new entry\n * here requires citing the source-file + line reference for the contract\n * that owns the `name` / `version` (so the next reviewer can spot-check the\n * claim, the same discipline `docs/THREAT_MODEL.md` §0 demands of any ✅\n * verdict that delegates to an out-of-scope component).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress } from \"viem\";\nimport { JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS } from \"./jpyc\";\n\n/** Known asset identifiers. New entries must update this union AND the table. */\nexport type KnownAssetId = \"jpyc-v2\";\n\n/** Fully-pinned EIP-712 domain for a known asset. */\nexport interface KnownAssetDomain {\n\treadonly id: KnownAssetId;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Canonical table. Lookups go through {@link getKnownAssetDomain}, which\n * returns a frozen copy so callers cannot mutate the registry.\n *\n * `verifyingContract` is the multi-chain canonical address — JPYC v2 is the\n * same address on Ethereum / Polygon (mainnet + Amoy) / Avalanche. The\n * signer cross-checks `requirements.asset` against this value at sign time,\n * so a server advertising a different `asset` is rejected before any\n * signature is produced.\n *\n * JPYC v2 domain: `name = \"JPY Coin\"`, `version = \"1\"`. Source of truth is\n * the deployed contract's `eip712Domain()` view — verified empirically and\n * also cached in `src/tokens/jpyc.ts:JPYC_EIP712_DOMAIN_HINT`.\n */\nconst KNOWN_ASSETS: ReadonlyArray<KnownAssetDomain> = [\n\t{\n\t\tid: \"jpyc-v2\",\n\t\tname: JPYC_EIP712_DOMAIN_HINT.name,\n\t\tversion: JPYC_EIP712_DOMAIN_HINT.version,\n\t\tverifyingContract: getAddress(JPYC_V2_ADDRESS),\n\t},\n];\n\n/**\n * Look up a known asset's pinned EIP-712 domain by id.\n *\n * @returns The domain, or `undefined` if the id is not in the registry.\n *\n * @example\n * ```ts\n * import { getKnownAssetDomain } from \"kawasekit\";\n *\n * const jpyc = getKnownAssetDomain(\"jpyc-v2\");\n * if (jpyc === undefined) throw new Error(\"unreachable\");\n * console.log(jpyc.verifyingContract); // 0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\n * ```\n */\nexport function getKnownAssetDomain(id: KnownAssetId): KnownAssetDomain | undefined {\n\treturn KNOWN_ASSETS.find((entry) => entry.id === id);\n}\n\n/** List every known asset id (for diagnostics / error messages). */\nexport function listKnownAssetIds(): readonly KnownAssetId[] {\n\treturn KNOWN_ASSETS.map((entry) => entry.id);\n}\n","/**\n * PolicyGatedSigner error types.\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown for a construction-time / configuration error in a PolicyGatedSigner\n * adapter — e.g. a `local` signer constructed without the required\n * `acknowledgeAdvisory: true`, or a non-bypassable signer asserted on an\n * advisory one (`assertNonBypassable`). Policy *denials* are NOT errors — they\n * are returned as a typed {@link PolicyRejection} in {@link SignResult}.\n *\n * @example\n * ```ts\n * import { createLocalPolicyGatedSigner, PolicyGatedSignerConfigError } from \"kawasekit/signer\";\n *\n * try {\n * // @ts-expect-error — acknowledgeAdvisory is required\n * createLocalPolicyGatedSigner({ account, policy, asset });\n * } catch (error) {\n * if (error instanceof PolicyGatedSignerConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class PolicyGatedSignerConfigError extends Error {\n\t/** The offending config field. */\n\treadonly field: string;\n\t/** Short machine-readable reason. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid PolicyGatedSigner config (${field}): ${reason}`, options);\n\t\tthis.name = \"PolicyGatedSignerConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n","/**\n * The enforcement-level type-gate — the compile-time (and runtime) mechanism\n * that prevents an advisory signer from being substituted for an enforcing one.\n *\n * @packageDocumentation\n */\n\nimport { PolicyGatedSignerConfigError } from \"./errors\";\nimport type { NonBypassableEnforcement, PolicyGatedSigner } from \"./types\";\n\n/**\n * Compile-time gate: accepts only a non-bypassable signer\n * (`cryptographic` | `hardware`). Passing an `advisory` (or `integrator`) signer\n * is a **compile error**, because `PolicyGatedSigner<\"advisory\">` is not\n * assignable to `PolicyGatedSigner<NonBypassableEnforcement>` (covariant `E`).\n *\n * Use it at the boundary of a bounded/regulated flow so wiring an advisory\n * signer into it fails the build, not silently at runtime.\n *\n * @example\n * ```ts\n * function payBounded(signer: PolicyGatedSigner<NonBypassableEnforcement>) { ... }\n *\n * requireNonBypassable(mpc2pSigner); // ✓ ok — cryptographic\n * // requireNonBypassable(localSigner); // ✗ compile error — advisory\n * ```\n */\nexport function requireNonBypassable<E extends NonBypassableEnforcement>(\n\tsigner: PolicyGatedSigner<E>,\n): PolicyGatedSigner<E> {\n\treturn signer;\n}\n\n/**\n * Runtime mirror of {@link requireNonBypassable}, for plain-JS call sites and as\n * defense-in-depth. Throws {@link PolicyGatedSignerConfigError} if the signer is\n * advisory/integrator (i.e. bypassable). On success, narrows the signer type to\n * {@link NonBypassableEnforcement}.\n */\nexport function assertNonBypassable(\n\tsigner: PolicyGatedSigner,\n): asserts signer is PolicyGatedSigner<NonBypassableEnforcement> {\n\tif (signer.enforcement === \"advisory\" || signer.enforcement === \"integrator\") {\n\t\tthrow new PolicyGatedSignerConfigError(\n\t\t\t\"enforcement\",\n\t\t\t`expected a non-bypassable signer (cryptographic | hardware), got \"${signer.enforcement}\" — an ${signer.enforcement} signer's policy can be bypassed by a key-holder`,\n\t\t);\n\t}\n}\n","/**\n * Typed errors thrown by the `kawasekit/x402` modules.\n *\n * Centralised so that consumers can `instanceof`-discriminate without importing\n * deep paths. Additional error classes are added here as the corresponding\n * modules come online (server, facilitator, …).\n *\n * @packageDocumentation\n */\n\nimport type { PolicyRejection } from \"../signer/types\";\n\n/**\n * Thrown when an x402 wire-format payload is malformed: invalid base64, invalid\n * JSON, or a value that cannot represent the expected schema.\n *\n * Carries the offending header / context name so callers can produce actionable\n * log lines without re-parsing the message string.\n *\n * @example\n * ```ts\n * import { decodePaymentSignatureHeader, X402InvalidPayloadError } from \"kawasekit\";\n *\n * try {\n * decodePaymentSignatureHeader(headerValue);\n * } catch (error) {\n * if (error instanceof X402InvalidPayloadError) {\n * console.warn(`reject ${error.context}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidPayloadError extends Error {\n\t/** Logical name of the payload that failed (e.g. `\"PAYMENT-SIGNATURE\"`). */\n\treadonly context: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(context: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${context} payload: ${reason}`, options);\n\t\tthis.name = \"X402InvalidPayloadError\";\n\t\tthis.context = context;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when an x402 SDK construction-time configuration is invalid: an\n * unknown `asset.kind`, a known asset id that kawasekit does not ship a\n * domain for, missing required fields on an `unsafeOverride`, etc.\n *\n * Distinct from {@link X402InvalidPayloadError} (which describes wire-format\n * problems): config errors are integrator bugs, not adversarial inputs.\n *\n * @example\n * ```ts\n * import { createX402PaymentSigner, X402InvalidConfigError } from \"kawasekit\";\n *\n * try {\n * createX402PaymentSigner({\n * network: \"testnet\",\n * account,\n * // @ts-expect-error — kind: \"foo\" is not a known kind\n * asset: { kind: \"foo\" },\n * });\n * } catch (error) {\n * if (error instanceof X402InvalidConfigError) {\n * console.error(`${error.field}: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402InvalidConfigError extends Error {\n\t/** Logical name of the config field that failed (e.g. `\"asset\"`). */\n\treadonly field: string;\n\t/** Short machine-readable reason code. */\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid ${field} config: ${reason}`, options);\n\t\tthis.name = \"X402InvalidConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown by {@link createX402PaymentSigner} (the `signer` variant) when the bound\n * `PolicyGatedSigner` refuses to sign — i.e. its `sign()` returned\n * `{ ok: false }`. Carries the typed {@link PolicyRejection} so callers can\n * branch on `reason`. This is the policy-driven analog of the `account`\n * variant's `maxAmountPerSign` throw ({@link X402InvalidPayloadError}): the\n * `X402PaymentSigner.sign()` surface returns a payload or throws, unchanged.\n *\n * @example\n * ```ts\n * import { X402PolicyRejectedError } from \"kawasekit\";\n *\n * try {\n * await signer.sign({ paymentRequirements });\n * } catch (error) {\n * if (error instanceof X402PolicyRejectedError) {\n * console.warn(`policy refused: ${error.reason}`);\n * }\n * }\n * ```\n */\nexport class X402PolicyRejectedError extends Error {\n\t/** The policy rejection reason (e.g. `\"amount_exceeds_per_sign\"`). */\n\treadonly reason: PolicyRejection[\"reason\"];\n\t/** The full typed rejection (its `detail` never contains the nonce or signature). */\n\treadonly rejection: PolicyRejection;\n\n\tconstructor(rejection: PolicyRejection, options?: { cause?: unknown }) {\n\t\tsuper(`x402 payment rejected by policy: ${rejection.reason} (${rejection.detail})`, options);\n\t\tthis.name = \"X402PolicyRejectedError\";\n\t\tthis.reason = rejection.reason;\n\t\tthis.rejection = rejection;\n\t}\n}\n","/**\n * EIP-712 asset-domain resolution for x402 / EIP-3009 signing.\n *\n * Construction-time pinning of the EIP-712 domain (`name` / `version` /\n * `verifyingContract`) a signer will use. The integrator declares an\n * {@link X402AssetParam} — either a kawasekit-maintained `known` asset or a\n * loud `unsafeOverride` — and {@link resolveAssetParam} resolves it to a pinned\n * {@link ResolvedAsset}. The signer then trusts only this pinned domain and\n * refuses to sign for a mismatched advertised asset (Threat 1.4: misadvertised\n * EIP-712 domain).\n *\n * Token-domain concern, reused by both the x402 signer (`src/x402/client.ts`)\n * and the M6 PolicyGatedSigner (`src/signer/`).\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { X402InvalidConfigError } from \"../x402/errors\";\nimport type { Eip3009Domain } from \"./eip3009\";\nimport {\n\tgetKnownAssetDomain,\n\ttype KnownAssetDomain,\n\ttype KnownAssetId,\n\tlistKnownAssetIds,\n} from \"./known-assets\";\n\n/** EIP-712 token domain `name` / `version` pair. */\nexport interface X402TokenDomain {\n\treadonly name: string;\n\treadonly version: string;\n}\n\n/**\n * Asset binding for {@link createX402PaymentSigner} and the M6 PolicyGatedSigner.\n * Required, discriminated.\n *\n * **Default-on whitelist**: integrators MUST declare which asset they intend\n * to sign for. The `known` branch references a kawasekit-maintained\n * whitelist (see `src/tokens/known-assets.ts`); the `unsafeOverride` branch\n * is the deliberate escape hatch for any other asset and is named loudly so\n * it survives a code review. Either way, the signer pins the EIP-712 domain\n * at construction time and refuses to sign if `paymentRequirements.asset`\n * disagrees with the pinned `verifyingContract`.\n *\n * Closes Threat 1.4 (misadvertised EIP-712 domain): the server's advertised\n * `extra.name` / `extra.version` and `asset` are all ignored for signing\n * purposes — the signer trusts only what the integrator declared here.\n */\nexport type X402AssetParam =\n\t| {\n\t\t\t/** Use a kawasekit-maintained pinned EIP-712 domain. */\n\t\t\treadonly kind: \"known\";\n\t\t\t/** The asset id to pin. See {@link KnownAssetId} for the registry. */\n\t\t\treadonly id: KnownAssetId;\n\t }\n\t| {\n\t\t\t/**\n\t\t\t * Use a caller-supplied EIP-712 domain for an asset NOT on the\n\t\t\t * kawasekit whitelist. The name is deliberately loud — pick this\n\t\t\t * branch only when you have separately audited the contract and its\n\t\t\t * `eip712Domain()` output.\n\t\t\t */\n\t\t\treadonly kind: \"unsafeOverride\";\n\t\t\treadonly domain: {\n\t\t\t\treadonly name: string;\n\t\t\t\treadonly version: string;\n\t\t\t\treadonly verifyingContract: Address;\n\t\t\t};\n\t };\n\n/** Construction-time resolution of an {@link X402AssetParam} to a pinned domain. */\nexport interface ResolvedAsset {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly verifyingContract: Address;\n}\n\n/**\n * Resolve an {@link X402AssetParam} to a pinned {@link ResolvedAsset}.\n *\n * Throws {@link X402InvalidConfigError} for an unknown `known` id or a malformed\n * `unsafeOverride` domain. Pure / construction-time — no chain RPC.\n */\nexport function resolveAssetParam(asset: X402AssetParam): ResolvedAsset {\n\tif (asset.kind === \"known\") {\n\t\tconst entry: KnownAssetDomain | undefined = getKnownAssetDomain(asset.id);\n\t\tif (entry === undefined) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.id\",\n\t\t\t\t`unknown asset id ${JSON.stringify(asset.id)}. Supported: ${listKnownAssetIds()\n\t\t\t\t\t.map((id) => JSON.stringify(id))\n\t\t\t\t\t.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: entry.name,\n\t\t\tversion: entry.version,\n\t\t\tverifyingContract: entry.verifyingContract,\n\t\t};\n\t}\n\tif (asset.kind === \"unsafeOverride\") {\n\t\tconst { domain } = asset;\n\t\tif (typeof domain.name !== \"string\" || domain.name === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.name\",\n\t\t\t\t\"`unsafeOverride.domain.name` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (typeof domain.version !== \"string\" || domain.version === \"\") {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.version\",\n\t\t\t\t\"`unsafeOverride.domain.version` must be a non-empty string\",\n\t\t\t);\n\t\t}\n\t\tif (!isAddress(domain.verifyingContract, { strict: false })) {\n\t\t\tthrow new X402InvalidConfigError(\n\t\t\t\t\"asset.domain.verifyingContract\",\n\t\t\t\t`\\`unsafeOverride.domain.verifyingContract\\` must be a valid address, got ${JSON.stringify(domain.verifyingContract)}`,\n\t\t\t);\n\t\t}\n\t\treturn {\n\t\t\tname: domain.name,\n\t\t\tversion: domain.version,\n\t\t\tverifyingContract: getAddress(domain.verifyingContract),\n\t\t};\n\t}\n\t// Defensive: TS exhaustiveness guarantees this is unreachable at compile\n\t// time, but a JS consumer could smuggle through an unknown kind.\n\tconst exhaustive = asset as { kind: string };\n\tthrow new X402InvalidConfigError(\n\t\t\"asset.kind\",\n\t\t`unsupported kind ${JSON.stringify(exhaustive.kind)}. Expected \"known\" or \"unsafeOverride\".`,\n\t);\n}\n\n/**\n * Assemble the EIP-712 {@link Eip3009Domain} from a construction-time pinned\n * {@link ResolvedAsset} and the runtime `chainId`.\n *\n * The single place that maps `(pinned asset, chainId) -> domain`, so every\n * signing path (`src/x402/client.ts`, `src/signer/`) builds the domain\n * identically — the domain half of the EIP-712 single-source-of-truth the\n * `mpc-2p` backend relies on (RFC M6-1 §4.5, H1). `name` / `version` /\n * `verifyingContract` come from the pinned asset; only `chainId` is per-request.\n */\nexport function resolvedAssetToEip3009Domain(asset: ResolvedAsset, chainId: number): Eip3009Domain {\n\treturn {\n\t\tname: asset.name,\n\t\tversion: asset.version,\n\t\tchainId,\n\t\tverifyingContract: asset.verifyingContract,\n\t};\n}\n","/**\n * EIP-3009 typed-data builders and signing helpers.\n *\n * Token-agnostic: works for any EIP-3009-compliant token (JPYC, USDC, USDP,\n * Centre FiatToken family). Pure off-chain construction — no chain RPC, no\n * submission. Submission is the caller's job (M3 x402 flow, or arbitrary\n * gas-paying relayer).\n *\n * @packageDocumentation\n */\n\nimport {\n\ttype Account,\n\ttype Address,\n\tgetAddress,\n\ttype Hex,\n\tkeccak256,\n\tparseSignature,\n\tstringToHex,\n} from \"viem\";\n\n// ---------------------------------------------------------------------------\n// Domain & typed-data shapes\n// ---------------------------------------------------------------------------\n\n/**\n * EIP-712 domain for an EIP-3009-compliant token.\n *\n * `name` and `version` MUST match the values the token used when computing\n * its `DOMAIN_SEPARATOR`. For JPYC see {@link JPYC_EIP712_DOMAIN_HINT}.\n */\nexport interface Eip3009Domain {\n\treadonly name: string;\n\treadonly version: string;\n\treadonly chainId: number;\n\treadonly verifyingContract: Address;\n}\n\n/** Message body for {@link signTransferWithAuthorization}. */\nexport interface TransferWithAuthorizationMessage {\n\treadonly from: Address;\n\treadonly to: Address;\n\treadonly value: bigint;\n\treadonly validAfter: bigint;\n\treadonly validBefore: bigint;\n\t/** 32-byte random nonce. Generate with {@link generateAuthorizationNonce}. */\n\treadonly nonce: Hex;\n}\n\n/** Message body for {@link signReceiveWithAuthorization}. */\nexport type ReceiveWithAuthorizationMessage = TransferWithAuthorizationMessage;\n\n/** Message body for {@link signCancelAuthorization}. */\nexport interface CancelAuthorizationMessage {\n\treadonly authorizer: Address;\n\treadonly nonce: Hex;\n}\n\n/**\n * A signed EIP-3009 authorization, ready to be passed to the token's\n * `*WithAuthorization` entrypoint as `(v, r, s)`.\n */\nexport interface SignedAuthorization<TMessage> {\n\treadonly signature: Hex;\n\treadonly v: number;\n\treadonly r: Hex;\n\treadonly s: Hex;\n\treadonly domain: Eip3009Domain;\n\treadonly message: TMessage;\n}\n\n// ---------------------------------------------------------------------------\n// EIP-712 type definitions (must match EIP-3009 byte-for-byte)\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical EIP-712 `TransferWithAuthorization` type definition.\n *\n * This is the **single source of truth** for the typed-data structure (field\n * names, types, and order) that EIP-3009 hashes and `ecrecover` verifies.\n * Exported so out-of-process / cross-language consumers — notably the `mpc-2p`\n * co-signer backend (RFC M6-1 §4.5, H1) — bind to this exact definition (or\n * codegen from it) instead of re-declaring it, and so the digest the policy\n * gates on is provably the digest the chain verifies (see the digest-conformance\n * corpus in `__fixtures__/eip3009-digest.vectors.json`).\n */\nexport const transferWithAuthorizationTypes = {\n\tTransferWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n/** Canonical EIP-712 `ReceiveWithAuthorization` types. See {@link transferWithAuthorizationTypes}. */\nexport const receiveWithAuthorizationTypes = {\n\tReceiveWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n/** Canonical EIP-712 `CancelAuthorization` types. See {@link transferWithAuthorizationTypes}. */\nexport const cancelAuthorizationTypes = {\n\tCancelAuthorization: [\n\t\t{ name: \"authorizer\", type: \"address\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Generates a cryptographically random 32-byte EIP-3009 nonce.\n *\n * The nonce only needs to be unique per `(authorizer, contract)` — duplicates\n * across different tokens are harmless because the contract scopes them.\n *\n * @example\n * ```ts\n * import { generateAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = generateAuthorizationNonce();\n * ```\n */\nexport function generateAuthorizationNonce(): Hex {\n\tconst bytes = new Uint8Array(32);\n\tcrypto.getRandomValues(bytes);\n\treturn `0x${Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")}` as Hex;\n}\n\n/** Domain tag separating the nonce preimage from any other keccak use in the SDK. */\nconst EIP3009_NONCE_DOMAIN_TAG = \"kawasekit/eip3009-nonce/1\";\n\n/**\n * Derives a **deterministic** 32-byte EIP-3009 nonce from a reasoning-step\n * idempotency key, scoped to `(from, verifyingContract, chainId)` so the same\n * key never collides across tokens or chains (M5-1, Half B).\n *\n * `nonce = keccak256(DOMAIN_TAG ‖ idempotencyKey ‖ from ‖ verifyingContract ‖\n * chainId)`. **No shared secret**: determinism across replicas / sub-agents\n * needs only a shared `conversationId` (the source of the key), not secret\n * distribution. A replayed key ⇒ identical nonce ⇒ the token contract's\n * `authorizationState` rejects the second settlement — the on-chain last line of\n * defence against re-signed same-intent duplicate payments. Use in place of\n * {@link generateAuthorizationNonce} only when a key is available.\n *\n * `chainId` is in the preimage, so the same JPYC address on Polygon / Avalanche\n * / Kaia / Ethereum yields distinct nonces (cross-chain replay safety).\n *\n * @example\n * ```ts\n * import { deriveAuthorizationNonce } from \"kawasekit\";\n *\n * const nonce = deriveAuthorizationNonce(\n * { idempotencyKey },\n * { from: account.address, verifyingContract, chainId },\n * );\n * ```\n */\nexport function deriveAuthorizationNonce(\n\tinput: { readonly idempotencyKey: string },\n\tscope: { readonly from: Address; readonly verifyingContract: Address; readonly chainId: number },\n): Hex {\n\tif (input.idempotencyKey === \"\") {\n\t\tthrow new Error(\"deriveAuthorizationNonce: idempotencyKey must be a non-empty string\");\n\t}\n\tconst preimage = JSON.stringify([\n\t\tEIP3009_NONCE_DOMAIN_TAG,\n\t\tinput.idempotencyKey,\n\t\tgetAddress(scope.from),\n\t\tgetAddress(scope.verifyingContract),\n\t\tscope.chainId,\n\t]);\n\treturn keccak256(stringToHex(preimage));\n}\n\n/**\n * Returns a `validBefore` UNIX timestamp `seconds` in the future.\n *\n * @param seconds - Lifetime of the authorization, in seconds.\n * @param nowSec - Optional override of \"now\" (defaults to {@link Date.now}).\n *\n * @example\n * ```ts\n * import { authorizationDeadlineFromNow } from \"kawasekit\";\n *\n * const validBefore = authorizationDeadlineFromNow(60 * 5); // 5 minutes\n * ```\n */\nexport function authorizationDeadlineFromNow(seconds: number, nowSec?: bigint): bigint {\n\tconst now = nowSec ?? BigInt(Math.floor(Date.now() / 1000));\n\treturn now + BigInt(seconds);\n}\n\nfunction requireSignTypedData(account: Account): NonNullable<Account[\"signTypedData\"]> {\n\tif (!account.signTypedData) {\n\t\tthrow new Error(\n\t\t\t`Account ${account.address} cannot sign typed data — pass a LocalAccount or a JsonRpcAccount bound to a WalletClient.`,\n\t\t);\n\t}\n\treturn account.signTypedData.bind(account);\n}\n\nfunction assertSignerMatches(account: Account, expectedFrom: Address, role: string): void {\n\tif (getAddress(account.address) !== getAddress(expectedFrom)) {\n\t\tthrow new Error(\n\t\t\t`EIP-3009 ${role} signature must come from \\`${role === \"cancel\" ? \"authorizer\" : \"from\"}\\`: account is ${account.address}, message says ${expectedFrom}.`,\n\t\t);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Signers\n// ---------------------------------------------------------------------------\n\n/**\n * Signs an EIP-3009 `TransferWithAuthorization` message.\n *\n * The signing account MUST equal `message.from` — EIP-3009 rejects signatures\n * from anyone else (the on-chain check is pure `ecrecover` against `from`).\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import {\n * authorizationDeadlineFromNow,\n * generateAuthorizationNonce,\n * JPYC_EIP712_DOMAIN_HINT,\n * polygon,\n * signTransferWithAuthorization,\n * } from \"kawasekit\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const signed = await signTransferWithAuthorization(account, {\n * ...JPYC_EIP712_DOMAIN_HINT,\n * chainId: polygon.id,\n * verifyingContract: \"0xE7C3D8C9a439feDe00D2600032D5dB0Be71C3c29\",\n * }, {\n * from: account.address,\n * to: \"0xBeef...\",\n * value: 100n * 10n ** 18n,\n * validAfter: 0n,\n * validBefore: authorizationDeadlineFromNow(300),\n * nonce: generateAuthorizationNonce(),\n * });\n * // → submit (v, r, s) to token.transferWithAuthorization(...)\n * ```\n */\nexport async function signTransferWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: TransferWithAuthorizationMessage,\n): Promise<SignedAuthorization<TransferWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"transfer\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: transferWithAuthorizationTypes,\n\t\tprimaryType: \"TransferWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `ReceiveWithAuthorization` message.\n *\n * Differs from {@link signTransferWithAuthorization} in two ways:\n * 1. Uses the `ReceiveWithAuthorization` EIP-712 type.\n * 2. The contract additionally enforces `msg.sender == to` at submission\n * time, so only `to` (or a relayer impersonating `to` — impossible in\n * practice) can land the tx.\n */\nexport async function signReceiveWithAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: ReceiveWithAuthorizationMessage,\n): Promise<SignedAuthorization<ReceiveWithAuthorizationMessage>> {\n\tassertSignerMatches(account, message.from, \"receive\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: receiveWithAuthorizationTypes,\n\t\tprimaryType: \"ReceiveWithAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\n/**\n * Signs an EIP-3009 `CancelAuthorization` message.\n *\n * Cancelling consumes the nonce so a later `transferWithAuthorization` or\n * `receiveWithAuthorization` with the same nonce will revert.\n */\nexport async function signCancelAuthorization(\n\taccount: Account,\n\tdomain: Eip3009Domain,\n\tmessage: CancelAuthorizationMessage,\n): Promise<SignedAuthorization<CancelAuthorizationMessage>> {\n\tassertSignerMatches(account, message.authorizer, \"cancel\");\n\tconst sign = requireSignTypedData(account);\n\tconst signature = await sign({\n\t\tdomain,\n\t\ttypes: cancelAuthorizationTypes,\n\t\tprimaryType: \"CancelAuthorization\",\n\t\tmessage,\n\t});\n\treturn splitAuthorization(signature, domain, message);\n}\n\nfunction splitAuthorization<TMessage>(\n\tsignature: Hex,\n\tdomain: Eip3009Domain,\n\tmessage: TMessage,\n): SignedAuthorization<TMessage> {\n\tconst parsed = parseSignature(signature);\n\t// viem's parseSignature returns yParity ∈ {0, 1} as well as v when present.\n\tconst v = parsed.v !== undefined ? Number(parsed.v) : (parsed.yParity ?? 0) + 27;\n\treturn {\n\t\tsignature,\n\t\tv,\n\t\tr: parsed.r,\n\t\ts: parsed.s,\n\t\tdomain,\n\t\tmessage,\n\t};\n}\n","/**\n * x402 v2 wire-format types — the canonical shapes that travel over HTTP between\n * client, resource server, and facilitator.\n *\n * These types are deliberately **spec-faithful**: field names, optionality, and\n * value encoding (e.g. `uint256` as decimal string) match the x402 v2\n * specification verbatim so that payloads kawasekit produces are byte-equivalent\n * to those from `@x402/core` and other reference implementations. Where the\n * spec allows a string union (e.g. `network`, `scheme`), kawasekit narrows the\n * type to the values it actually supports — but every kawasekit type is\n * structurally assignable to its `@x402/core` counterpart.\n *\n * For the EVM `exact` scheme (the only scheme kawasekit implements in M3) the\n * settlement mechanism is EIP-3009 `transferWithAuthorization`. Permit2 and\n * ERC-7710 are deferred.\n *\n * See:\n * - x402 v2 spec: https://github.com/coinbase/x402/blob/main/specs/x402-specification-v2.md\n * - exact-EVM scheme: https://github.com/coinbase/x402/blob/main/specs/schemes/exact/scheme_exact_evm.md\n *\n * @packageDocumentation\n */\n\nimport type { Address, Hex } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { isSupportedChainId } from \"../chains\";\n\n// ---------------------------------------------------------------------------\n// Protocol version\n// ---------------------------------------------------------------------------\n\n/**\n * Current x402 protocol version implemented by kawasekit.\n *\n * v2 is the wire format that uses CAIP-2 network identifiers (`eip155:N`) and\n * separates {@link X402ResourceInfo} from {@link X402PaymentRequirements}. v1 is\n * deprecated and not supported.\n */\nexport const X402_VERSION = 2 as const;\n\n/** Literal type of {@link X402_VERSION}. */\nexport type X402Version = typeof X402_VERSION;\n\n// ---------------------------------------------------------------------------\n// Scheme & network\n// ---------------------------------------------------------------------------\n\n/**\n * Payment scheme identifier.\n *\n * Only `\"exact\"` is implemented in M3. The spec is extensible (`\"upto\"`,\n * `\"batch-settlement\"`, …); future kawasekit milestones may widen this union.\n */\nexport type X402Scheme = \"exact\";\n\n/**\n * CAIP-2 network identifier in `eip155:{chainId}` form, narrowed to chains\n * kawasekit supports.\n *\n * Adding a chain to {@link SupportedChainId} automatically extends this union.\n *\n * @example\n * ```ts\n * const net: X402Network = \"eip155:80002\"; // Polygon Amoy\n * ```\n */\nexport type X402Network = `eip155:${SupportedChainId}`;\n\n/**\n * Asset transfer method advertised inside `PaymentRequirements.extra` for the\n * EVM `exact` scheme.\n *\n * kawasekit M3 only implements `\"eip3009\"`. The other values exist so that\n * inbound payloads from interoperable servers can be parsed without losing\n * information, even though kawasekit will reject them at validation time.\n */\nexport type X402AssetTransferMethod = \"eip3009\" | \"permit2\" | \"erc7710\";\n\n/**\n * Conventional shape of `PaymentRequirements.extra` for the exact-EVM scheme.\n *\n * `name` and `version` MUST match the EIP-712 domain values used by the token\n * (for JPYC: `name = \"JPY Coin\"`, `version = \"1\"` — see\n * `JPYC_EIP712_DOMAIN_HINT`). Servers may include additional fields; this\n * interface is intentionally open via the index signature.\n */\nexport interface X402ExactEvmExtra {\n\treadonly assetTransferMethod?: X402AssetTransferMethod;\n\treadonly name: string;\n\treadonly version: string;\n\treadonly [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Resource & requirements\n// ---------------------------------------------------------------------------\n\n/**\n * Describes the resource being paid for.\n *\n * In v2 this object lives at the top level of {@link X402PaymentRequiredResponse}\n * (and is echoed back optionally inside {@link X402PaymentPayload}), so that a\n * single payment offer can describe one resource served at one URL.\n */\nexport interface X402ResourceInfo {\n\treadonly url: string;\n\treadonly description?: string;\n\treadonly mimeType?: string;\n\treadonly serviceName?: string;\n\treadonly tags?: readonly string[];\n\treadonly iconUrl?: string;\n}\n\n/**\n * One acceptable payment method, as advertised by the resource server.\n *\n * Field encoding follows the wire format exactly:\n * - `amount` is a **decimal string** of atomic token units (`uint256`-safe).\n * - `asset` and `payTo` are 0x-prefixed addresses; case is not normalised at\n * this layer (the verifier MUST checksum-compare).\n * - `maxTimeoutSeconds` is the max wall-clock time the client may take to\n * produce a signed payload after receiving the 402 response.\n *\n * `extra` is required (matching `@x402/core`) so that producers always provide\n * the EIP-712 domain hint needed for signature verification. The most common\n * shape is {@link X402ExactEvmExtra}.\n */\nexport interface X402PaymentRequirements {\n\treadonly scheme: X402Scheme;\n\treadonly network: X402Network;\n\treadonly amount: string;\n\treadonly asset: Address;\n\treadonly payTo: Address;\n\treadonly maxTimeoutSeconds: number;\n\treadonly extra: Record<string, unknown>;\n}\n\n/**\n * The JSON body returned by a resource server alongside the \"Payment Required\"\n * response (HTTP 402, or the transport equivalent).\n *\n * `accepts` is an OR-list: the client picks **one** entry and produces a\n * matching {@link X402PaymentPayload}.\n */\nexport interface X402PaymentRequiredResponse {\n\treadonly x402Version: X402Version;\n\treadonly error?: string;\n\treadonly resource: X402ResourceInfo;\n\treadonly accepts: readonly X402PaymentRequirements[];\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Payment payload (client → server)\n// ---------------------------------------------------------------------------\n\n/**\n * EIP-3009 `TransferWithAuthorization` parameters in **wire format**.\n *\n * Note that `value`, `validAfter`, and `validBefore` are decimal strings here\n * (uint256-safe over JSON), whereas the in-process EIP-712 signing helpers in\n * `src/tokens/eip3009.ts` use `bigint`. Converters between the two\n * representations live in `src/x402/encoding.ts`.\n *\n * `nonce` is a 0x-prefixed 32-byte hex string — generate one with\n * {@link generateAuthorizationNonce} from `src/tokens/eip3009.ts`.\n */\nexport interface X402ExactEvmAuthorization {\n\treadonly from: Address;\n\treadonly to: Address;\n\treadonly value: string;\n\treadonly validAfter: string;\n\treadonly validBefore: string;\n\treadonly nonce: Hex;\n}\n\n/**\n * Scheme-specific `payload` body for the exact-EVM scheme using EIP-3009.\n *\n * `signature` is the 65-byte EIP-712 signature over a\n * `TransferWithAuthorization` message, produced by\n * {@link signTransferWithAuthorization}.\n */\nexport interface X402ExactEvmPayload {\n\treadonly signature: Hex;\n\treadonly authorization: X402ExactEvmAuthorization;\n}\n\n/**\n * The JSON body the client sends to a paywalled resource (typically base64-\n * encoded inside an `X-PAYMENT` header — see `src/x402/encoding.ts`).\n *\n * `accepted` is the single {@link X402PaymentRequirements} entry the client\n * chose from the server's `accepts` list. `payload` is scheme-specific; for\n * the exact-EVM scheme it has the shape of {@link X402ExactEvmPayload}.\n *\n * `payload` is typed as the open `Record<string, unknown>` so that this\n * interface stays structurally compatible with `@x402/core`'s `PaymentPayload`.\n * Use a scheme-aware parser to narrow it.\n */\nexport interface X402PaymentPayload {\n\treadonly x402Version: X402Version;\n\treadonly resource?: X402ResourceInfo;\n\treadonly accepted: X402PaymentRequirements;\n\treadonly payload: Record<string, unknown>;\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Settlement response (server → client, after settlement)\n// ---------------------------------------------------------------------------\n\n/**\n * The JSON body the resource server returns once the facilitator has settled\n * the payment (typically base64-encoded inside an `X-PAYMENT-RESPONSE`\n * header).\n *\n * On failure, `transaction` is an empty string and `errorReason` is set.\n */\nexport interface X402SettlementResponse {\n\treadonly success: boolean;\n\treadonly errorReason?: string;\n\treadonly errorMessage?: string;\n\treadonly payer?: Address;\n\treadonly transaction: string;\n\treadonly network: X402Network;\n\treadonly amount?: string;\n\treadonly extensions?: Record<string, unknown>;\n\treadonly extra?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Facilitator HTTP API (server ↔ facilitator)\n// ---------------------------------------------------------------------------\n\n/**\n * Body of `POST /verify` — asks the facilitator whether a payment payload\n * would settle, without broadcasting anything.\n */\nexport interface X402VerifyRequest {\n\treadonly x402Version: X402Version;\n\treadonly paymentPayload: X402PaymentPayload;\n\treadonly paymentRequirements: X402PaymentRequirements;\n}\n\n/** Response from `POST /verify`. */\nexport interface X402VerifyResponse {\n\treadonly isValid: boolean;\n\treadonly invalidReason?: string;\n\treadonly invalidMessage?: string;\n\treadonly payer?: Address;\n\treadonly extensions?: Record<string, unknown>;\n\treadonly extra?: Record<string, unknown>;\n}\n\n/**\n * Body of `POST /settle` — same shape as {@link X402VerifyRequest}. The\n * facilitator broadcasts the transaction and returns an\n * {@link X402SettlementResponse}.\n */\nexport type X402SettleRequest = X402VerifyRequest;\n\n/** Response from `POST /settle`. Same shape as {@link X402SettlementResponse}. */\nexport type X402SettleResponse = X402SettlementResponse;\n\n/**\n * One supported (scheme, network) pair returned by `GET /supported`.\n *\n * `network` is intentionally typed as `string` (not {@link X402Network}) here:\n * the facilitator may advertise networks kawasekit has not yet whitelisted, and\n * `kawasekit/x402` must be able to read that response to gate features (e.g.\n * skip the Coinbase facilitator demo when Polygon Amoy is not listed).\n */\nexport interface X402SupportedKind {\n\treadonly x402Version: X402Version;\n\treadonly scheme: string;\n\treadonly network: string;\n\treadonly extra?: Record<string, unknown>;\n}\n\n/** Response from `GET /supported`. */\nexport interface X402SupportedResponse {\n\treadonly kinds: readonly X402SupportedKind[];\n\treadonly extensions: readonly string[];\n\treadonly signers: Readonly<Record<string, readonly Address[]>>;\n}\n\n/**\n * A facilitator endpoint kawasekit can talk to.\n *\n * Two implementations live in `src/x402/facilitator.ts`:\n * - `createHttpFacilitator()` — proxies `/verify` & `/settle` over HTTP to any\n * x402 v2-compliant endpoint (Coinbase CDP, a self-hosted mirror, etc.)\n * - `createSelfFacilitator()` — runs `transferWithAuthorization` from a\n * private key kawasekit holds locally (testnet / self-host case)\n *\n * `createX402Handler()` accepts any object satisfying this interface and is\n * agnostic to the underlying transport (HTTPS, in-process, mocked).\n */\nexport interface Facilitator {\n\t/** Verify a payment payload without broadcasting. */\n\tverify(request: X402VerifyRequest): Promise<X402VerifyResponse>;\n\t/** Settle a verified payment — broadcasts to the chain. */\n\tsettle(request: X402SettleRequest): Promise<X402SettleResponse>;\n\t/** List supported (scheme, network) pairs. */\n\tsupported(): Promise<X402SupportedResponse>;\n}\n\n// ---------------------------------------------------------------------------\n// SupportedChainId ↔ X402Network conversions\n// ---------------------------------------------------------------------------\n\nconst EIP155_PREFIX = \"eip155:\" as const;\n\n/**\n * Builds the CAIP-2 {@link X402Network} string for a kawasekit-supported chain.\n *\n * @example\n * ```ts\n * import { chainIdToX402Network, polygonAmoy } from \"kawasekit\";\n *\n * const network = chainIdToX402Network(polygonAmoy.id); // \"eip155:80002\"\n * ```\n */\nexport function chainIdToX402Network<TChainId extends SupportedChainId>(\n\tchainId: TChainId,\n): `eip155:${TChainId}` {\n\treturn `${EIP155_PREFIX}${chainId}` as `eip155:${TChainId}`;\n}\n\n/**\n * Type guard for {@link X402Network}.\n *\n * Accepts only `eip155:N` strings where `N` is a kawasekit-supported chain ID.\n * A facilitator response advertising e.g. `\"eip155:8453\"` (Base) returns\n * `false` and should be treated as out-of-scope by the caller.\n */\nexport function isX402Network(value: string): value is X402Network {\n\tif (!value.startsWith(EIP155_PREFIX)) {\n\t\treturn false;\n\t}\n\tconst rest = value.slice(EIP155_PREFIX.length);\n\tif (rest.length === 0 || /^0\\d/.test(rest)) {\n\t\treturn false;\n\t}\n\tconst parsed = Number(rest);\n\tif (!Number.isInteger(parsed) || parsed < 0) {\n\t\treturn false;\n\t}\n\treturn isSupportedChainId(parsed);\n}\n\n/**\n * Extracts the {@link SupportedChainId} from an {@link X402Network}.\n *\n * Total over the {@link X402Network} type: if the input is `eip155:80002` the\n * result is `80002`. Use {@link isX402Network} first to narrow an arbitrary\n * `string`.\n *\n * @example\n * ```ts\n * import { x402NetworkToChainId } from \"kawasekit\";\n *\n * const chainId = x402NetworkToChainId(\"eip155:80002\"); // 80002\n * ```\n */\nexport function x402NetworkToChainId(network: X402Network): SupportedChainId {\n\tconst rest = network.slice(EIP155_PREFIX.length);\n\treturn Number(rest) as SupportedChainId;\n}\n","/**\n * x402 v2 client-side signer.\n *\n * Given a server-issued {@link X402PaymentRequirements}, produce a\n * {@link X402PaymentPayload} the client can send back in the next request. This\n * is the first runtime consumer of the M2 EIP-3009 helpers\n * ({@link signTransferWithAuthorization}, {@link authorizationDeadlineFromNow},\n * {@link generateAuthorizationNonce}).\n *\n * Scope:\n * - **exact-EVM scheme only.** Permit2 / ERC-7710 are M4+.\n * - **EOA payer only.** EIP-3009 uses pure `ecrecover` (no ERC-1271 fallback)\n * so smart accounts cannot be `from`. The agent-account flow is\n * {@link transferJpyc} (UserOp), not x402.\n *\n * @packageDocumentation\n */\n\nimport type { Account, Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport { getChain, isSupportedChainId } from \"../chains\";\nimport { assertNonBypassable } from \"../signer/gate\";\nimport type { NonBypassableEnforcement, PaymentIntent, PolicyGatedSigner } from \"../signer/types\";\nimport type { X402AssetParam, X402TokenDomain } from \"../tokens/asset-domain\";\nimport { resolveAssetParam, resolvedAssetToEip3009Domain } from \"../tokens/asset-domain\";\nimport {\n\tauthorizationDeadlineFromNow,\n\tderiveAuthorizationNonce,\n\tgenerateAuthorizationNonce,\n\tsignTransferWithAuthorization,\n} from \"../tokens/eip3009\";\nimport { X402InvalidPayloadError, X402PolicyRejectedError } from \"./errors\";\nimport type {\n\tX402ExactEvmPayload,\n\tX402PaymentPayload,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n} from \"./types\";\nimport { X402_VERSION, x402NetworkToChainId } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default authorization lifetime (`validBefore = now + this`) when the caller\n * does not pass an override. Capped per-sign by `paymentRequirements.maxTimeoutSeconds`.\n *\n * 300 s matches the M3 example app's tolerance for Polygon Amoy bundler\n * inclusion latency (see plan risk #6).\n */\nexport const X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS = 300;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n// `X402TokenDomain` and `X402AssetParam` were lifted to `../tokens/asset-domain`\n// (M6-0) so the PolicyGatedSigner can reuse the same pinned-domain resolution.\n// Re-exported here for back-compat — consumers still import them from this module.\nexport type { X402AssetParam, X402TokenDomain };\n\n/**\n * Parameters for the `account` (EOA) variant of {@link createX402PaymentSigner}.\n *\n * Kept as a named, extensible `interface` (consumers may `extends` /\n * declaration-merge it). `maxAmountPerSign` pins the per-sign ceiling; for richer\n * policy use the `signer` variant ({@link CreateX402PaymentSignerSignerParams}).\n */\nexport interface CreateX402PaymentSignerAccountParams {\n\t/**\n\t * Declared production-vs-test intent. Each `sign()` call verifies that\n\t * `paymentRequirements.network` resolves to a chain whose `isTestnet`\n\t * agrees with this value, and throws otherwise. The point is to refuse\n\t * to sign a real-funds payment when the signer was configured for testnet\n\t * (e.g. the server unexpectedly demanded `polygon-mainnet` instead of\n\t * `polygon-amoy`).\n\t */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/**\n\t * EOA / LocalAccount that signs the EIP-3009 `TransferWithAuthorization`.\n\t * MUST be the same address the requirements' `from` will name.\n\t */\n\treadonly account: Account;\n\t/**\n\t * Asset binding (required). Pins the EIP-712 domain at construction time\n\t * and cross-checks `paymentRequirements.asset` at every sign call.\n\t * See {@link X402AssetParam} for the discriminated-union shape.\n\t *\n\t * **Threat 1.4 mitigation**: the wire-format `extra.name` and\n\t * `extra.version` are NOT consulted; a malicious server cannot coerce a\n\t * mismatched signature through them.\n\t */\n\treadonly asset: X402AssetParam;\n\t/**\n\t * Default authorization lifetime in seconds. Bounded by each\n\t * requirement's `maxTimeoutSeconds` at sign time.\n\t * Defaults to {@link X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS}.\n\t */\n\treadonly defaultLifetimeSeconds?: number;\n\t/**\n\t * Optional per-signature value ceiling, in the asset's smallest unit\n\t * (`bigint`). When set, `sign()` throws {@link X402InvalidPayloadError} if a\n\t * server advertises `requirements.amount` greater than this — refusing to\n\t * sign an over-budget payment at the primitive.\n\t *\n\t * **Threat 1.14 mitigation.** {@link createX402PaymentSigner} is a public API\n\t * and the direct-signer path bypasses the `wrapFetch` `onPayment` guard; the\n\t * EOA-payer x402 flow is also not bounded by the Layer-4 session-key daily\n\t * limit. This pins the *amount* ceiling the way {@link X402AssetParam} pins\n\t * the *asset* (1.4) — production posture is to set it. Omit it for no ceiling\n\t * (backward-compatible default; the payer EOA balance is the only bound).\n\t */\n\treadonly maxAmountPerSign?: bigint;\n\t/** Discriminant: absent on this arm — use the `signer` variant for a PolicyGatedSigner. */\n\treadonly signer?: never;\n}\n\n/**\n * Parameters for the `signer` (PolicyGatedSigner) variant of\n * {@link createX402PaymentSigner}. Drives signing through a\n * {@link PolicyGatedSigner} (e.g. `createLocalPolicyGatedSigner`); the per-sign\n * ceiling and richer policy live in the signer, so `maxAmountPerSign` is not\n * accepted here.\n */\nexport interface CreateX402PaymentSignerSignerParams {\n\t/** Declared production-vs-test intent (same semantics as the `account` variant). */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/** The policy-gated signer that produces the EIP-3009 authorization. */\n\treadonly signer: PolicyGatedSigner;\n\t/** Asset binding — pins the EIP-712 domain and cross-checks `paymentRequirements.asset`. */\n\treadonly asset: X402AssetParam;\n\t/**\n\t * Default authorization lifetime in seconds. Bounded per-sign by\n\t * `paymentRequirements.maxTimeoutSeconds`. Defaults to\n\t * {@link X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS}.\n\t */\n\treadonly defaultLifetimeSeconds?: number;\n\t/**\n\t * When set, asserts at construction that `signer` is non-bypassable\n\t * (`cryptographic` | `hardware`) — the runtime mirror of the\n\t * `requireNonBypassable` type-gate. Throws for an advisory signer.\n\t */\n\treadonly requireEnforcement?: NonBypassableEnforcement;\n\t/** Discriminant: absent on this arm. */\n\treadonly account?: never;\n\t/** Subsumed by the signer's policy; not accepted on this arm. */\n\treadonly maxAmountPerSign?: never;\n}\n\n/**\n * Parameters for {@link createX402PaymentSigner} — a discriminated union of the\n * `account` (EOA) and `signer` (PolicyGatedSigner) variants.\n *\n * NOTE: type-level breaking change from the original `interface` (a union cannot\n * be `extends`-ed). Existing `{ account, asset, network }` callers are\n * value-assignable to the `account` arm and unaffected; consumers who `extends`\n * / declaration-merge should use {@link CreateX402PaymentSignerAccountParams}.\n */\nexport type CreateX402PaymentSignerParams =\n\t| CreateX402PaymentSignerAccountParams\n\t| CreateX402PaymentSignerSignerParams;\n\n/** Parameters for {@link X402PaymentSigner.sign}. */\nexport interface SignX402PaymentParams {\n\t/** The chosen entry from the server's `accepts` array. */\n\treadonly paymentRequirements: X402PaymentRequirements;\n\t/** Optional {@link X402ResourceInfo} to echo back in the payload. */\n\treadonly resource?: X402ResourceInfo;\n\t/** Unix-seconds override of `validAfter`. Defaults to `0n`. */\n\treadonly validAfter?: bigint;\n\t/**\n\t * Unix-seconds override of `validBefore`. Defaults to `now + lifetime`\n\t * where lifetime = `min(signer default, requirements.maxTimeoutSeconds)`.\n\t */\n\treadonly validBefore?: bigint;\n\t/**\n\t * Optional reasoning-step idempotency key (M5-1, Half B). When supplied, the\n\t * EIP-3009 nonce is **derived deterministically** from it (instead of random)\n\t * so a re-signed same-intent payment produces the same on-chain nonce — the\n\t * token contract's `authorizationState` then rejects the duplicate\n\t * settlement. For a byte-identical re-sign, also pin `validBefore`. Build the\n\t * key with `createIdempotencyKeyBuilder` from `kawasekit/idempotency`.\n\t */\n\treadonly idempotencyKey?: string;\n}\n\n/** Signer returned by {@link createX402PaymentSigner}. */\nexport interface X402PaymentSigner {\n\t/** Address of the EOA bound to this signer. */\n\treadonly address: Address;\n\t/** Sign a payment for one {@link X402PaymentRequirements}. */\n\tsign(params: SignX402PaymentParams): Promise<X402PaymentPayload>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst UINT256_DECIMAL = /^(0|[1-9][0-9]*)$/;\n\nfunction parseUintString(value: string, field: string): bigint {\n\tif (!UINT256_DECIMAL.test(value)) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` must be a non-negative decimal string, got ${JSON.stringify(value)}`,\n\t\t);\n\t}\n\tconst parsed = BigInt(value);\n\tif (parsed > UINT256_MAX) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` exceeds uint256, got ${value}`,\n\t\t);\n\t}\n\treturn parsed;\n}\n\nfunction assertAddress(value: string, field: string): Address {\n\tif (!isAddress(value, { strict: false })) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` is not a valid address: ${value}`,\n\t\t);\n\t}\n\treturn value as Address;\n}\n\nfunction validateRequirements(requirements: X402PaymentRequirements): {\n\treadonly chainId: number;\n\treadonly value: bigint;\n\treadonly asset: Address;\n\treadonly payTo: Address;\n} {\n\tif (requirements.scheme !== \"exact\") {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`unsupported scheme: ${requirements.scheme}`,\n\t\t);\n\t}\n\tconst chainId = x402NetworkToChainId(requirements.network);\n\tif (!isSupportedChainId(chainId)) {\n\t\t// Defensive: an inbound payload typed as X402PaymentRequirements that\n\t\t// nonetheless smuggled an unsupported chainId via type-cast.\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`unsupported network: ${requirements.network}`,\n\t\t);\n\t}\n\tconst value = parseUintString(requirements.amount, \"amount\");\n\tif (value === 0n) {\n\t\tthrow new X402InvalidPayloadError(\"PaymentRequirements\", \"`amount` must be positive\");\n\t}\n\tif (requirements.maxTimeoutSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`maxTimeoutSeconds\\` must be positive, got ${requirements.maxTimeoutSeconds}`,\n\t\t);\n\t}\n\tconst asset = assertAddress(requirements.asset, \"asset\");\n\tconst payTo = assertAddress(requirements.payTo, \"payTo\");\n\treturn { chainId, value, asset, payTo };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Build an {@link X402PaymentSigner} bound to a single signing account.\n *\n * The returned signer can produce many {@link X402PaymentPayload}s in\n * succession — one per accepted requirement. Each call generates a fresh\n * EIP-3009 nonce.\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { createX402PaymentSigner } from \"kawasekit\";\n *\n * const account = privateKeyToAccount(\"0x...\");\n * const signer = createX402PaymentSigner({\n * network: \"testnet\",\n * account,\n * asset: { kind: \"known\", id: \"jpyc-v2\" },\n * });\n *\n * // ...after receiving a 402 with PAYMENT-REQUIRED header...\n * const paymentPayload = await signer.sign({ paymentRequirements });\n * ```\n */\nexport function createX402PaymentSigner(params: CreateX402PaymentSignerParams): X402PaymentSigner {\n\tif (params.signer !== undefined) {\n\t\treturn createSignerBackedX402PaymentSigner(params);\n\t}\n\tconst { account, network } = params;\n\tconst defaultLifetimeSeconds =\n\t\tparams.defaultLifetimeSeconds ?? X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS;\n\tif (defaultLifetimeSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`defaultLifetimeSeconds\\` must be positive, got ${defaultLifetimeSeconds}`,\n\t\t);\n\t}\n\tconst maxAmountPerSign = params.maxAmountPerSign;\n\tif (maxAmountPerSign !== undefined && maxAmountPerSign <= 0n) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`maxAmountPerSign\\` must be a positive bigint, got ${maxAmountPerSign}`,\n\t\t);\n\t}\n\tconst pinnedDomain = resolveAssetParam(params.asset);\n\n\treturn {\n\t\taddress: account.address,\n\t\tasync sign(signParams) {\n\t\t\tconst { paymentRequirements } = signParams;\n\t\t\tconst { chainId, value, asset, payTo } = validateRequirements(paymentRequirements);\n\t\t\tconst chain = getChain(chainId);\n\t\t\tif (network === \"mainnet\" && chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"mainnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a testnet`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (network === \"testnet\" && !chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"testnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a mainnet — refusing to sign payment for real funds`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (getAddress(asset) !== pinnedDomain.verifyingContract) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.asset (${getAddress(asset)}) does not match the signer's pinned verifyingContract (${pinnedDomain.verifyingContract}) — refusing to sign for an asset the signer was not configured to handle`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (maxAmountPerSign !== undefined && value > maxAmountPerSign) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.amount (${value}) exceeds the signer's \\`maxAmountPerSign\\` ceiling (${maxAmountPerSign}) — refusing to sign a payment above the configured per-signature limit (threat 1.14)`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst lifetime = Math.min(defaultLifetimeSeconds, paymentRequirements.maxTimeoutSeconds);\n\t\t\tconst validAfter = signParams.validAfter ?? 0n;\n\t\t\tconst validBefore = signParams.validBefore ?? authorizationDeadlineFromNow(lifetime);\n\t\t\tif (validBefore <= validAfter) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`\\`validBefore\\` (${validBefore}) must be greater than \\`validAfter\\` (${validAfter})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nonce =\n\t\t\t\tsignParams.idempotencyKey !== undefined\n\t\t\t\t\t? deriveAuthorizationNonce(\n\t\t\t\t\t\t\t{ idempotencyKey: signParams.idempotencyKey },\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfrom: account.address,\n\t\t\t\t\t\t\t\tverifyingContract: pinnedDomain.verifyingContract,\n\t\t\t\t\t\t\t\tchainId,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateAuthorizationNonce();\n\t\t\tconst signed = await signTransferWithAuthorization(\n\t\t\t\taccount,\n\t\t\t\tresolvedAssetToEip3009Domain(pinnedDomain, chainId),\n\t\t\t\t{\n\t\t\t\t\tfrom: account.address,\n\t\t\t\t\tto: payTo,\n\t\t\t\t\tvalue,\n\t\t\t\t\tvalidAfter,\n\t\t\t\t\tvalidBefore,\n\t\t\t\t\tnonce,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tconst payload: X402ExactEvmPayload = {\n\t\t\t\tsignature: signed.signature,\n\t\t\t\tauthorization: {\n\t\t\t\t\tfrom: signed.message.from,\n\t\t\t\t\tto: signed.message.to,\n\t\t\t\t\tvalue: signed.message.value.toString(),\n\t\t\t\t\tvalidAfter: signed.message.validAfter.toString(),\n\t\t\t\t\tvalidBefore: signed.message.validBefore.toString(),\n\t\t\t\t\tnonce: signed.message.nonce,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst result: X402PaymentPayload = signParams.resource\n\t\t\t\t? {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\tresource: signParams.resource,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t};\n\t\t\treturn result;\n\t\t},\n\t};\n}\n\n/**\n * The `signer` (PolicyGatedSigner) variant of {@link createX402PaymentSigner}.\n *\n * Shares the `account` path's validate / network / asset-pin / window / nonce\n * prologue (kept in sync deliberately — the two security checks must not drift),\n * then routes the EIP-3009 signing through the {@link PolicyGatedSigner}. A\n * policy denial (`sign()` → `{ ok: false }`) surfaces as a thrown\n * {@link X402PolicyRejectedError}, so the `X402PaymentSigner.sign()` contract is\n * unchanged (returns a payload or throws). The per-sign ceiling is the signer's\n * policy, so there is no `maxAmountPerSign` check here.\n */\nfunction createSignerBackedX402PaymentSigner(\n\tparams: CreateX402PaymentSignerSignerParams,\n): X402PaymentSigner {\n\tconst { signer, network } = params;\n\tconst defaultLifetimeSeconds =\n\t\tparams.defaultLifetimeSeconds ?? X402_DEFAULT_AUTHORIZATION_LIFETIME_SECONDS;\n\tif (defaultLifetimeSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"X402PaymentSignerConfig\",\n\t\t\t`\\`defaultLifetimeSeconds\\` must be positive, got ${defaultLifetimeSeconds}`,\n\t\t);\n\t}\n\tif (params.requireEnforcement !== undefined) {\n\t\tassertNonBypassable(signer);\n\t}\n\tconst pinnedDomain = resolveAssetParam(params.asset);\n\tconst from = signer.from;\n\n\treturn {\n\t\taddress: from,\n\t\tasync sign(signParams) {\n\t\t\tconst { paymentRequirements } = signParams;\n\t\t\tconst { chainId, value, asset, payTo } = validateRequirements(paymentRequirements);\n\t\t\tconst chain = getChain(chainId);\n\t\t\tif (network === \"mainnet\" && chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"mainnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a testnet`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (network === \"testnet\" && !chain.isTestnet) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`signer was configured for network=\"testnet\" but requirements.network=\"${paymentRequirements.network}\" (chainId ${chainId}) is a mainnet — refusing to sign payment for real funds`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (getAddress(asset) !== pinnedDomain.verifyingContract) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`requirements.asset (${getAddress(asset)}) does not match the signer's pinned verifyingContract (${pinnedDomain.verifyingContract}) — refusing to sign for an asset the signer was not configured to handle`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst lifetime = Math.min(defaultLifetimeSeconds, paymentRequirements.maxTimeoutSeconds);\n\t\t\tconst validAfter = signParams.validAfter ?? 0n;\n\t\t\tconst validBefore = signParams.validBefore ?? authorizationDeadlineFromNow(lifetime);\n\t\t\tif (validBefore <= validAfter) {\n\t\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t\t`\\`validBefore\\` (${validBefore}) must be greater than \\`validAfter\\` (${validAfter})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst nonce =\n\t\t\t\tsignParams.idempotencyKey !== undefined\n\t\t\t\t\t? deriveAuthorizationNonce(\n\t\t\t\t\t\t\t{ idempotencyKey: signParams.idempotencyKey },\n\t\t\t\t\t\t\t{ from, verifyingContract: pinnedDomain.verifyingContract, chainId },\n\t\t\t\t\t\t)\n\t\t\t\t\t: generateAuthorizationNonce();\n\n\t\t\tconst intent: PaymentIntent = {\n\t\t\t\ttoken: pinnedDomain.verifyingContract,\n\t\t\t\tchainId,\n\t\t\t\tfrom,\n\t\t\t\tto: payTo,\n\t\t\t\tvalue,\n\t\t\t\tvalidAfter,\n\t\t\t\tvalidBefore,\n\t\t\t\tnonce,\n\t\t\t};\n\n\t\t\tconst signResult = await signer.sign(intent);\n\t\t\tif (!signResult.ok) {\n\t\t\t\tthrow new X402PolicyRejectedError(signResult.rejection);\n\t\t\t}\n\n\t\t\tconst payload: X402ExactEvmPayload = {\n\t\t\t\tsignature: signResult.signature,\n\t\t\t\tauthorization: {\n\t\t\t\t\tfrom,\n\t\t\t\t\tto: payTo,\n\t\t\t\t\tvalue: value.toString(),\n\t\t\t\t\tvalidAfter: validAfter.toString(),\n\t\t\t\t\tvalidBefore: validBefore.toString(),\n\t\t\t\t\tnonce,\n\t\t\t\t},\n\t\t\t};\n\n\t\t\tconst result: X402PaymentPayload = signParams.resource\n\t\t\t\t? {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\tresource: signParams.resource,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\t\t\taccepted: paymentRequirements,\n\t\t\t\t\t\tpayload: { ...payload },\n\t\t\t\t\t};\n\t\t\treturn result;\n\t\t},\n\t};\n}\n","/**\n * Wire-format encoding for x402 v2 headers.\n *\n * Three pairs of `encode*` / `decode*` helpers, one per x402 v2 HTTP header:\n *\n * | Direction | Header | Payload type |\n * | ---------------- | ------------------- | -------------------------------- |\n * | server → client | `PAYMENT-REQUIRED` | {@link X402PaymentRequiredResponse} |\n * | client → server | `PAYMENT-SIGNATURE` | {@link X402PaymentPayload} |\n * | server → client | `PAYMENT-RESPONSE` | {@link X402SettlementResponse} |\n *\n * Encoding rules (match `@x402/core@2.13.0` byte-for-byte so kawasekit payloads\n * decode in any spec-compliant client / facilitator):\n *\n * - The payload is JSON-stringified, then UTF-8 → base64 encoded.\n * - **Standard base64** with `+` / `/` and `=` padding, **not** URL-safe base64.\n * (Header values flow through `Authorization`-style positions where `+` is\n * acceptable in the v2 spec.)\n * - The replacer used by `JSON.stringify` rewrites any stray `bigint` value to\n * its decimal string form, so kawasekit callers can hand a payload whose\n * `value` / `validAfter` / `validBefore` are bigints by mistake and the\n * encoder still produces a spec-conformant string — silent corruption\n * surfaces as a type error in `tsc`, not a runtime crash.\n *\n * Decoders are intentionally minimal: base64 syntax check + `JSON.parse` + a\n * \"must be a plain object\" sanity check. Schema-level validation lives one\n * layer up (in `server.ts` and `client.ts`) so that this module stays a small,\n * dependency-free wire codec.\n *\n * @packageDocumentation\n */\n\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentPayload,\n\tX402PaymentRequiredResponse,\n\tX402SettlementResponse,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// HTTP header names (x402 v2 transport spec)\n// ---------------------------------------------------------------------------\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402PaymentRequiredResponse} alongside the HTTP 402 status.\n */\nexport const X402_HEADER_PAYMENT_REQUIRED = \"PAYMENT-REQUIRED\" as const;\n\n/**\n * Name of the request header that carries the client's base64-encoded\n * {@link X402PaymentPayload}.\n *\n * Note: x402 v1 used `X-PAYMENT`. v2 drops the `X-` prefix. Servers may accept\n * both during transition; clients should send only this v2 name.\n */\nexport const X402_HEADER_PAYMENT_SIGNATURE = \"PAYMENT-SIGNATURE\" as const;\n\n/**\n * Name of the response header that carries the base64-encoded\n * {@link X402SettlementResponse} after a successful settlement.\n */\nexport const X402_HEADER_PAYMENT_RESPONSE = \"PAYMENT-RESPONSE\" as const;\n\n/**\n * Name of the optional request header that carries a reasoning-step idempotency\n * key (M5-1). Standard `Idempotency-Key` (IETF draft / Stripe-compatible). When\n * present, the x402 server deduplicates on this logical key; the EIP-3009 nonce\n * remains the on-chain fund backstop. See `docs/rfc/m5-1-reasoning-step-idempotency.md`.\n */\nexport const X402_HEADER_IDEMPOTENCY_KEY = \"Idempotency-Key\" as const;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n// Canonical base64 per RFC 4648 §4: encoded length is a multiple of 4 and the\n// only legal trailing forms are `XX==`, `XXX=`, or `XXXX` (no padding). The\n// outer prefix is zero or more 4-char groups; the optional inner alternation\n// matches a single final group of 4 chars or a properly padded 2-or-3 char\n// group. This shape rejects the non-canonical forms an adversary could try\n// to smuggle past the decoder — overlong padding (`X===`), misplaced padding\n// (`X=XX`), short tails (`XXX` with no `=`), or non-mod-4 lengths.\n//\n// See `docs/THREAT_MODEL.md` §6.7 for the M4 review trail and\n// `src/x402/encoding.test.ts` \"RFC 4648 canonical enforcement\" for the\n// adversarial corpus.\n/**\n * Strict RFC 4648 §4 canonical base64 matcher. Exported for the\n * property-based test in `encoding.test.ts` (Threat 1.7 / §6.7\n * regex-vs-decoder agreement); not intended as part of the public API.\n *\n * @internal\n */\nexport const BASE64_REGEX =\n\t/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})?$/;\n\nfunction bigIntReplacer(_key: string, value: unknown): unknown {\n\treturn typeof value === \"bigint\" ? value.toString() : value;\n}\n\nfunction stringifyBigIntSafe(value: unknown): string {\n\treturn JSON.stringify(value, bigIntReplacer);\n}\n\nfunction utf8ToBase64(input: string): string {\n\t// Cross-env: prefer `btoa` (browsers, Workers, Bun, modern Node 18+) and\n\t// fall back to `Buffer` for older Node where `btoa` was Latin-1-only.\n\tif (typeof globalThis.btoa === \"function\") {\n\t\tconst bytes = new TextEncoder().encode(input);\n\t\tlet binary = \"\";\n\t\tfor (const byte of bytes) {\n\t\t\tbinary += String.fromCharCode(byte);\n\t\t}\n\t\treturn globalThis.btoa(binary);\n\t}\n\treturn Buffer.from(input, \"utf8\").toString(\"base64\");\n}\n\n/**\n * Internal helper exported for the regex-vs-decoder property-based test.\n * Not part of the public API.\n *\n * @internal\n */\nexport function base64ToUtf8(input: string): string {\n\tif (typeof globalThis.atob === \"function\") {\n\t\tconst binary = globalThis.atob(input);\n\t\tconst bytes = new Uint8Array(binary.length);\n\t\tfor (let i = 0; i < binary.length; i++) {\n\t\t\tbytes[i] = binary.charCodeAt(i);\n\t\t}\n\t\treturn new TextDecoder(\"utf-8\").decode(bytes);\n\t}\n\treturn Buffer.from(input, \"base64\").toString(\"utf8\");\n}\n\nfunction decodeHeader<T>(headerName: string, headerValue: string): T {\n\tif (!BASE64_REGEX.test(headerValue)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"header is not valid base64\");\n\t}\n\tlet json: string;\n\ttry {\n\t\tjson = base64ToUtf8(headerValue);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"base64 decode failed\", { cause });\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(json);\n\t} catch (cause) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not valid JSON\", { cause });\n\t}\n\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\tthrow new X402InvalidPayloadError(headerName, \"decoded value is not a JSON object\");\n\t}\n\treturn parsed as T;\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-REQUIRED\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentRequiredResponse} as a base64 string suitable\n * for the `PAYMENT-REQUIRED` response header.\n *\n * @example\n * ```ts\n * import { encodePaymentRequiredHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentRequiredHeader({\n * x402Version: 2,\n * resource: { url: \"https://api.example.com/data\" },\n * accepts: [],\n * });\n * res.setHeader(\"PAYMENT-REQUIRED\", headerValue);\n * ```\n */\nexport function encodePaymentRequiredHeader(payload: X402PaymentRequiredResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-REQUIRED` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentRequiredHeader(headerValue: string): X402PaymentRequiredResponse {\n\treturn decodeHeader<X402PaymentRequiredResponse>(X402_HEADER_PAYMENT_REQUIRED, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-SIGNATURE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402PaymentPayload} as a base64 string suitable for the\n * `PAYMENT-SIGNATURE` request header.\n *\n * @example\n * ```ts\n * import { encodePaymentSignatureHeader } from \"kawasekit\";\n *\n * const headerValue = encodePaymentSignatureHeader(paymentPayload);\n * await fetch(url, { headers: { \"PAYMENT-SIGNATURE\": headerValue } });\n * ```\n */\nexport function encodePaymentSignatureHeader(payload: X402PaymentPayload): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-SIGNATURE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentSignatureHeader(headerValue: string): X402PaymentPayload {\n\treturn decodeHeader<X402PaymentPayload>(X402_HEADER_PAYMENT_SIGNATURE, headerValue);\n}\n\n// ---------------------------------------------------------------------------\n// PAYMENT-RESPONSE\n// ---------------------------------------------------------------------------\n\n/**\n * Encodes an {@link X402SettlementResponse} as a base64 string suitable for\n * the `PAYMENT-RESPONSE` response header.\n */\nexport function encodePaymentResponseHeader(payload: X402SettlementResponse): string {\n\treturn utf8ToBase64(stringifyBigIntSafe(payload));\n}\n\n/**\n * Decodes a `PAYMENT-RESPONSE` header value.\n *\n * @throws {X402InvalidPayloadError} If the header is not valid base64 / JSON /\n * object.\n */\nexport function decodePaymentResponseHeader(headerValue: string): X402SettlementResponse {\n\treturn decodeHeader<X402SettlementResponse>(X402_HEADER_PAYMENT_RESPONSE, headerValue);\n}\n","/**\n * Observability hooks — the base interface that the kawasekit core surfaces\n * (facilitator, x402 handler, wrapFetch) emit events to. Operators wire metrics\n * / logs / traces by passing one of:\n *\n * - their own callback set (zero new dependencies, full control)\n * - one of the optional adapters at `kawasekit/observability/prometheus` or\n * `kawasekit/observability/otlp` (push-button Prometheus / OTLP metrics)\n *\n * Design points worth reading before writing an adapter:\n *\n * - **All hooks are fire-and-forget.** {@link invokeHookSafely} swallows both\n * synchronous throws and rejected Promises so hook misbehaviour cannot\n * destabilise the kawasekit hot path. Adapters should still wrap any\n * external I/O (HTTP exporter pushes, etc.) in their own resilience layer.\n *\n * - **Events carry timing.** Every event extends {@link ObservabilityEventBase}\n * with a `startedAtMs` wall-clock timestamp and a `durationMs` measurement\n * so histograms (Prometheus, OTLP) can be derived without the adapter\n * needing to thread its own clocks.\n *\n * - **No private data leaks.** Hooks intentionally omit signatures, nonces,\n * and authorization bytes. They expose only the public-after-broadcast\n * metadata (payer, amount, network, tx hash, x402 error code) — enough for\n * dashboards, not enough to replay a payment.\n *\n * - **Failure events carry x402 spec error codes verbatim.** The\n * `invalidReason` / `errorReason` fields are the canonical x402 v2 codes\n * (e.g. `insufficient_funds`, `invalid_exact_evm_payload_signature`). This\n * gives adapters a stable label vocabulary that Grafana / Datadog can group\n * by without ad-hoc parsing.\n *\n * @packageDocumentation\n */\n\nimport type { Address, Hex } from \"viem\";\nimport type { X402Network, X402PaymentRequirements } from \"../x402/types\";\n\n// ---------------------------------------------------------------------------\n// Event types\n// ---------------------------------------------------------------------------\n\n/** Fields shared by every observability event. */\nexport interface ObservabilityEventBase {\n\t/** Wall-clock unix milliseconds when the observed operation started. */\n\treadonly startedAtMs: number;\n\t/** Wall-clock duration of the observed operation in milliseconds. */\n\treadonly durationMs: number;\n}\n\n/** Emitted by {@link createSelfFacilitator} after every `verify()` call. */\nexport type VerifyEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"verify\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer: Address;\n\t\t\t/** Authorization amount in token-base units (wei for 18-decimal JPYC). */\n\t\t\treadonly amount: string;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"verify\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly network: X402Network;\n\t\t\t/** Payer address if it was recoverable before the failure. */\n\t\t\treadonly payer?: Address;\n\t\t\t/** x402 v2 invalidReason code (e.g. `invalid_payload`). */\n\t\t\treadonly invalidReason: string;\n\t\t\t/** Human-readable detail; never includes private credentials. */\n\t\t\treadonly invalidMessage?: string;\n\t });\n\n/** Emitted by {@link createSelfFacilitator} after every `settle()` call. */\nexport type SettleEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"settle\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer: Address;\n\t\t\treadonly amount: string;\n\t\t\t/** On-chain transaction hash of the broadcast settlement. */\n\t\t\treadonly transaction: Hex;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"settle\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly network: X402Network;\n\t\t\treadonly payer?: Address;\n\t\t\t/** x402 v2 errorReason code (e.g. `insufficient_funds`). */\n\t\t\treadonly errorReason: string;\n\t\t\treadonly errorMessage?: string;\n\t\t\t/** Tx hash if the broadcast succeeded but the receipt reverted. */\n\t\t\treadonly transaction?: Hex;\n\t });\n\n/** Emitted by {@link createX402Handler} when it returns HTTP 402. */\nexport interface PaymentRequiredEvent extends ObservabilityEventBase {\n\treadonly kind: \"payment_required\";\n\t/** The URL that triggered the paywall, taken from `Request.url`. */\n\treadonly requestUrl: string;\n\t/** Networks listed in the `accepts` array, in order. */\n\treadonly acceptedNetworks: readonly X402Network[];\n}\n\n/** Emitted by {@link createX402Handler} when settlement unlocks the inner handler. */\nexport interface PaymentAcceptedEvent extends ObservabilityEventBase {\n\treadonly kind: \"payment_accepted\";\n\treadonly requestUrl: string;\n\treadonly payer: Address;\n\treadonly amount: string;\n\treadonly network: X402Network;\n\treadonly transaction: Hex;\n}\n\n/** Emitted by {@link wrapFetch} after each paywall round-trip. */\nexport type ClientPaymentEvent =\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"client_payment\";\n\t\t\treadonly result: \"success\";\n\t\t\treadonly requestUrl: string;\n\t\t\treadonly payer: Address;\n\t\t\treadonly amount: string;\n\t\t\treadonly network: X402Network;\n\t\t\t/** Settlement tx hash if the server echoed it back in PAYMENT-RESPONSE. */\n\t\t\treadonly transaction?: Hex;\n\t })\n\t| (ObservabilityEventBase & {\n\t\t\treadonly kind: \"client_payment\";\n\t\t\treadonly result: \"failure\";\n\t\t\treadonly requestUrl: string;\n\t\t\t/** Short label: `onPayment_declined` / `no_acceptable_requirement` / `settle_rejected` / `http_error`. */\n\t\t\treadonly reason: string;\n\t\t\treadonly httpStatus?: number;\n\t });\n\n/** Discriminated union of every event the hook surface may emit. */\nexport type ObservabilityEvent =\n\t| VerifyEvent\n\t| SettleEvent\n\t| PaymentRequiredEvent\n\t| PaymentAcceptedEvent\n\t| ClientPaymentEvent;\n\n// ---------------------------------------------------------------------------\n// Hook callback shapes\n// ---------------------------------------------------------------------------\n\n/** Generic shape of a hook callback. Async hooks are fire-and-forget. */\nexport type HookCallback<TEvent> = (event: TEvent) => void | Promise<void>;\n\n/**\n * The complete kawasekit observability surface. All fields are optional —\n * pass only the hooks for the events you care about.\n *\n * @example\n * ```ts\n * import { createSelfFacilitator } from \"kawasekit\";\n *\n * const facilitator = createSelfFacilitator({\n * network: \"testnet\",\n * walletClient,\n * publicClient,\n * hooks: {\n * onSettle: (event) => {\n * if (event.result === \"success\") {\n * console.log(\"settled\", event.network, event.amount, event.transaction);\n * } else {\n * console.warn(\"settle failed\", event.errorReason);\n * }\n * },\n * },\n * });\n * ```\n */\nexport interface ObservabilityHooks {\n\t/** Fired after every facilitator `verify()`. Discriminate on `event.result`. */\n\treadonly onVerify?: HookCallback<VerifyEvent>;\n\t/** Fired after every facilitator `settle()`. Discriminate on `event.result`. */\n\treadonly onSettle?: HookCallback<SettleEvent>;\n\t/** Fired when the x402 handler returns 402 (no payment yet). */\n\treadonly onPaymentRequired?: HookCallback<PaymentRequiredEvent>;\n\t/** Fired when a settled payment unlocks the inner x402 handler. */\n\treadonly onPaymentAccepted?: HookCallback<PaymentAcceptedEvent>;\n\t/** Fired by `wrapFetch` after each paywall round-trip. */\n\treadonly onClientPayment?: HookCallback<ClientPaymentEvent>;\n}\n\n// ---------------------------------------------------------------------------\n// Safe invocation helper\n// ---------------------------------------------------------------------------\n\n/**\n * Invokes a single optional hook and swallows both synchronous throws and\n * rejected Promises. Use this at every site where the kawasekit core surfaces\n * call user-provided callbacks — it is the contract that guarantees hooks\n * cannot destabilise verify / settle / fetch flows.\n *\n * If a hook misbehaves, the error is discarded silently — kawasekit's\n * observability promise is \"best-effort, never blocking\". Future work\n * (planned in plan D12) may route discarded errors to a structured logger so\n * operators can see hook bugs without paying for them in hot paths.\n *\n * @example\n * ```ts\n * import { invokeHookSafely } from \"kawasekit/observability\";\n *\n * invokeHookSafely(hooks.onSettle, {\n * kind: \"settle\",\n * result: \"success\",\n * startedAtMs,\n * durationMs: Date.now() - startedAtMs,\n * network: \"eip155:80002\",\n * payer,\n * amount,\n * transaction: txHash,\n * });\n * ```\n */\nexport function invokeHookSafely<TEvent>(\n\thook: HookCallback<TEvent> | undefined,\n\tevent: TEvent,\n): void {\n\tif (hook === undefined) return;\n\ttry {\n\t\tconst result = hook(event);\n\t\tif (result instanceof Promise) {\n\t\t\tresult.catch(() => {\n\t\t\t\t// Discard async rejection — observability hooks are fire-and-forget.\n\t\t\t});\n\t\t}\n\t} catch {\n\t\t// Discard sync throw — observability hooks are fire-and-forget.\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Helpers for adapter authors\n// ---------------------------------------------------------------------------\n\n/**\n * Type-safe pluck of the `accepts` network list from a\n * {@link X402PaymentRequirements} array. Adapter authors can use this to build\n * `acceptedNetworks` for {@link PaymentRequiredEvent} without re-implementing\n * the narrow.\n *\n * @example\n * ```ts\n * import { extractAcceptedNetworks } from \"kawasekit/observability\";\n *\n * const acceptedNetworks = extractAcceptedNetworks(requirements);\n * ```\n */\nexport function extractAcceptedNetworks(\n\trequirements: readonly X402PaymentRequirements[],\n): readonly X402Network[] {\n\treturn requirements.map((req) => req.network);\n}\n","/**\n * Facilitator implementations: local viem-backed (`createSelfFacilitator`) and\n * HTTP-proxied (`createHttpFacilitator`).\n *\n * Both expose the same {@link Facilitator} interface — `verify` / `settle` /\n * `supported` — so {@link createX402Handler} can swap one for the other based\n * on environment (testnet vs. mainnet, self-hosted vs. Coinbase CDP).\n *\n * Spec references:\n * - Error codes: x402 v2 spec §9 (Error Handling)\n * - Verification steps: scheme_exact_evm.md §1 Phase 2\n * - Facilitator HTTP API: x402 v2 spec §7\n *\n * @packageDocumentation\n */\n\nimport type { Account, Address, Chain, Hex, PublicClient, Transport, WalletClient } from \"viem\";\nimport { getAddress, parseSignature, recoverTypedDataAddress } from \"viem\";\nimport { getChain, isSupportedChainId, type KawaseChain, type SupportedChainId } from \"../chains\";\nimport {\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n\ttype SettleEvent,\n\ttype VerifyEvent,\n} from \"../observability/hooks\";\nimport { JPYC_EIP712_DOMAIN_HINT, JPYC_V2_ADDRESS, jpycAbi } from \"../tokens/jpyc\";\nimport type {\n\tFacilitator,\n\tX402PaymentRequirements,\n\tX402SettleRequest,\n\tX402SettleResponse,\n\tX402SupportedKind,\n\tX402SupportedResponse,\n\tX402VerifyRequest,\n\tX402VerifyResponse,\n} from \"./types\";\nimport { chainIdToX402Network, X402_VERSION, x402NetworkToChainId } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Error code vocabulary (x402 v2 §9)\n// ---------------------------------------------------------------------------\n\n/**\n * Standard x402 v2 error codes used as `invalidReason` (verify) and\n * `errorReason` (settle). Kept as string literals so that consumers can\n * `switch` on the union; values match the spec verbatim.\n */\nexport const X402_FACILITATOR_ERROR_CODES = {\n\tinsufficient_funds: \"insufficient_funds\",\n\tinvalid_exact_evm_payload_authorization_valid_after:\n\t\t\"invalid_exact_evm_payload_authorization_valid_after\",\n\tinvalid_exact_evm_payload_authorization_valid_before:\n\t\t\"invalid_exact_evm_payload_authorization_valid_before\",\n\tinvalid_exact_evm_payload_authorization_value_mismatch:\n\t\t\"invalid_exact_evm_payload_authorization_value_mismatch\",\n\tinvalid_exact_evm_payload_recipient_mismatch: \"invalid_exact_evm_payload_recipient_mismatch\",\n\tinvalid_exact_evm_payload_signature: \"invalid_exact_evm_payload_signature\",\n\tinvalid_network: \"invalid_network\",\n\tinvalid_payload: \"invalid_payload\",\n\tinvalid_scheme: \"invalid_scheme\",\n\tinvalid_transaction_state: \"invalid_transaction_state\",\n\tunexpected_settle_error: \"unexpected_settle_error\",\n\tunexpected_verify_error: \"unexpected_verify_error\",\n} as const;\n\ntype X402FacilitatorErrorCode =\n\t(typeof X402_FACILITATOR_ERROR_CODES)[keyof typeof X402_FACILITATOR_ERROR_CODES];\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\ninterface NarrowExactEvmPayload {\n\treadonly signature: Hex;\n\treadonly authorization: {\n\t\treadonly from: Address;\n\t\treadonly to: Address;\n\t\treadonly value: string;\n\t\treadonly validAfter: string;\n\t\treadonly validBefore: string;\n\t\treadonly nonce: Hex;\n\t};\n}\n\nfunction isHex(value: unknown): value is Hex {\n\treturn typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n}\n\nfunction isAddressLike(value: unknown): value is Address {\n\treturn typeof value === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(value);\n}\n\nfunction isDecimalString(value: unknown): value is string {\n\treturn typeof value === \"string\" && /^(0|[1-9][0-9]*)$/.test(value);\n}\n\nfunction narrowExactEvmPayload(payload: Record<string, unknown>): NarrowExactEvmPayload | null {\n\tconst p = payload as { signature?: unknown; authorization?: unknown };\n\tif (!isHex(p.signature)) return null;\n\tif (typeof p.authorization !== \"object\" || p.authorization === null) return null;\n\tconst a = p.authorization as {\n\t\tfrom?: unknown;\n\t\tto?: unknown;\n\t\tvalue?: unknown;\n\t\tvalidAfter?: unknown;\n\t\tvalidBefore?: unknown;\n\t\tnonce?: unknown;\n\t};\n\tif (!isAddressLike(a.from)) return null;\n\tif (!isAddressLike(a.to)) return null;\n\tif (!isDecimalString(a.value)) return null;\n\tif (!isDecimalString(a.validAfter)) return null;\n\tif (!isDecimalString(a.validBefore)) return null;\n\tif (!isHex(a.nonce)) return null;\n\treturn {\n\t\tsignature: p.signature,\n\t\tauthorization: {\n\t\t\tfrom: a.from,\n\t\t\tto: a.to,\n\t\t\tvalue: a.value,\n\t\t\tvalidAfter: a.validAfter,\n\t\t\tvalidBefore: a.validBefore,\n\t\t\tnonce: a.nonce,\n\t\t},\n\t};\n}\n\nconst TRANSFER_AUTHORIZATION_TYPES = {\n\tTransferWithAuthorization: [\n\t\t{ name: \"from\", type: \"address\" },\n\t\t{ name: \"to\", type: \"address\" },\n\t\t{ name: \"value\", type: \"uint256\" },\n\t\t{ name: \"validAfter\", type: \"uint256\" },\n\t\t{ name: \"validBefore\", type: \"uint256\" },\n\t\t{ name: \"nonce\", type: \"bytes32\" },\n\t],\n} as const;\n\nfunction resolveDomain(requirements: X402PaymentRequirements): {\n\treadonly name: string;\n\treadonly version: string;\n} {\n\tconst extra = requirements.extra as { name?: unknown; version?: unknown };\n\tif (typeof extra.name === \"string\" && typeof extra.version === \"string\") {\n\t\treturn { name: extra.name, version: extra.version };\n\t}\n\tif (getAddress(requirements.asset) === getAddress(JPYC_V2_ADDRESS)) {\n\t\treturn JPYC_EIP712_DOMAIN_HINT;\n\t}\n\tthrow new Error(\n\t\t\"resolveDomain: `extra.name` and `extra.version` are required for non-JPYC assets\",\n\t);\n}\n\nfunction failVerify(\n\treason: X402FacilitatorErrorCode,\n\tmessage?: string,\n\tpayer?: Address,\n): X402VerifyResponse {\n\tif (message !== undefined && payer !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, invalidMessage: message, payer };\n\t}\n\tif (message !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, invalidMessage: message };\n\t}\n\tif (payer !== undefined) {\n\t\treturn { isValid: false, invalidReason: reason, payer };\n\t}\n\treturn { isValid: false, invalidReason: reason };\n}\n\nfunction failSettle(\n\tnetwork: X402SettleResponse[\"network\"],\n\treason: X402FacilitatorErrorCode,\n\toptions: { message?: string; payer?: Address; transaction?: string } = {},\n): X402SettleResponse {\n\tconst transaction = options.transaction ?? \"\";\n\tconst base: X402SettleResponse = {\n\t\tsuccess: false,\n\t\terrorReason: reason,\n\t\ttransaction,\n\t\tnetwork,\n\t};\n\tif (options.message !== undefined && options.payer !== undefined) {\n\t\treturn { ...base, errorMessage: options.message, payer: options.payer };\n\t}\n\tif (options.message !== undefined) {\n\t\treturn { ...base, errorMessage: options.message };\n\t}\n\tif (options.payer !== undefined) {\n\t\treturn { ...base, payer: options.payer };\n\t}\n\treturn base;\n}\n\n// ---------------------------------------------------------------------------\n// Self-facilitator (local viem-backed)\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link createSelfFacilitator}. */\nexport interface CreateSelfFacilitatorParams {\n\t/**\n\t * Declared production-vs-test intent. MUST agree with `walletClient.chain`:\n\t * - `\"mainnet\"` requires a kawasekit chain with `isTestnet === false`.\n\t * - `\"testnet\"` requires a kawasekit chain with `isTestnet === true`.\n\t *\n\t * The check is enforced at construction time and throws a fatal error on\n\t * disagreement. The point is to make accidentally pointing a testnet\n\t * configuration at a mainnet RPC (or vice versa) impossible — that mistake\n\t * would broadcast real-fund transactions silently.\n\t */\n\treadonly network: \"mainnet\" | \"testnet\";\n\t/**\n\t * Pre-configured wallet client that broadcasts settlement transactions.\n\t * The bound account pays gas. `walletClient.chain.id` determines the only\n\t * chain this facilitator serves, and `walletClient.chain.isTestnet` MUST\n\t * agree with the declared {@link network}.\n\t */\n\treadonly walletClient: WalletClient<Transport, Chain, Account>;\n\t/**\n\t * Pre-configured public client on the same chain as `walletClient`. Used\n\t * for balance and authorization-state reads during verify.\n\t */\n\treadonly publicClient: PublicClient<Transport, Chain>;\n\t/**\n\t * Timeout (ms) for `waitForTransactionReceipt` during settle.\n\t * Defaults to 60_000.\n\t */\n\treadonly receiptTimeoutMs?: number;\n\t/**\n\t * Number of block confirmations to wait past the settle tx inclusion\n\t * before considering settlement final. Mitigates threat 2.8 (settle\n\t * tx reorg producing a \"content delivered, payment reverted\" state)\n\t * by raising the bar past Polygon PoS's typical reorg depth.\n\t *\n\t * Chain-aware defaults if omitted:\n\t * - testnet (Polygon Amoy): `1` — fast feedback for dev loops, no\n\t * real funds at risk\n\t * - mainnet (Polygon): `4` — roughly ~8 s of soft finality at\n\t * Polygon's ~2 s block time, suitable for the small-value paywall\n\t * hits kawasekit targets (sub-100 JPYC per call)\n\t *\n\t * For high-value merchants — or any deployment uncomfortable with\n\t * shallow reorg risk — raise this to 32+ and bump\n\t * {@link receiptTimeoutMs} so the timeout still accommodates the\n\t * wait. See `docs/THREAT_MODEL.md` §2.8 / §6.6.\n\t */\n\treadonly confirmations?: number;\n\t/**\n\t * Optional observability callbacks. Hooks are fire-and-forget — any throw\n\t * or rejection inside a hook is silently discarded and never propagates to\n\t * the verify / settle return path. See {@link ObservabilityHooks}.\n\t *\n\t * The facilitator emits `onVerify` after every `verify()` call (including\n\t * the internal re-verify that runs at the start of `settle()`) and\n\t * `onSettle` after every `settle()` call.\n\t */\n\treadonly hooks?: ObservabilityHooks;\n}\n\nconst RECEIPT_TIMEOUT_FLOOR_MS = 60_000;\nconst RECEIPT_INCLUSION_MS = 15_000;\nconst RECEIPT_TIMEOUT_SLACK = 1.5;\n\n/**\n * Auto-sizes the settle receipt timeout to a confirmation depth and the chain's\n * block time: `max(60_000, 15_000 + confirmations × blockTimeMs × 1.5)`. This is\n * the default {@link CreateSelfFacilitatorParams.receiptTimeoutMs} when the\n * operator does not pass one, so a deep-confirmation chain (Ethereum's `32` ×\n * ~12 s ≈ 10 min) does not time out at the flat 60 s floor, while shallow chains\n * (Polygon) keep the floor. Exposed so operators tuning `confirmations` per the\n * finality recipe (`docs/recipes/facilitator-finality-tuning.md`) can compute a\n * matching timeout.\n *\n * @example\n * ```ts\n * import { deriveReceiptTimeoutMs, ethereum } from \"kawasekit\";\n *\n * deriveReceiptTimeoutMs(ethereum, 32); // ≈ 591_000 ms\n * ```\n */\nexport function deriveReceiptTimeoutMs(chain: KawaseChain, confirmations: number): number {\n\tconst wallMs = RECEIPT_INCLUSION_MS + confirmations * chain.blockTimeMs * RECEIPT_TIMEOUT_SLACK;\n\treturn Math.max(RECEIPT_TIMEOUT_FLOOR_MS, Math.ceil(wallMs));\n}\n\n/**\n * Builds a facilitator that verifies and broadcasts exact-EVM EIP-3009\n * payments using a locally-held EOA private key (gas payer).\n *\n * Intended for self-hosted paywalls and testnet (Polygon Amoy) where the\n * Coinbase CDP facilitator is not guaranteed to support the chain.\n *\n * **Concurrent settle() calls**: under any meaningful load (e.g. an LLM\n * agent fan-out) you will issue multiple `transferWithAuthorization`\n * broadcasts from the same facilitator EOA in parallel. Without local nonce\n * sequencing those broadcasts race for the same on-chain nonce and only\n * one lands. Pass viem's `nonceManager` when constructing the facilitator\n * account to make this safe — see `@example` below.\n *\n * @example\n * ```ts\n * import { createPublicClient, createWalletClient, http } from \"viem\";\n * import { nonceManager, privateKeyToAccount } from \"viem/accounts\";\n * import { createSelfFacilitator, polygonAmoy } from \"kawasekit\";\n *\n * // `nonceManager` is REQUIRED whenever you expect concurrent settlements.\n * const account = privateKeyToAccount(\n * process.env.FACILITATOR_PK as `0x${string}`,\n * { nonceManager },\n * );\n * const transport = http(process.env.RPC_URL);\n * const facilitator = createSelfFacilitator({\n * network: \"testnet\", // must agree with polygonAmoy.isTestnet === true\n * walletClient: createWalletClient({ chain: polygonAmoy, transport, account }),\n * publicClient: createPublicClient({ chain: polygonAmoy, transport }),\n * });\n * ```\n */\nexport function createSelfFacilitator(params: CreateSelfFacilitatorParams): Facilitator {\n\tconst { walletClient, publicClient } = params;\n\tconst facilitatorChainId = walletClient.chain.id;\n\tif (!isSupportedChainId(facilitatorChainId)) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: walletClient.chain.id ${facilitatorChainId} is not a kawasekit-supported chain`,\n\t\t);\n\t}\n\tconst supportedChainId: SupportedChainId = facilitatorChainId;\n\tconst chain = getChain(supportedChainId);\n\tif (params.network === \"mainnet\" && chain.isTestnet) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: network=\"mainnet\" but walletClient.chain \"${chain.name}\" (chainId ${supportedChainId}) is a testnet`,\n\t\t);\n\t}\n\tif (params.network === \"testnet\" && !chain.isTestnet) {\n\t\tthrow new Error(\n\t\t\t`createSelfFacilitator: network=\"testnet\" but walletClient.chain \"${chain.name}\" (chainId ${supportedChainId}) is a mainnet — refusing to broadcast with real funds`,\n\t\t);\n\t}\n\t// Chain-aware confirmation depth (threat 2.8 / §6.6), sourced from the chain\n\t// config (config-as-data): probabilistic chains need depth, deterministic-\n\t// finality chains (Avalanche Snowman / Kaia IBFT) need 1-2, Ethereum ~32.\n\t// Operators override via `params.confirmations`.\n\tconst confirmations = params.confirmations ?? chain.defaultConfirmations;\n\t// `receiptTimeoutMs` auto-sizes to the depth so a deep-confirmation chain does\n\t// not time out at the flat 60 s floor (e.g. Ethereum's 32×12 s). Shallow chains\n\t// (Polygon) keep the 60 s floor. Override to extend further.\n\tconst receiptTimeoutMs = params.receiptTimeoutMs ?? deriveReceiptTimeoutMs(chain, confirmations);\n\n\t// Threat 2.2 (concurrent settle nonce race) enforcement. The facilitator\n\t// will broadcast `transferWithAuthorization` calls in parallel under any\n\t// fan-out workload (LLM agent tool calls are the canonical example).\n\t// Without viem's nonceManager attached, every parallel `writeContract`\n\t// reads the same on-chain nonce and only one tx lands — settlements\n\t// silently dropped. Enforcing this at construction time means the\n\t// failure mode shows up at boot, not at the first parallel hit in\n\t// production. See `docs/THREAT_MODEL.md#22-concurrent-settle-nonce-race`.\n\tif (walletClient.account.nonceManager === undefined) {\n\t\tthrow new Error(\n\t\t\t'createSelfFacilitator: walletClient.account must be constructed with viem\\'s `nonceManager` to serialise nonces under concurrent settle(). Example:\\n import { nonceManager, privateKeyToAccount } from \"viem/accounts\";\\n const account = privateKeyToAccount(pk, { nonceManager });\\n const walletClient = createWalletClient({ chain, transport, account });',\n\t\t);\n\t}\n\n\tconst network = chainIdToX402Network(supportedChainId);\n\tconst hooks = params.hooks;\n\n\tfunction buildVerifyEvent(\n\t\treq: X402VerifyRequest,\n\t\tresponse: X402VerifyResponse,\n\t\tstartedAtMs: number,\n\t): VerifyEvent {\n\t\tconst durationMs = Date.now() - startedAtMs;\n\t\tconst eventNetwork = req.paymentRequirements.network;\n\t\tif (response.isValid && response.payer !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"verify\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tpayer: response.payer,\n\t\t\t\tamount: req.paymentRequirements.amount,\n\t\t\t};\n\t\t}\n\t\tif (response.isValid) {\n\t\t\t// verifyCore always sets payer on success, but the X402VerifyResponse\n\t\t\t// type permits it to be absent; downgrade to a synthetic failure\n\t\t\t// event so the discriminated union remains sound for adapters.\n\t\t\treturn {\n\t\t\t\tkind: \"verify\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tinvalidReason: \"unexpected_verify_error\",\n\t\t\t\tinvalidMessage: \"verify succeeded but payer was not surfaced\",\n\t\t\t};\n\t\t}\n\t\tconst base = {\n\t\t\tkind: \"verify\" as const,\n\t\t\tresult: \"failure\" as const,\n\t\t\tstartedAtMs,\n\t\t\tdurationMs,\n\t\t\tnetwork: eventNetwork,\n\t\t\tinvalidReason: response.invalidReason ?? \"unexpected_verify_error\",\n\t\t};\n\t\tif (response.payer !== undefined && response.invalidMessage !== undefined) {\n\t\t\treturn { ...base, payer: response.payer, invalidMessage: response.invalidMessage };\n\t\t}\n\t\tif (response.payer !== undefined) {\n\t\t\treturn { ...base, payer: response.payer };\n\t\t}\n\t\tif (response.invalidMessage !== undefined) {\n\t\t\treturn { ...base, invalidMessage: response.invalidMessage };\n\t\t}\n\t\treturn base;\n\t}\n\n\tfunction buildSettleEvent(\n\t\treq: X402SettleRequest,\n\t\tresponse: X402SettleResponse,\n\t\tstartedAtMs: number,\n\t): SettleEvent {\n\t\tconst durationMs = Date.now() - startedAtMs;\n\t\tconst eventNetwork = req.paymentRequirements.network;\n\t\tif (response.success && response.payer !== undefined) {\n\t\t\treturn {\n\t\t\t\tkind: \"settle\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\tpayer: response.payer,\n\t\t\t\tamount: req.paymentRequirements.amount,\n\t\t\t\ttransaction: response.transaction as Hex,\n\t\t\t};\n\t\t}\n\t\tif (response.success) {\n\t\t\t// settleCore always sets payer on success; the spec response type\n\t\t\t// permits it to be absent so we downgrade to a synthetic failure\n\t\t\t// rather than emit a malformed event.\n\t\t\treturn {\n\t\t\t\tkind: \"settle\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs,\n\t\t\t\tnetwork: eventNetwork,\n\t\t\t\terrorReason: \"unexpected_settle_error\",\n\t\t\t\terrorMessage: \"settle succeeded but payer was not surfaced\",\n\t\t\t\ttransaction: response.transaction as Hex,\n\t\t\t};\n\t\t}\n\t\tconst base = {\n\t\t\tkind: \"settle\" as const,\n\t\t\tresult: \"failure\" as const,\n\t\t\tstartedAtMs,\n\t\t\tdurationMs,\n\t\t\tnetwork: eventNetwork,\n\t\t\terrorReason: response.errorReason ?? \"unexpected_settle_error\",\n\t\t};\n\t\tconst withPayer = response.payer !== undefined ? { ...base, payer: response.payer } : base;\n\t\tconst withMessage =\n\t\t\tresponse.errorMessage !== undefined\n\t\t\t\t? { ...withPayer, errorMessage: response.errorMessage }\n\t\t\t\t: withPayer;\n\t\tif (response.transaction !== \"\" && response.transaction !== undefined) {\n\t\t\treturn { ...withMessage, transaction: response.transaction as Hex };\n\t\t}\n\t\treturn withMessage;\n\t}\n\n\tasync function verifyCore(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\t// 1. Scheme / network gates\n\t\tif (req.paymentRequirements.scheme !== \"exact\") {\n\t\t\treturn failVerify(\"invalid_scheme\");\n\t\t}\n\t\tif (req.paymentPayload.accepted.scheme !== \"exact\") {\n\t\t\treturn failVerify(\"invalid_scheme\");\n\t\t}\n\t\tconst reqChainId = x402NetworkToChainId(req.paymentRequirements.network);\n\t\tif (reqChainId !== supportedChainId) {\n\t\t\treturn failVerify(\"invalid_network\");\n\t\t}\n\t\tif (req.paymentPayload.accepted.network !== req.paymentRequirements.network) {\n\t\t\treturn failVerify(\"invalid_network\");\n\t\t}\n\n\t\t// 2. Narrow scheme-specific payload\n\t\tconst exact = narrowExactEvmPayload(req.paymentPayload.payload);\n\t\tif (exact === null) {\n\t\t\treturn failVerify(\"invalid_payload\");\n\t\t}\n\t\tconst auth = exact.authorization;\n\n\t\t// 3. Parameter matching against requirements\n\t\tif (auth.value !== req.paymentRequirements.amount) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_value_mismatch\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (getAddress(auth.to) !== getAddress(req.paymentRequirements.payTo)) {\n\t\t\treturn failVerify(\"invalid_exact_evm_payload_recipient_mismatch\", undefined, auth.from);\n\t\t}\n\n\t\t// 4. Time window\n\t\tconst now = BigInt(Math.floor(Date.now() / 1000));\n\t\tconst validAfter = BigInt(auth.validAfter);\n\t\tconst validBefore = BigInt(auth.validBefore);\n\t\tif (now < validAfter) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_valid_after\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (now >= validBefore) {\n\t\t\treturn failVerify(\n\t\t\t\t\"invalid_exact_evm_payload_authorization_valid_before\",\n\t\t\t\tundefined,\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\n\t\t// 5. Signature recovery\n\t\tlet recovered: Address;\n\t\ttry {\n\t\t\tconst domain = resolveDomain(req.paymentRequirements);\n\t\t\trecovered = await recoverTypedDataAddress({\n\t\t\t\tdomain: {\n\t\t\t\t\tname: domain.name,\n\t\t\t\t\tversion: domain.version,\n\t\t\t\t\tchainId: reqChainId,\n\t\t\t\t\tverifyingContract: req.paymentRequirements.asset,\n\t\t\t\t},\n\t\t\t\ttypes: TRANSFER_AUTHORIZATION_TYPES,\n\t\t\t\tprimaryType: \"TransferWithAuthorization\",\n\t\t\t\tmessage: {\n\t\t\t\t\tfrom: auth.from,\n\t\t\t\t\tto: auth.to,\n\t\t\t\t\tvalue: BigInt(auth.value),\n\t\t\t\t\tvalidAfter,\n\t\t\t\t\tvalidBefore,\n\t\t\t\t\tnonce: auth.nonce,\n\t\t\t\t},\n\t\t\t\tsignature: exact.signature,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn failVerify(\n\t\t\t\t\"unexpected_verify_error\",\n\t\t\t\tcause instanceof Error ? cause.message : String(cause),\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\t\tif (getAddress(recovered) !== getAddress(auth.from)) {\n\t\t\treturn failVerify(\"invalid_exact_evm_payload_signature\", undefined, auth.from);\n\t\t}\n\n\t\t// 6. On-chain reads: balance + nonce-not-used\n\t\ttry {\n\t\t\tconst [balance, used] = await Promise.all([\n\t\t\t\tpublicClient.readContract({\n\t\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\t\tabi: jpycAbi,\n\t\t\t\t\tfunctionName: \"balanceOf\",\n\t\t\t\t\targs: [auth.from],\n\t\t\t\t}),\n\t\t\t\tpublicClient.readContract({\n\t\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\t\tabi: jpycAbi,\n\t\t\t\t\tfunctionName: \"authorizationState\",\n\t\t\t\t\targs: [auth.from, auth.nonce],\n\t\t\t\t}),\n\t\t\t]);\n\t\t\tif (used) {\n\t\t\t\treturn failVerify(\"invalid_payload\", \"authorization nonce already used\", auth.from);\n\t\t\t}\n\t\t\tif ((balance as bigint) < BigInt(auth.value)) {\n\t\t\t\treturn failVerify(\"insufficient_funds\", undefined, auth.from);\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\treturn failVerify(\n\t\t\t\t\"unexpected_verify_error\",\n\t\t\t\tcause instanceof Error ? cause.message : String(cause),\n\t\t\t\tauth.from,\n\t\t\t);\n\t\t}\n\n\t\treturn { isValid: true, payer: auth.from };\n\t}\n\n\tasync function settleCore(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\t// Re-verify before broadcasting. The wrapped `verify` is used so the\n\t\t// internal re-verify also emits onVerify; operators can dedupe in their\n\t\t// hook if they don't want the extra event.\n\t\tconst verifyResult = await verify(req);\n\t\tif (!verifyResult.isValid) {\n\t\t\treturn failSettle(\n\t\t\t\treq.paymentRequirements.network,\n\t\t\t\t(verifyResult.invalidReason as X402FacilitatorErrorCode) ?? \"unexpected_settle_error\",\n\t\t\t\t{\n\t\t\t\t\t...(verifyResult.invalidMessage !== undefined\n\t\t\t\t\t\t? { message: verifyResult.invalidMessage }\n\t\t\t\t\t\t: {}),\n\t\t\t\t\t...(verifyResult.payer !== undefined ? { payer: verifyResult.payer } : {}),\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\n\t\tconst exact = narrowExactEvmPayload(req.paymentPayload.payload);\n\t\tif (exact === null) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"invalid_payload\");\n\t\t}\n\t\tconst auth = exact.authorization;\n\t\tconst parsed = parseSignature(exact.signature);\n\t\tconst v = parsed.v !== undefined ? Number(parsed.v) : (parsed.yParity ?? 0) + 27;\n\n\t\tlet txHash: Hex;\n\t\ttry {\n\t\t\ttxHash = await walletClient.writeContract({\n\t\t\t\taddress: req.paymentRequirements.asset,\n\t\t\t\tabi: jpycAbi,\n\t\t\t\tfunctionName: \"transferWithAuthorization\",\n\t\t\t\targs: [\n\t\t\t\t\tauth.from,\n\t\t\t\t\tauth.to,\n\t\t\t\t\tBigInt(auth.value),\n\t\t\t\t\tBigInt(auth.validAfter),\n\t\t\t\t\tBigInt(auth.validBefore),\n\t\t\t\t\tauth.nonce,\n\t\t\t\t\tv,\n\t\t\t\t\tparsed.r,\n\t\t\t\t\tparsed.s,\n\t\t\t\t],\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"unexpected_settle_error\", {\n\t\t\t\tmessage: cause instanceof Error ? cause.message : String(cause),\n\t\t\t\tpayer: auth.from,\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tconst receipt = await publicClient.waitForTransactionReceipt({\n\t\t\t\thash: txHash,\n\t\t\t\ttimeout: receiptTimeoutMs,\n\t\t\t\tconfirmations,\n\t\t\t});\n\t\t\tif (receipt.status !== \"success\") {\n\t\t\t\treturn failSettle(req.paymentRequirements.network, \"invalid_transaction_state\", {\n\t\t\t\t\ttransaction: txHash,\n\t\t\t\t\tpayer: auth.from,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (cause) {\n\t\t\treturn failSettle(req.paymentRequirements.network, \"unexpected_settle_error\", {\n\t\t\t\tmessage: cause instanceof Error ? cause.message : String(cause),\n\t\t\t\tpayer: auth.from,\n\t\t\t\ttransaction: txHash,\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\ttransaction: txHash,\n\t\t\tnetwork: req.paymentRequirements.network,\n\t\t\tpayer: auth.from,\n\t\t\tamount: auth.value,\n\t\t};\n\t}\n\n\tasync function verify(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\tconst startedAtMs = Date.now();\n\t\tconst result = await verifyCore(req);\n\t\tinvokeHookSafely(hooks?.onVerify, buildVerifyEvent(req, result, startedAtMs));\n\t\treturn result;\n\t}\n\n\tasync function settle(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\tconst startedAtMs = Date.now();\n\t\tconst result = await settleCore(req);\n\t\tinvokeHookSafely(hooks?.onSettle, buildSettleEvent(req, result, startedAtMs));\n\t\treturn result;\n\t}\n\n\tasync function supportedInternal(): Promise<X402SupportedResponse> {\n\t\tconst kind: X402SupportedKind = {\n\t\t\tx402Version: X402_VERSION,\n\t\t\tscheme: \"exact\",\n\t\t\tnetwork,\n\t\t};\n\t\treturn {\n\t\t\tkinds: [kind],\n\t\t\textensions: [],\n\t\t\tsigners: { \"eip155:*\": [walletClient.account.address] },\n\t\t};\n\t}\n\n\treturn {\n\t\tverify,\n\t\tsettle,\n\t\tsupported: supportedInternal,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// HTTP-proxied facilitator (Coinbase CDP and any other x402 v2-compliant\n// facilitator endpoint)\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link createHttpFacilitator}. */\nexport interface CreateHttpFacilitatorParams {\n\t/**\n\t * Base URL of the facilitator service (Coinbase CDP, your own host, any\n\t * x402 v2-compliant endpoint). Endpoints `/verify`, `/settle`, `/supported`\n\t * are POST / POST / GET respectively relative to this URL. Trailing slash\n\t * is stripped.\n\t */\n\treadonly baseUrl: string;\n\t/**\n\t * Optional callback invoked per request that returns headers to merge\n\t * into the outbound request (typically `Authorization`). Receives the\n\t * endpoint name so the caller can compute distinct signatures per route.\n\t */\n\treadonly getAuthHeaders?: (\n\t\tendpoint: \"verify\" | \"settle\" | \"supported\",\n\t) => Promise<Record<string, string>> | Record<string, string>;\n\t/**\n\t * Override the global `fetch` (e.g. for in-process testing or to inject\n\t * an `undici` Agent in Node).\n\t */\n\treadonly fetch?: typeof fetch;\n}\n\n/**\n * Builds a facilitator that proxies all RPC over HTTP to a remote endpoint,\n * matching the request / response shapes of x402 v2 spec §7.\n *\n * Works with any x402 v2-compliant facilitator — Coinbase CDP, your own\n * self-hosted facilitator behind nginx, a regional mirror — as long as it\n * exposes `/verify`, `/settle`, and `/supported` per the spec.\n *\n * If your target facilitator doesn't support the chain you need, fall back\n * to {@link createSelfFacilitator} (in-process viem broadcaster).\n *\n * @example\n * ```ts\n * import { createHttpFacilitator } from \"kawasekit\";\n *\n * const facilitator = createHttpFacilitator({\n * baseUrl: process.env.X402_FACILITATOR_URL!, // e.g. Coinbase CDP endpoint\n * getAuthHeaders: () => ({ Authorization: `Bearer ${apiKey}` }),\n * });\n * ```\n */\nexport function createHttpFacilitator(params: CreateHttpFacilitatorParams): Facilitator {\n\tconst baseUrl = params.baseUrl.replace(/\\/$/, \"\");\n\tconst fetchImpl = params.fetch ?? fetch;\n\tconst getAuthHeaders = params.getAuthHeaders;\n\n\tasync function post<TResponse>(endpoint: \"verify\" | \"settle\", body: unknown): Promise<TResponse> {\n\t\tconst headers: Record<string, string> = { \"content-type\": \"application/json\" };\n\t\tif (getAuthHeaders) {\n\t\t\tObject.assign(headers, await getAuthHeaders(endpoint));\n\t\t}\n\t\tconst response = await fetchImpl(`${baseUrl}/${endpoint}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\t\tconst text = await response.text();\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = text === \"\" ? null : JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator ${endpoint} returned non-JSON (status ${response.status}): ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator ${endpoint} failed (status ${response.status}): ${JSON.stringify(parsed).slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\treturn parsed as TResponse;\n\t}\n\n\tasync function verifyInternal(req: X402VerifyRequest): Promise<X402VerifyResponse> {\n\t\treturn post<X402VerifyResponse>(\"verify\", {\n\t\t\tx402Version: req.x402Version,\n\t\t\tpaymentPayload: req.paymentPayload,\n\t\t\tpaymentRequirements: req.paymentRequirements,\n\t\t});\n\t}\n\n\tasync function settleInternal(req: X402SettleRequest): Promise<X402SettleResponse> {\n\t\treturn post<X402SettleResponse>(\"settle\", {\n\t\t\tx402Version: req.x402Version,\n\t\t\tpaymentPayload: req.paymentPayload,\n\t\t\tpaymentRequirements: req.paymentRequirements,\n\t\t});\n\t}\n\n\tasync function supportedInternal(): Promise<X402SupportedResponse> {\n\t\tconst headers: Record<string, string> = {};\n\t\tif (getAuthHeaders) {\n\t\t\tObject.assign(headers, await getAuthHeaders(\"supported\"));\n\t\t}\n\t\tconst response = await fetchImpl(`${baseUrl}/supported`, { method: \"GET\", headers });\n\t\tconst text = await response.text();\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = text === \"\" ? null : JSON.parse(text);\n\t\t} catch {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator supported returned non-JSON (status ${response.status}): ${text.slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Facilitator supported failed (status ${response.status}): ${JSON.stringify(parsed).slice(0, 200)}`,\n\t\t\t);\n\t\t}\n\t\treturn parsed as X402SupportedResponse;\n\t}\n\n\treturn {\n\t\tverify: verifyInternal,\n\t\tsettle: settleInternal,\n\t\tsupported: supportedInternal,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Deprecated aliases (M3-era names)\n//\n// The HTTP-proxied facilitator used to be called `createCoinbaseFacilitator`\n// because the only x402 v2-compliant endpoint we tested against at the time\n// was Coinbase CDP. The function was never Coinbase-specific — it speaks the\n// raw x402 v2 HTTP shape — and the rename to `createHttpFacilitator` lands in\n// v0.1.0-alpha to make that obvious before the npm publish freezes the API.\n//\n// The aliases below preserve M3-era call sites for the v0.1.x line. Calling\n// `createCoinbaseFacilitator` emits a one-shot Node DeprecationWarning. The\n// aliases will be removed in v0.2.0.\n// ---------------------------------------------------------------------------\n\n/**\n * @deprecated Renamed to {@link CreateHttpFacilitatorParams} in v0.1.0-alpha.\n * The HTTP facilitator works with any x402 v2-compliant endpoint, not only\n * Coinbase CDP. This alias will be removed in v0.2.0.\n */\nexport type CreateCoinbaseFacilitatorParams = CreateHttpFacilitatorParams;\n\nlet warnedCreateCoinbaseFacilitator = false;\n\n/**\n * @deprecated Renamed to {@link createHttpFacilitator} in v0.1.0-alpha.\n * This alias delegates to the new function and emits one\n * `DeprecationWarning` per process on first call. It will be removed in\n * v0.2.0.\n */\nexport function createCoinbaseFacilitator(params: CreateHttpFacilitatorParams): Facilitator {\n\tif (!warnedCreateCoinbaseFacilitator) {\n\t\twarnedCreateCoinbaseFacilitator = true;\n\t\tprocess.emitWarning(\n\t\t\t\"createCoinbaseFacilitator() is deprecated and will be removed in kawasekit v0.2.0. Use createHttpFacilitator() instead — the function works with any x402 v2-compliant HTTP endpoint, not only Coinbase CDP.\",\n\t\t\t{ type: \"DeprecationWarning\", code: \"KAWASEKIT_DEP_001\" },\n\t\t);\n\t}\n\treturn createHttpFacilitator(params);\n}\n","/**\n * `wrapFetch()` — turn any WHATWG `fetch` implementation into an x402-aware\n * client.\n *\n * The returned function makes a first request as usual. If the server replies\n * with `402 Payment Required`, the wrapper decodes the `PAYMENT-REQUIRED`\n * header (or response body as a fallback), picks one entry from `accepts`,\n * signs it with the configured {@link X402PaymentSigner}, and retries the\n * same request with a `PAYMENT-SIGNATURE` header. Non-402 responses are\n * returned unchanged.\n *\n * The wrapper does **not** poll or back off — the latency budget (Polygon Amoy\n * bundler inclusion can take ~60 s) lives entirely on the server side, which\n * holds the connection open while it broadcasts and waits for the receipt.\n * If the second attempt still fails the wrapper returns that response so the\n * caller can decide how to recover.\n *\n * Streaming request bodies are not retry-safe; the wrapper passes `init.body`\n * through verbatim, so callers who need retry must pass a buffered body\n * (string / Uint8Array / ArrayBuffer / FormData).\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport {\n\ttype ClientPaymentEvent,\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n} from \"../observability/hooks\";\nimport type { X402PaymentSigner } from \"./client\";\nimport {\n\tdecodePaymentRequiredHeader,\n\tdecodePaymentResponseHeader,\n\tencodePaymentSignatureHeader,\n\tX402_HEADER_IDEMPOTENCY_KEY,\n\tX402_HEADER_PAYMENT_REQUIRED,\n\tX402_HEADER_PAYMENT_RESPONSE,\n\tX402_HEADER_PAYMENT_SIGNATURE,\n} from \"./encoding\";\nimport type { X402PaymentRequiredResponse, X402PaymentRequirements } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Function shape matching the WHATWG `fetch` global. */\nexport type X402Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\n/** Parameters for {@link wrapFetch}. */\nexport interface WrapFetchParams {\n\t/**\n\t * The signer used to produce {@link X402PaymentPayload}s when the server\n\t * returns 402. Bound to one EOA.\n\t */\n\treadonly signer: X402PaymentSigner;\n\t/**\n\t * Optional underlying fetch implementation. Defaults to `globalThis.fetch`.\n\t */\n\treadonly fetch?: X402Fetch;\n\t/**\n\t * Optional policy for choosing one entry from the server's `accepts` list.\n\t * Defaults to the first entry. Return `null` to abort — the original 402\n\t * response is returned without retry.\n\t */\n\treadonly selectRequirements?: (\n\t\taccepts: readonly X402PaymentRequirements[],\n\t\tresponse: Response,\n\t) => X402PaymentRequirements | null;\n\t/**\n\t * Required gate invoked just before the retry request goes out. Receives\n\t * the chosen requirements and the parsed 402 body so the caller can log\n\t * spending, prompt the user, or enforce a budget.\n\t *\n\t * Returning `false` aborts the retry — the original 402 is returned.\n\t * Returning `true` (or `undefined`) proceeds with the signed retry.\n\t *\n\t * This callback is **required** at the type level: a 402 retry transfers\n\t * real funds, and kawasekit refuses to default to \"always pay\" silently.\n\t * If your caller already enforces a budget elsewhere, return `true`\n\t * explicitly — the empty function `() => true` is a deliberate opt-in.\n\t *\n\t * See `docs/THREAT_MODEL.md` Threat 1.8 / §6.1.\n\t */\n\treadonly onPayment: (\n\t\trequirements: X402PaymentRequirements,\n\t\tpaymentRequired: X402PaymentRequiredResponse,\n\t) => boolean | undefined | Promise<boolean | undefined>;\n\t/**\n\t * Optional observability callbacks. {@link wrapFetch} emits an\n\t * `onClientPayment` event for every paywall round-trip — `success` when the\n\t * retry returns 2xx with a PAYMENT-RESPONSE header, `failure` otherwise\n\t * (including `onPayment` declining the retry).\n\t */\n\treadonly hooks?: ObservabilityHooks;\n\t/**\n\t * Optional mapper from a request to a reasoning-step idempotency key (M5-1).\n\t * When it returns a key, the key is (a) sent as the `Idempotency-Key` request\n\t * header so the server can deduplicate, and (b) forwarded into the signer so\n\t * the EIP-3009 nonce is derived deterministically (on-chain backstop). Return\n\t * `undefined` to fall back to today's random-nonce behaviour. Build keys with\n\t * `createIdempotencyKeyBuilder` from `kawasekit/idempotency` at the agent\n\t * harness's tool-execution boundary, where the reasoning-step intent is visible.\n\t */\n\treadonly idempotencyKeyFor?: (\n\t\tinput: string | URL | Request,\n\t\trequirements: X402PaymentRequirements,\n\t\tpaymentRequired: X402PaymentRequiredResponse,\n\t) => string | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nasync function readPaymentRequired(\n\tresponse: Response,\n): Promise<X402PaymentRequiredResponse | null> {\n\tconst headerValue = response.headers.get(X402_HEADER_PAYMENT_REQUIRED);\n\tif (headerValue !== null && headerValue !== \"\") {\n\t\ttry {\n\t\t\treturn decodePaymentRequiredHeader(headerValue);\n\t\t} catch {\n\t\t\t// Fall through to body parse — the header was malformed but the\n\t\t\t// body might still be intact (or vice versa).\n\t\t}\n\t}\n\ttry {\n\t\tconst body = await response.clone().text();\n\t\tif (body === \"\") return null;\n\t\tconst parsed = JSON.parse(body) as unknown;\n\t\tif (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn parsed as X402PaymentRequiredResponse;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction defaultSelectRequirements(\n\taccepts: readonly X402PaymentRequirements[],\n): X402PaymentRequirements | null {\n\treturn accepts[0] ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Returns an x402-aware `fetch` that pays for `402` responses on the caller's\n * behalf using the provided signer.\n *\n * @example\n * ```ts\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { createX402PaymentSigner, wrapFetch } from \"kawasekit\";\n *\n * const signer = createX402PaymentSigner({\n * account: privateKeyToAccount(process.env.PAYER_PK as `0x${string}`),\n * });\n *\n * let spent = 0n;\n * const MAX_SPEND = 100_000n; // 100 JPYC (6 decimals)\n * const fetch402 = wrapFetch({\n * signer,\n * onPayment: (req) => {\n * const next = spent + BigInt(req.amount);\n * if (next > MAX_SPEND) return false; // budget exhausted\n * spent = next;\n * return true;\n * },\n * });\n *\n * const res = await fetch402(\"https://api.example.com/weather?city=Tokyo\");\n * console.log(await res.json());\n * ```\n */\nexport function wrapFetch(params: WrapFetchParams): X402Fetch {\n\tconst baseFetch: X402Fetch = params.fetch ?? ((input, init) => fetch(input, init));\n\tconst selectRequirements = params.selectRequirements ?? defaultSelectRequirements;\n\tconst onPayment = params.onPayment;\n\tconst hooks = params.hooks;\n\n\treturn async function x402Fetch(input, init) {\n\t\tconst startedAtMs = Date.now();\n\t\tconst requestUrl =\n\t\t\ttypeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n\n\t\tconst emitFailure = (reason: string, httpStatus: number | undefined): void => {\n\t\t\tconst event: ClientPaymentEvent = {\n\t\t\t\tkind: \"client_payment\",\n\t\t\t\tresult: \"failure\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl,\n\t\t\t\treason,\n\t\t\t\t...(httpStatus !== undefined ? { httpStatus } : {}),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onClientPayment, event);\n\t\t};\n\n\t\tconst initialResponse = await baseFetch(input, init);\n\t\tif (initialResponse.status !== 402) {\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst paymentRequired = await readPaymentRequired(initialResponse);\n\t\tif (paymentRequired === null || paymentRequired.accepts.length === 0) {\n\t\t\temitFailure(\"no_acceptable_requirement\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst chosen = selectRequirements(paymentRequired.accepts, initialResponse);\n\t\tif (chosen === null) {\n\t\t\temitFailure(\"no_acceptable_requirement\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst proceed = await onPayment(chosen, paymentRequired);\n\t\tif (proceed === false) {\n\t\t\temitFailure(\"onPayment_declined\", 402);\n\t\t\treturn initialResponse;\n\t\t}\n\n\t\tconst idempotencyKey = params.idempotencyKeyFor?.(input, chosen, paymentRequired);\n\n\t\tconst paymentPayload = await params.signer.sign({\n\t\t\tpaymentRequirements: chosen,\n\t\t\t...(paymentRequired.resource ? { resource: paymentRequired.resource } : {}),\n\t\t\t...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n\t\t});\n\n\t\tconst retryHeaders = new Headers(init?.headers);\n\t\tretryHeaders.set(X402_HEADER_PAYMENT_SIGNATURE, encodePaymentSignatureHeader(paymentPayload));\n\t\tif (idempotencyKey !== undefined) {\n\t\t\tretryHeaders.set(X402_HEADER_IDEMPOTENCY_KEY, idempotencyKey);\n\t\t}\n\n\t\tconst retryResponse = await baseFetch(input, { ...init, headers: retryHeaders });\n\n\t\tif (retryResponse.status >= 200 && retryResponse.status < 300) {\n\t\t\tconst settlementHeader = retryResponse.headers.get(X402_HEADER_PAYMENT_RESPONSE);\n\t\t\tlet transaction: Hex | undefined;\n\t\t\tif (settlementHeader !== null && settlementHeader !== \"\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst settlement = decodePaymentResponseHeader(settlementHeader);\n\t\t\t\t\tif (settlement.transaction !== \"\") {\n\t\t\t\t\t\ttransaction = settlement.transaction as Hex;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// PAYMENT-RESPONSE header malformed — the retry still\n\t\t\t\t\t// succeeded so we treat that as a (degraded) success event.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst successEvent: ClientPaymentEvent = {\n\t\t\t\tkind: \"client_payment\",\n\t\t\t\tresult: \"success\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl,\n\t\t\t\tpayer: params.signer.address,\n\t\t\t\tamount: chosen.amount,\n\t\t\t\tnetwork: chosen.network,\n\t\t\t\t...(transaction !== undefined ? { transaction } : {}),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onClientPayment, successEvent);\n\t\t} else {\n\t\t\temitFailure(\n\t\t\t\tretryResponse.status === 402 ? \"settle_rejected\" : \"http_error\",\n\t\t\t\tretryResponse.status,\n\t\t\t);\n\t\t}\n\n\t\treturn retryResponse;\n\t};\n}\n","/**\n * Server-side builders for x402 v2 `PAYMENT-REQUIRED` payloads.\n *\n * `buildPaymentRequirements()` produces one accepted-payment entry; servers\n * call it once per (chain × asset) they want to advertise. `buildPaymentRequiredResponse()`\n * wraps a list of those entries into the full body the server returns alongside\n * an HTTP 402 status (typically also encoded into the `PAYMENT-REQUIRED`\n * header — see `src/x402/encoding.ts`).\n *\n * These factories live on the **server** side. The mirror-image client-side\n * factory is `createX402PaymentSigner()` in `client.ts`.\n *\n * @packageDocumentation\n */\n\nimport type { Address } from \"viem\";\nimport { getAddress, isAddress } from \"viem\";\nimport type { SupportedChainId } from \"../chains\";\nimport { JPYC_V2_ADDRESS } from \"../tokens/jpyc\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport type {\n\tX402PaymentRequiredResponse,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n} from \"./types\";\nimport { chainIdToX402Network, X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default value for `maxTimeoutSeconds` when {@link BuildPaymentRequirementsParams.maxTimeoutSeconds}\n * is not supplied. Matches the x402 spec example for short-lived authorizations.\n *\n * Increase to 300 (the client-side default) when targeting Polygon Amoy in the\n * M3 demo — bundler inclusion latency can spike above 60 s on testnet.\n */\nexport const X402_DEFAULT_MAX_TIMEOUT_SECONDS = 60;\n\n/** Default `extra` payload kawasekit injects when the asset is JPYC. */\nconst JPYC_EXACT_EVM_EXTRA = {\n\tassetTransferMethod: \"eip3009\",\n\tname: \"JPY Coin\",\n\tversion: \"1\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Parameters for {@link buildPaymentRequirements}. */\nexport interface BuildPaymentRequirementsParams {\n\t/** Numeric chain ID; converted to the CAIP-2 `eip155:{chainId}` form. */\n\treadonly chainId: SupportedChainId;\n\t/** ERC-20 contract address of the token to be transferred. */\n\treadonly asset: Address;\n\t/** Recipient wallet address. */\n\treadonly payTo: Address;\n\t/** Atomic-unit amount. Accepts `bigint` (preferred) or a decimal `string`. */\n\treadonly amount: bigint | string;\n\t/**\n\t * Optional. Defaults to {@link X402_DEFAULT_MAX_TIMEOUT_SECONDS}.\n\t *\n\t * The maximum wall-clock time the client may take to produce a signed\n\t * payload after receiving this 402 response.\n\t */\n\treadonly maxTimeoutSeconds?: number;\n\t/**\n\t * Optional explicit `extra` payload. When omitted and `asset` is JPYC,\n\t * kawasekit injects a default `{ assetTransferMethod: \"eip3009\", name: \"JPY Coin\", version: \"1\" }`.\n\t * For non-JPYC assets `extra` is required (the client needs at least\n\t * `name` / `version` to reconstruct the EIP-712 domain).\n\t */\n\treadonly extra?: Record<string, unknown>;\n}\n\n/** Parameters for {@link buildPaymentRequiredResponse}. */\nexport interface BuildPaymentRequiredResponseParams {\n\t/** The protected resource the client is being asked to pay for. */\n\treadonly resource: X402ResourceInfo;\n\t/** One or more acceptable payment methods. */\n\treadonly accepts: readonly X402PaymentRequirements[];\n\t/** Optional human-readable reason for the 402, echoed in the response body. */\n\treadonly error?: string;\n\t/** Optional protocol extensions (advanced; rarely set). */\n\treadonly extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst UINT256_MAX = (1n << 256n) - 1n;\nconst UINT256_DECIMAL = /^(0|[1-9][0-9]*)$/;\n\nfunction coerceAmount(amount: bigint | string): string {\n\tif (typeof amount === \"bigint\") {\n\t\tif (amount <= 0n) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` must be positive, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\tif (amount > UINT256_MAX) {\n\t\t\tthrow new X402InvalidPayloadError(\n\t\t\t\t\"PaymentRequirements\",\n\t\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t\t);\n\t\t}\n\t\treturn amount.toString();\n\t}\n\tif (!UINT256_DECIMAL.test(amount)) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` must be a non-negative decimal string, got ${JSON.stringify(amount)}`,\n\t\t);\n\t}\n\tconst parsed = BigInt(amount);\n\tif (parsed === 0n) {\n\t\tthrow new X402InvalidPayloadError(\"PaymentRequirements\", \"`amount` must be positive\");\n\t}\n\tif (parsed > UINT256_MAX) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`amount\\` exceeds uint256, got ${amount}`,\n\t\t);\n\t}\n\treturn amount;\n}\n\nfunction assertAddress(value: string, field: string): Address {\n\tif (!isAddress(value, { strict: false })) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`${field}\\` is not a valid address: ${value}`,\n\t\t);\n\t}\n\treturn value as Address;\n}\n\nfunction resolveExtra(\n\tasset: Address,\n\texplicit: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\tif (getAddress(asset) === getAddress(JPYC_V2_ADDRESS)) {\n\t\treturn { ...JPYC_EXACT_EVM_EXTRA };\n\t}\n\tthrow new X402InvalidPayloadError(\n\t\t\"PaymentRequirements\",\n\t\t\"`extra` is required for non-JPYC assets (clients need at least `name` and `version` for EIP-712 domain reconstruction)\",\n\t);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds one {@link X402PaymentRequirements} entry suitable for the `accepts`\n * array of a `PAYMENT-REQUIRED` response.\n *\n * @example Single-chain JPYC (defaults extra automatically)\n * ```ts\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const requirements = buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * });\n * ```\n */\nexport function buildPaymentRequirements(\n\tparams: BuildPaymentRequirementsParams,\n): X402PaymentRequirements {\n\tconst asset = assertAddress(params.asset, \"asset\");\n\tconst payTo = assertAddress(params.payTo, \"payTo\");\n\tconst amount = coerceAmount(params.amount);\n\tconst maxTimeoutSeconds = params.maxTimeoutSeconds ?? X402_DEFAULT_MAX_TIMEOUT_SECONDS;\n\tif (maxTimeoutSeconds <= 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequirements\",\n\t\t\t`\\`maxTimeoutSeconds\\` must be positive, got ${maxTimeoutSeconds}`,\n\t\t);\n\t}\n\tconst extra = resolveExtra(asset, params.extra);\n\n\treturn {\n\t\tscheme: \"exact\",\n\t\tnetwork: chainIdToX402Network(params.chainId),\n\t\tamount,\n\t\tasset,\n\t\tpayTo,\n\t\tmaxTimeoutSeconds,\n\t\textra,\n\t};\n}\n\n/**\n * Builds the full {@link X402PaymentRequiredResponse} body the server returns\n * alongside HTTP 402.\n *\n * @example\n * ```ts\n * import {\n * buildPaymentRequiredResponse,\n * buildPaymentRequirements,\n * encodePaymentRequiredHeader,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const response = buildPaymentRequiredResponse({\n * resource: { url: \"https://api.example.com/weather\", description: \"Real-time weather\" },\n * accepts: [\n * buildPaymentRequirements({ chainId: polygonAmoy.id, ... }),\n * ],\n * error: \"PAYMENT-SIGNATURE header is required\",\n * });\n *\n * res.statusCode = 402;\n * res.setHeader(\"PAYMENT-REQUIRED\", encodePaymentRequiredHeader(response));\n * res.setHeader(\"content-type\", \"application/json\");\n * res.end(JSON.stringify(response));\n * ```\n */\nexport function buildPaymentRequiredResponse(\n\tparams: BuildPaymentRequiredResponseParams,\n): X402PaymentRequiredResponse {\n\tif (params.accepts.length === 0) {\n\t\tthrow new X402InvalidPayloadError(\n\t\t\t\"PaymentRequired\",\n\t\t\t\"`accepts` must contain at least one PaymentRequirements entry\",\n\t\t);\n\t}\n\t// Object literal is built conditionally so optional fields are *absent* (not\n\t// `undefined`) when not provided — required by `exactOptionalPropertyTypes`.\n\tconst base: Pick<X402PaymentRequiredResponse, \"x402Version\" | \"resource\" | \"accepts\"> = {\n\t\tx402Version: X402_VERSION,\n\t\tresource: params.resource,\n\t\taccepts: params.accepts,\n\t};\n\tif (params.error !== undefined && params.extensions !== undefined) {\n\t\treturn { ...base, error: params.error, extensions: params.extensions };\n\t}\n\tif (params.error !== undefined) {\n\t\treturn { ...base, error: params.error };\n\t}\n\tif (params.extensions !== undefined) {\n\t\treturn { ...base, extensions: params.extensions };\n\t}\n\treturn base;\n}\n","/**\n * Typed errors for the reasoning-step idempotency layer (M5-1).\n *\n * Mirrors the kawasekit error convention: plain `extends Error`, a stable\n * `this.name`, public `readonly` discriminant fields, and an optional\n * `{ cause }` options bag forwarded to `super`. Consumers discriminate via\n * `instanceof`, never a string `.code`.\n *\n * @packageDocumentation\n */\n\n/**\n * Thrown at construction / configuration time when an idempotency primitive is\n * wired up incorrectly (e.g. a non-positive LRU cap, an empty key). This is an\n * integrator bug, not an adversarial input — analogous to\n * {@link X402InvalidConfigError}.\n *\n * @example\n * ```ts\n * import { IdempotencyConfigError } from \"kawasekit/idempotency\";\n *\n * try {\n * createInMemoryIdempotencyStore({ maxEntries: 0 });\n * } catch (err) {\n * if (err instanceof IdempotencyConfigError) {\n * console.error(err.field, err.reason);\n * }\n * }\n * ```\n */\nexport class IdempotencyConfigError extends Error {\n\treadonly field: string;\n\treadonly reason: string;\n\n\tconstructor(field: string, reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Invalid idempotency config (${field}): ${reason}`, options);\n\t\tthis.name = \"IdempotencyConfigError\";\n\t\tthis.field = field;\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when {@link parseIdempotencyRecord} cannot decode a persisted record\n * (malformed JSON, missing/!mistyped field). Carries a machine-readable\n * `reason` and the underlying `cause` when available.\n *\n * @example\n * ```ts\n * import { IdempotencyRecordParseError, parseIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * try {\n * parseIdempotencyRecord(rawFromRedis);\n * } catch (err) {\n * if (err instanceof IdempotencyRecordParseError) {\n * // drop the corrupt entry; treat the request as fresh\n * }\n * }\n * ```\n */\nexport class IdempotencyRecordParseError extends Error {\n\treadonly reason: string;\n\n\tconstructor(reason: string, options?: { cause?: unknown }) {\n\t\tsuper(`Failed to parse idempotency record: ${reason}`, options);\n\t\tthis.name = \"IdempotencyRecordParseError\";\n\t\tthis.reason = reason;\n\t}\n}\n\n/**\n * Thrown when a persisted record's `kawasekitVersion` does not match the\n * version this build understands. Distinct from a parse error so a forward /\n * backward migration can be detected and handled explicitly (the version is a\n * string so future variants like `\"2\"` do not break parser ordering).\n *\n * @example\n * ```ts\n * import { IdempotencyRecordVersionError } from \"kawasekit/idempotency\";\n * // expected \"1\", received \"2\" → caller decides to ignore or migrate\n * ```\n */\nexport class IdempotencyRecordVersionError extends Error {\n\treadonly expected: string;\n\treadonly received: unknown;\n\n\tconstructor(expected: string, received: unknown) {\n\t\tsuper(\n\t\t\t`Unsupported idempotency record version: expected ${expected}, received ${JSON.stringify(received)}`,\n\t\t);\n\t\tthis.name = \"IdempotencyRecordVersionError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n","/**\n * The persisted idempotency record + its (de)serialization (M5-1).\n *\n * Follows the `session/envelope` convention: a bigint/`Address`-friendly PUBLIC\n * type and a SEPARATE private `…Json` wire shape with bigints as decimal\n * strings, validated on parse via small `assert*` helpers, output as plain\n * UTF-8 JSON. The string `kawasekitVersion` + dedicated `…VersionError` keep a\n * future schema bump a clean, typed migration.\n *\n * A record is dedup *metadata*, never funds — it stores enough to **replay** a\n * prior settlement (the on-chain `txHash` and an optional response snapshot),\n * not to move value.\n *\n * @packageDocumentation\n */\n\nimport { type Address, getAddress, type Hex } from \"viem\";\nimport { isX402Network, type X402Network } from \"../x402/types\";\nimport { IdempotencyRecordParseError, IdempotencyRecordVersionError } from \"./errors\";\n\n/** Current idempotency-record schema version. String, so `\"2\"`, `\"1-jwe\"`, … never break parser ordering. */\nexport const KAWASEKIT_IDEMPOTENCY_RECORD_VERSION = \"1\" as const;\n\n/** The schema version literal type. */\nexport type KawasekitIdempotencyRecordVersion = typeof KAWASEKIT_IDEMPOTENCY_RECORD_VERSION;\n\n/**\n * A byte-faithful, credential-safe snapshot of the paid response, so a\n * duplicate request can be replayed without re-running settlement or the inner\n * handler. Headers are an allowlist captured by the server (hop-by-hop /\n * `Set-Cookie` / auth headers are stripped); the body is base64.\n */\nexport interface IdempotencyResponseSnapshot {\n\treadonly status: number;\n\treadonly headers: ReadonlyArray<readonly [string, string]>;\n\treadonly bodyBase64: string;\n}\n\n/**\n * A completed reasoning-step settlement, keyed by the idempotency key. Retained\n * until `expiresAt` (anchored to the authorization `validBefore`, never beyond).\n */\nexport interface IdempotencyRecord {\n\treadonly kawasekitVersion: KawasekitIdempotencyRecordVersion;\n\t/** The idempotency key this record is stored under. */\n\treadonly key: string;\n\t/** The on-chain settlement tx hash (replayed in the `PAYMENT-RESPONSE` header). */\n\treadonly txHash: Hex;\n\t/** The payer EOA recovered at settlement. */\n\treadonly payer: Address;\n\t/** Settled amount, decimal string (uint256-safe). */\n\treadonly amount: string;\n\t/** x402 network the settlement landed on. */\n\treadonly network: X402Network;\n\t/** Optional captured response for byte-identical replay. */\n\treadonly responseSnapshot?: IdempotencyResponseSnapshot;\n\t/** Unix-seconds expiry. The record MUST NOT outlive the authorization `validBefore`. */\n\treadonly expiresAt: bigint;\n}\n\ninterface IdempotencyResponseSnapshotJson {\n\treadonly status: number;\n\treadonly headers: ReadonlyArray<readonly [string, string]>;\n\treadonly bodyBase64: string;\n}\n\ninterface IdempotencyRecordJson {\n\treadonly kawasekitVersion: string;\n\treadonly key: string;\n\treadonly txHash: string;\n\treadonly payer: string;\n\treadonly amount: string;\n\treadonly network: string;\n\treadonly responseSnapshot?: IdempotencyResponseSnapshotJson;\n\treadonly expiresAt: string;\n}\n\nconst UINT_DECIMAL = /^(0|[1-9][0-9]*)$/;\nconst HEX = /^0x[0-9a-fA-F]*$/;\n\nfunction assertString(value: unknown, field: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a string`);\n\t}\n\treturn value;\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): string {\n\tconst s = assertString(value, field);\n\tif (s === \"\") {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must not be empty`);\n\t}\n\treturn s;\n}\n\nfunction assertNumber(value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a finite number`);\n\t}\n\treturn value;\n}\n\nfunction assertHex(value: unknown, field: string): Hex {\n\tconst s = assertString(value, field);\n\tif (!HEX.test(s) || s.length % 2 !== 0) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be 0x-prefixed even-length hex`);\n\t}\n\t// Narrowed to viem's Hex by the regex above; the cast carries no extra trust.\n\treturn s as Hex;\n}\n\nfunction parseBigIntString(value: unknown, field: string): bigint {\n\tconst s = assertString(value, field);\n\tif (!UINT_DECIMAL.test(s)) {\n\t\tthrow new IdempotencyRecordParseError(\n\t\t\t`field \"${field}\" must be a non-negative decimal integer string`,\n\t\t);\n\t}\n\treturn BigInt(s);\n}\n\nfunction assertAddress(value: unknown, field: string): Address {\n\tconst s = assertString(value, field);\n\ttry {\n\t\treturn getAddress(s);\n\t} catch (cause) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a valid address`, { cause });\n\t}\n}\n\nfunction assertNetwork(value: unknown, field: string): X402Network {\n\tconst s = assertString(value, field);\n\tif (!isX402Network(s)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"${field}\" must be a valid x402 network`);\n\t}\n\treturn s;\n}\n\nfunction assertSnapshot(value: unknown): IdempotencyResponseSnapshot {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"responseSnapshot\" must be an object`);\n\t}\n\tconst raw = value as {\n\t\tstatus?: unknown;\n\t\theaders?: unknown;\n\t\tbodyBase64?: unknown;\n\t};\n\tconst status = assertNumber(raw.status, \"responseSnapshot.status\");\n\tif (!Array.isArray(raw.headers)) {\n\t\tthrow new IdempotencyRecordParseError(`field \"responseSnapshot.headers\" must be an array`);\n\t}\n\tconst headers = raw.headers.map((pair, i): readonly [string, string] => {\n\t\tif (!Array.isArray(pair) || pair.length !== 2) {\n\t\t\tthrow new IdempotencyRecordParseError(\n\t\t\t\t`field \"responseSnapshot.headers[${i}]\" must be a [name, value] pair`,\n\t\t\t);\n\t\t}\n\t\treturn [\n\t\t\tassertString(pair[0], `responseSnapshot.headers[${i}][0]`),\n\t\t\tassertString(pair[1], `responseSnapshot.headers[${i}][1]`),\n\t\t];\n\t});\n\tconst bodyBase64 = assertString(raw.bodyBase64, \"responseSnapshot.bodyBase64\");\n\treturn { status, headers, bodyBase64 };\n}\n\n/**\n * Serializes a record to a plain UTF-8 JSON string (base64 / transport is the\n * caller's concern). Bigints become decimal strings.\n *\n * @example\n * ```ts\n * import { serializeIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * const json = serializeIdempotencyRecord(record);\n * ```\n */\nexport function serializeIdempotencyRecord(record: IdempotencyRecord): string {\n\tconst json: IdempotencyRecordJson = {\n\t\tkawasekitVersion: record.kawasekitVersion,\n\t\tkey: record.key,\n\t\ttxHash: record.txHash,\n\t\tpayer: record.payer,\n\t\tamount: record.amount,\n\t\tnetwork: record.network,\n\t\t...(record.responseSnapshot !== undefined ? { responseSnapshot: record.responseSnapshot } : {}),\n\t\texpiresAt: record.expiresAt.toString(),\n\t};\n\treturn JSON.stringify(json);\n}\n\n/**\n * Parses a serialized record. Throws {@link IdempotencyRecordVersionError} on a\n * version mismatch and {@link IdempotencyRecordParseError} on any structural /\n * field error (so a corrupt entry can be dropped and the request treated as\n * fresh — fund-correctness still rests on the on-chain nonce, not this cache).\n *\n * @example\n * ```ts\n * import { parseIdempotencyRecord } from \"kawasekit/idempotency\";\n *\n * const record = parseIdempotencyRecord(jsonFromStore);\n * ```\n */\nexport function parseIdempotencyRecord(input: string): IdempotencyRecord {\n\tlet raw: unknown;\n\ttry {\n\t\traw = JSON.parse(input);\n\t} catch (cause) {\n\t\tthrow new IdempotencyRecordParseError(\"input is not valid JSON\", { cause });\n\t}\n\tif (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n\t\tthrow new IdempotencyRecordParseError(\"input must be a JSON object\");\n\t}\n\t// Narrow to a per-field `unknown` shape (not an index signature) so each field\n\t// is validated by an assert* helper and dot-access stays lint-clean.\n\tconst obj = raw as {\n\t\treadonly kawasekitVersion?: unknown;\n\t\treadonly key?: unknown;\n\t\treadonly txHash?: unknown;\n\t\treadonly payer?: unknown;\n\t\treadonly amount?: unknown;\n\t\treadonly network?: unknown;\n\t\treadonly responseSnapshot?: unknown;\n\t\treadonly expiresAt?: unknown;\n\t};\n\n\tconst version = assertString(obj.kawasekitVersion, \"kawasekitVersion\");\n\tif (version !== KAWASEKIT_IDEMPOTENCY_RECORD_VERSION) {\n\t\tthrow new IdempotencyRecordVersionError(KAWASEKIT_IDEMPOTENCY_RECORD_VERSION, version);\n\t}\n\n\tconst snapshotRaw = obj.responseSnapshot;\n\treturn {\n\t\tkawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n\t\tkey: assertNonEmptyString(obj.key, \"key\"),\n\t\ttxHash: assertHex(obj.txHash, \"txHash\"),\n\t\tpayer: assertAddress(obj.payer, \"payer\"),\n\t\tamount: parseBigIntString(obj.amount, \"amount\").toString(),\n\t\tnetwork: assertNetwork(obj.network, \"network\"),\n\t\t...(snapshotRaw !== undefined ? { responseSnapshot: assertSnapshot(snapshotRaw) } : {}),\n\t\texpiresAt: parseBigIntString(obj.expiresAt, \"expiresAt\"),\n\t};\n}\n","/**\n * The idempotency store abstraction + the default in-memory implementation\n * (M5-1).\n *\n * The store is an **injected** dependency (mirroring how `Facilitator` / `hooks`\n * are injected), never a module global — kawasekit holds no ambient state. The\n * default {@link createInMemoryIdempotencyStore} is single-process; durable /\n * cross-replica backends (Redis, SQL) are operator territory, shipped as\n * optional-peer-dep adapters that implement this same interface.\n *\n * **Correctness vs. telemetry.** Unlike observability hooks (fire-and-forget),\n * store calls are correctness-relevant and are awaited; their errors are NOT\n * swallowed. Fund-correctness, however, never *depends* on the store — the\n * on-chain EIP-3009 nonce is the backstop — so a cold/missing store degrades\n * response replay, not safety.\n *\n * @packageDocumentation\n */\n\nimport { IdempotencyConfigError } from \"./errors\";\nimport type { IdempotencyRecord } from \"./record\";\n\n/** A fence token proving ownership of an in-flight slot, carrying its expiry. */\nexport interface IdempotencyLease {\n\treadonly token: string;\n\t/** Unix-seconds; after this the lease is reclaimable as `fresh` (crash recovery). */\n\treadonly expiresAt: bigint;\n}\n\n/** The outcome of {@link IdempotencyStore.begin}. */\nexport type IdempotencyLookupResult =\n\t| { readonly status: \"fresh\"; readonly lease: IdempotencyLease }\n\t| { readonly status: \"in_flight\" }\n\t| { readonly status: \"completed\"; readonly record: IdempotencyRecord };\n\n/**\n * Reasoning-step idempotency store. Implementations MUST make {@link begin}\n * atomic: a single caller wins the `fresh` lease; concurrent callers see\n * `in_flight`; an *expired* in-flight lease is reclaimable as `fresh` so a\n * crashed holder cannot strand a key forever.\n */\nexport interface IdempotencyStore {\n\t/** Atomically lease a fresh slot, or report in-flight / completed. */\n\tbegin(key: string): Promise<IdempotencyLookupResult>;\n\t/** Extend an owned lease while a settlement runs long. Rejects if the lease was lost. */\n\trenew(key: string, lease: IdempotencyLease): Promise<IdempotencyLease>;\n\t/** Persist the completed record (no-op if the lease was reclaimed/superseded). */\n\tcomplete(key: string, record: IdempotencyRecord, lease: IdempotencyLease): Promise<void>;\n\t/** Release an owned in-flight slot so the step can be retried (idempotent). */\n\tabandon(key: string, lease: IdempotencyLease): Promise<void>;\n}\n\n/** Parameters for {@link createInMemoryIdempotencyStore}. */\nexport interface CreateInMemoryIdempotencyStoreParams {\n\t/** LRU cap on retained entries (memory-DoS bound, T-I9). Default 10_000. */\n\treadonly maxEntries?: number;\n\t/** In-flight lease TTL in seconds (crash-recovery window, H3). Default 90. */\n\treadonly leaseTtlSeconds?: number;\n\t/** Unix-seconds clock (override for tests). */\n\treadonly now?: () => bigint;\n\t/** Lease-token source (override for tests). */\n\treadonly generateLeaseToken?: () => string;\n\t/** Suppress the one-time single-process warning (default emits it). */\n\treadonly warnOnConstruct?: boolean;\n}\n\ntype Entry =\n\t| { readonly state: \"in_flight\"; readonly lease: IdempotencyLease }\n\t| { readonly state: \"completed\"; readonly record: IdempotencyRecord };\n\nfunction entryExpiry(entry: Entry): bigint {\n\treturn entry.state === \"in_flight\" ? entry.lease.expiresAt : entry.record.expiresAt;\n}\n\nfunction defaultNow(): bigint {\n\treturn BigInt(Math.floor(Date.now() / 1000));\n}\n\nfunction defaultLeaseToken(): string {\n\tconst bytes = new Uint8Array(16);\n\tcrypto.getRandomValues(bytes);\n\treturn Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nlet warnedSingleProcess = false;\n\nfunction warnSingleProcessOnce(): void {\n\tif (warnedSingleProcess) {\n\t\treturn;\n\t}\n\twarnedSingleProcess = true;\n\tif (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") {\n\t\tprocess.emitWarning(\n\t\t\t\"createInMemoryIdempotencyStore: in-memory dedup is single-process and does NOT \" +\n\t\t\t\t\"deduplicate across replicas. Multi-replica deployments require a shared store \" +\n\t\t\t\t\"(Redis/SQL adapter) or the client-side derived nonce for the guarantee.\",\n\t\t\t{ type: \"Warning\", code: \"KAWASEKIT_IDEMPOTENCY_001\" },\n\t\t);\n\t}\n}\n\n/**\n * In-memory, single-process idempotency store: a bounded LRU with a leased\n * in-flight state machine and lazy TTL eviction. The default the SDK ships;\n * safe for one process, NOT for multiple replicas (see the construct-time\n * warning).\n *\n * @example\n * ```ts\n * import { createInMemoryIdempotencyStore } from \"kawasekit/idempotency\";\n *\n * const store = createInMemoryIdempotencyStore({ maxEntries: 50_000 });\n * const result = await store.begin(key);\n * if (result.status === \"completed\") {\n * // replay result.record\n * }\n * ```\n */\nexport function createInMemoryIdempotencyStore(\n\tparams: CreateInMemoryIdempotencyStoreParams = {},\n): IdempotencyStore {\n\tconst maxEntries = params.maxEntries ?? 10_000;\n\tif (!Number.isInteger(maxEntries) || maxEntries < 1) {\n\t\tthrow new IdempotencyConfigError(\"maxEntries\", \"must be a positive integer\");\n\t}\n\tconst leaseTtlSeconds = params.leaseTtlSeconds ?? 90;\n\tif (!Number.isInteger(leaseTtlSeconds) || leaseTtlSeconds < 1) {\n\t\tthrow new IdempotencyConfigError(\"leaseTtlSeconds\", \"must be a positive integer\");\n\t}\n\tconst now = params.now ?? defaultNow;\n\tconst mintToken = params.generateLeaseToken ?? defaultLeaseToken;\n\n\tif (params.warnOnConstruct !== false) {\n\t\twarnSingleProcessOnce();\n\t}\n\n\t// Map preserves insertion order; we delete+set on access to move the entry\n\t// to the tail, so the head is always the least-recently-used.\n\tconst entries = new Map<string, Entry>();\n\n\t/** Read an entry, treating an expired one as absent (and evicting it). */\n\tfunction live(key: string): Entry | undefined {\n\t\tconst entry = entries.get(key);\n\t\tif (entry === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (entryExpiry(entry) <= now()) {\n\t\t\tentries.delete(key);\n\t\t\treturn undefined;\n\t\t}\n\t\t// LRU touch.\n\t\tentries.delete(key);\n\t\tentries.set(key, entry);\n\t\treturn entry;\n\t}\n\n\tfunction set(key: string, entry: Entry): void {\n\t\tentries.delete(key);\n\t\tentries.set(key, entry);\n\t\twhile (entries.size > maxEntries) {\n\t\t\tconst oldest = entries.keys().next().value;\n\t\t\tif (oldest === undefined) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tentries.delete(oldest);\n\t\t}\n\t}\n\n\treturn {\n\t\tasync begin(key: string): Promise<IdempotencyLookupResult> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry === undefined) {\n\t\t\t\tconst lease: IdempotencyLease = {\n\t\t\t\t\ttoken: mintToken(),\n\t\t\t\t\texpiresAt: now() + BigInt(leaseTtlSeconds),\n\t\t\t\t};\n\t\t\t\tset(key, { state: \"in_flight\", lease });\n\t\t\t\treturn { status: \"fresh\", lease };\n\t\t\t}\n\t\t\tif (entry.state === \"completed\") {\n\t\t\t\treturn { status: \"completed\", record: entry.record };\n\t\t\t}\n\t\t\treturn { status: \"in_flight\" };\n\t\t},\n\n\t\tasync renew(key: string, lease: IdempotencyLease): Promise<IdempotencyLease> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry === undefined || entry.state !== \"in_flight\" || entry.lease.token !== lease.token) {\n\t\t\t\tthrow new IdempotencyConfigError(\n\t\t\t\t\t\"lease\",\n\t\t\t\t\t\"renew called without an owned in-flight lease (lost or reclaimed)\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst renewed: IdempotencyLease = {\n\t\t\t\ttoken: lease.token,\n\t\t\t\texpiresAt: now() + BigInt(leaseTtlSeconds),\n\t\t\t};\n\t\t\tset(key, { state: \"in_flight\", lease: renewed });\n\t\t\treturn renewed;\n\t\t},\n\n\t\tasync complete(key: string, record: IdempotencyRecord, lease: IdempotencyLease): Promise<void> {\n\t\t\tconst entry = live(key);\n\t\t\t// Only the lease holder may write. If the lease was reclaimed (expired)\n\t\t\t// or another holder superseded it, do NOT clobber — fund-correctness is\n\t\t\t// guaranteed on-chain regardless; this only affects response replay.\n\t\t\tif (entry === undefined || entry.state !== \"in_flight\" || entry.lease.token !== lease.token) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tset(key, { state: \"completed\", record });\n\t\t},\n\n\t\tasync abandon(key: string, lease: IdempotencyLease): Promise<void> {\n\t\t\tconst entry = live(key);\n\t\t\tif (entry !== undefined && entry.state === \"in_flight\" && entry.lease.token === lease.token) {\n\t\t\t\tentries.delete(key);\n\t\t\t}\n\t\t},\n\t};\n}\n","/**\n * `createX402Handler()` — framework-agnostic x402 v2 resource-server adapter.\n *\n * The returned function maps any WHATWG `Request` to a `Response`, gating the\n * caller-supplied inner handler behind an x402 payment flow:\n *\n * 1. Compute requirements for the request (via `requirementsFor`).\n * `null` / empty array → no payment, pass through to inner handler.\n * 2. Look for the `PAYMENT-SIGNATURE` header. If missing or malformed →\n * `402 Payment Required` with a `PAYMENT-REQUIRED` header carrying the\n * encoded {@link X402PaymentRequiredResponse}.\n * 3. The client's `paymentPayload.accepted` must match one entry in our\n * requirements list (scheme / network / amount / asset / payTo).\n * 4. Call `facilitator.verify`. On failure → 402 with a reason.\n * 5. Call `facilitator.settle`. On failure → 402 with a reason. On success →\n * invoke the inner handler, attach the `PAYMENT-RESPONSE` header, return.\n *\n * Because the contract is `Request → Response`, the handler runs unchanged on\n * Node (via `@hono/node-server` or a hand-rolled adapter), Bun, Deno, Cloudflare\n * Workers, and Vercel Edge.\n *\n * @packageDocumentation\n */\n\nimport type { Hex } from \"viem\";\nimport { getAddress } from \"viem\";\nimport {\n\tcreateInMemoryIdempotencyStore,\n\ttype IdempotencyLease,\n\ttype IdempotencyLookupResult,\n\ttype IdempotencyRecord,\n\ttype IdempotencyResponseSnapshot,\n\ttype IdempotencyStore,\n\tKAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n} from \"../idempotency\";\nimport {\n\textractAcceptedNetworks,\n\tinvokeHookSafely,\n\ttype ObservabilityHooks,\n\ttype PaymentAcceptedEvent,\n\ttype PaymentRequiredEvent,\n} from \"../observability/hooks\";\nimport {\n\tdecodePaymentSignatureHeader,\n\tencodePaymentRequiredHeader,\n\tencodePaymentResponseHeader,\n\tX402_HEADER_IDEMPOTENCY_KEY,\n\tX402_HEADER_PAYMENT_REQUIRED,\n\tX402_HEADER_PAYMENT_RESPONSE,\n\tX402_HEADER_PAYMENT_SIGNATURE,\n} from \"./encoding\";\nimport { X402InvalidPayloadError } from \"./errors\";\nimport { buildPaymentRequiredResponse } from \"./payment-requirements\";\nimport type {\n\tFacilitator,\n\tX402PaymentPayload,\n\tX402PaymentRequirements,\n\tX402ResourceInfo,\n\tX402SettlementResponse,\n} from \"./types\";\nimport { X402_VERSION } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Context passed to the inner handler **after** a payment has been verified\n * and settled. `null` when the request bypassed the payment flow because\n * `requirementsFor` returned `null` / `[]`.\n */\nexport interface X402HandlerContext {\n\t/** The client's signed payment payload. */\n\treadonly paymentPayload: X402PaymentPayload;\n\t/** The matching requirements entry the client targeted. */\n\treadonly matchedRequirements: X402PaymentRequirements;\n\t/** Facilitator's settlement response (broadcast already happened). */\n\treadonly settlement: X402SettlementResponse;\n}\n\n/**\n * The inner business-logic handler. Receives the same `Request` plus a context\n * that is present when a payment was made for this request, and `null`\n * otherwise (pass-through case).\n */\nexport type X402InnerHandler = (\n\trequest: Request,\n\tcontext: X402HandlerContext | null,\n) => Promise<Response> | Response;\n\n/** Parameters for {@link createX402Handler}. */\nexport interface CreateX402HandlerParams {\n\t/** Facilitator that performs verify and settle (self or HTTP-proxied). */\n\treadonly facilitator: Facilitator;\n\t/**\n\t * Returns the {@link X402PaymentRequirements} that apply to this request.\n\t *\n\t * - Return one or more entries to require payment (client picks one).\n\t * - Return `null` or `[]` to skip the payment flow entirely for this\n\t * request — the inner handler is invoked with `context = null`.\n\t */\n\treadonly requirementsFor: (\n\t\trequest: Request,\n\t) =>\n\t\t| Promise<readonly X402PaymentRequirements[] | null>\n\t\t| readonly X402PaymentRequirements[]\n\t\t| null;\n\t/** The protected business-logic handler. Invoked after settlement. */\n\treadonly handler: X402InnerHandler;\n\t/**\n\t * Optional builder for the {@link X402ResourceInfo} echoed in the 402\n\t * response. Defaults to `{ url: request.url }`.\n\t */\n\treadonly resourceFor?: (request: Request) => Promise<X402ResourceInfo> | X402ResourceInfo;\n\t/**\n\t * Optional observability callbacks. The handler emits `onPaymentRequired`\n\t * each time it returns a 402, and `onPaymentAccepted` after a settled\n\t * payment unlocks the inner handler. Hooks are fire-and-forget — see\n\t * {@link ObservabilityHooks}.\n\t */\n\treadonly hooks?: ObservabilityHooks;\n\t/**\n\t * Reasoning-step idempotency (M5-1, Half A). **Default-on**: when omitted, an\n\t * in-memory store deduplicates re-sent / concurrent paid requests — replaying\n\t * the cached response and closing the verify→settle TOCTOU. Pass\n\t * `{ store: \"none\" }` to disable, or a shared store (Redis/SQL adapter) for\n\t * multi-replica deployments (the in-memory default is single-process).\n\t * Fund-correctness never depends on this store — the on-chain EIP-3009 nonce\n\t * is the backstop.\n\t */\n\treadonly idempotency?: IdempotencyServerConfig;\n}\n\n/** Server-side idempotency configuration (M5-1). See {@link CreateX402HandlerParams.idempotency}. */\nexport interface IdempotencyServerConfig {\n\t/** The store, or `\"none\"` to disable. Default: a fresh in-memory bounded LRU. */\n\treadonly store?: IdempotencyStore | \"none\";\n\t/**\n\t * What to do when a concurrent request holds the in-flight lease for the same\n\t * key. `\"reject\"` (default) returns a `payment_in_progress` 402 (the client\n\t * retries and gets the cached result); `\"await\"` polls briefly for the twin\n\t * to complete, then replays its response.\n\t */\n\treadonly inFlight?: \"await\" | \"reject\";\n\t/** Max captured response body size for replay, in bytes. Default 65536 (64 KiB). */\n\treadonly maxSnapshotBytes?: number;\n\t/** Fallback record TTL in seconds when the authorization `validBefore` is unreadable. Default 86400. */\n\treadonly fallbackTtlSeconds?: number;\n}\n\n/** The function returned by {@link createX402Handler}. */\nexport type X402RequestHandler = (request: Request) => Promise<Response>;\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction defaultResource(request: Request): X402ResourceInfo {\n\treturn { url: request.url };\n}\n\nfunction isSameRequirements(\n\toffered: X402PaymentRequirements,\n\tchosen: X402PaymentRequirements,\n): boolean {\n\treturn (\n\t\toffered.scheme === chosen.scheme &&\n\t\toffered.network === chosen.network &&\n\t\toffered.amount === chosen.amount &&\n\t\tgetAddress(offered.asset) === getAddress(chosen.asset) &&\n\t\tgetAddress(offered.payTo) === getAddress(chosen.payTo)\n\t);\n}\n\nasync function paymentRequired(\n\trequest: Request,\n\trequirements: readonly X402PaymentRequirements[],\n\tresourceFor: ((r: Request) => Promise<X402ResourceInfo> | X402ResourceInfo) | undefined,\n\terror: string,\n): Promise<Response> {\n\tconst resource = resourceFor ? await resourceFor(request) : defaultResource(request);\n\tconst body = buildPaymentRequiredResponse({ resource, accepts: requirements, error });\n\tconst headers = new Headers({ \"content-type\": \"application/json\" });\n\theaders.set(X402_HEADER_PAYMENT_REQUIRED, encodePaymentRequiredHeader(body));\n\treturn new Response(JSON.stringify(body), { status: 402, headers });\n}\n\nfunction internalError(reason: string, cause: unknown): Response {\n\tconst message = cause instanceof Error ? cause.message : String(cause);\n\treturn new Response(JSON.stringify({ error: reason, message }), {\n\t\tstatus: 500,\n\t\theaders: { \"content-type\": \"application/json\" },\n\t});\n}\n\nfunction withPaymentResponseHeader(\n\tinnerResponse: Response,\n\tsettlement: X402SettlementResponse,\n): Response {\n\tconst headers = new Headers(innerResponse.headers);\n\theaders.set(X402_HEADER_PAYMENT_RESPONSE, encodePaymentResponseHeader(settlement));\n\treturn new Response(innerResponse.body, {\n\t\tstatus: innerResponse.status,\n\t\tstatusText: innerResponse.statusText,\n\t\theaders,\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Idempotency (M5-1) helpers\n// ---------------------------------------------------------------------------\n\n/** Credential-safe header allowlist preserved in a replayed response. */\nconst SNAPSHOT_HEADER_ALLOWLIST = [\"content-type\", X402_HEADER_PAYMENT_RESPONSE];\nconst IDEMPOTENCY_REPLAYED_HEADER = \"Idempotency-Replayed\";\nconst DEFAULT_MAX_SNAPSHOT_BYTES = 64 * 1024;\nconst DEFAULT_FALLBACK_TTL_SECONDS = 86_400;\n\ninterface ResolvedIdempotency {\n\treadonly store: IdempotencyStore;\n\treadonly inFlight: \"await\" | \"reject\";\n\treadonly maxSnapshotBytes: number;\n\treadonly fallbackTtlSeconds: number;\n}\n\n/** Resolve the (default-on) idempotency config once per handler construction. */\nfunction resolveIdempotency(\n\tconfig: IdempotencyServerConfig | undefined,\n): ResolvedIdempotency | null {\n\tif (config?.store === \"none\") {\n\t\treturn null;\n\t}\n\treturn {\n\t\tstore: config?.store ?? createInMemoryIdempotencyStore(),\n\t\tinFlight: config?.inFlight ?? \"reject\",\n\t\tmaxSnapshotBytes: config?.maxSnapshotBytes ?? DEFAULT_MAX_SNAPSHOT_BYTES,\n\t\tfallbackTtlSeconds: config?.fallbackTtlSeconds ?? DEFAULT_FALLBACK_TTL_SECONDS,\n\t};\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n\tlet binary = \"\";\n\tfor (const b of bytes) {\n\t\tbinary += String.fromCharCode(b);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n\tconst binary = atob(b64);\n\tconst bytes = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i += 1) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\n/** Defensively read the EIP-3009 nonce + validBefore from an opaque payload. */\nfunction readAuthorization(\n\tpayload: X402PaymentPayload,\n): { readonly nonce: string; readonly validBefore: bigint } | null {\n\tconst inner = payload.payload;\n\tif (typeof inner !== \"object\" || inner === null) {\n\t\treturn null;\n\t}\n\tconst auth = (inner as { authorization?: unknown }).authorization;\n\tif (typeof auth !== \"object\" || auth === null) {\n\t\treturn null;\n\t}\n\tconst a = auth as { nonce?: unknown; validBefore?: unknown };\n\tif (typeof a.nonce !== \"string\" || a.nonce === \"\") {\n\t\treturn null;\n\t}\n\tconst validBefore =\n\t\ttypeof a.validBefore === \"string\" && /^[0-9]+$/.test(a.validBefore)\n\t\t\t? BigInt(a.validBefore)\n\t\t\t: 0n;\n\treturn { nonce: a.nonce, validBefore };\n}\n\n/**\n * The server dedup key: the client `Idempotency-Key` header when present (the\n * logical reasoning-step key, working even for signers that cannot derive a\n * nonce), else the EIP-3009 nonce — both namespaced by (network, payTo, asset)\n * for cross-tenant isolation. `null` ⇒ no key can be formed; dedup is skipped\n * (the on-chain nonce still backstops fund-correctness).\n */\nfunction computeServerKey(\n\trequest: Request,\n\trequirements: X402PaymentRequirements,\n\tauth: { readonly nonce: string } | null,\n): string | null {\n\tconst header = request.headers.get(X402_HEADER_IDEMPOTENCY_KEY);\n\tlet material: string;\n\tif (header !== null && header !== \"\") {\n\t\tmaterial = `hdr:${header}`;\n\t} else if (auth !== null) {\n\t\tmaterial = `nonce:${auth.nonce}`;\n\t} else {\n\t\treturn null;\n\t}\n\treturn JSON.stringify([\n\t\trequirements.network,\n\t\tgetAddress(requirements.payTo),\n\t\tgetAddress(requirements.asset),\n\t\tmaterial,\n\t]);\n}\n\n/**\n * Snapshot a response for replay, reading from a clone so the original body\n * stays intact. `undefined` if the body exceeds `maxBytes` (the record then\n * stores only the settlement for a minimal replay).\n */\nasync function snapshotResponse(\n\tresponse: Response,\n\tmaxBytes: number,\n): Promise<IdempotencyResponseSnapshot | undefined> {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength !== null && Number(contentLength) > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst buffer = await response.clone().arrayBuffer();\n\tif (buffer.byteLength > maxBytes) {\n\t\treturn undefined;\n\t}\n\tconst headers: Array<readonly [string, string]> = [];\n\tfor (const name of SNAPSHOT_HEADER_ALLOWLIST) {\n\t\tconst value = response.headers.get(name);\n\t\tif (value !== null) {\n\t\t\theaders.push([name, value]);\n\t\t}\n\t}\n\treturn { status: response.status, headers, bodyBase64: bytesToBase64(new Uint8Array(buffer)) };\n}\n\n/** Rebuild a response from a completed record (replay path), tagged for clients. */\nfunction replayResponse(record: IdempotencyRecord): Response {\n\tconst snapshot = record.responseSnapshot;\n\tif (snapshot !== undefined) {\n\t\tconst headers = new Headers();\n\t\tfor (const [name, value] of snapshot.headers) {\n\t\t\theaders.set(name, value);\n\t\t}\n\t\theaders.set(IDEMPOTENCY_REPLAYED_HEADER, \"true\");\n\t\treturn new Response(base64ToBytes(snapshot.bodyBase64), { status: snapshot.status, headers });\n\t}\n\tconst headers = new Headers({ [IDEMPOTENCY_REPLAYED_HEADER]: \"true\" });\n\theaders.set(\n\t\tX402_HEADER_PAYMENT_RESPONSE,\n\t\tencodePaymentResponseHeader({\n\t\t\tsuccess: true,\n\t\t\ttransaction: record.txHash,\n\t\t\tnetwork: record.network,\n\t\t\tpayer: record.payer,\n\t\t\tamount: record.amount,\n\t\t}),\n\t);\n\treturn new Response(null, { status: 200, headers });\n}\n\nfunction buildRecord(\n\tkey: string,\n\tsettlement: X402SettlementResponse,\n\trequirements: X402PaymentRequirements,\n\tvalidBefore: bigint,\n\tfallbackTtlSeconds: number,\n\tsnapshot: IdempotencyResponseSnapshot | undefined,\n): IdempotencyRecord | null {\n\tif (settlement.transaction === \"\" || settlement.payer === undefined) {\n\t\treturn null;\n\t}\n\tconst nowSec = BigInt(Math.floor(Date.now() / 1000));\n\tconst expiresAt = validBefore > nowSec ? validBefore : nowSec + BigInt(fallbackTtlSeconds);\n\treturn {\n\t\tkawasekitVersion: KAWASEKIT_IDEMPOTENCY_RECORD_VERSION,\n\t\tkey,\n\t\t// settlement.transaction is the on-chain tx hash (0x-hex) the facilitator broadcast.\n\t\ttxHash: settlement.transaction as Hex,\n\t\tpayer: settlement.payer,\n\t\tamount: settlement.amount ?? requirements.amount,\n\t\tnetwork: requirements.network,\n\t\t...(snapshot !== undefined ? { responseSnapshot: snapshot } : {}),\n\t\texpiresAt,\n\t};\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tsetTimeout(resolve, ms);\n\t});\n}\n\nconst IN_FLIGHT_POLL_MS = 100;\nconst IN_FLIGHT_MAX_POLLS = 50; // ~5s bounded wait for the \"await\" policy\n\n/** Release an owned in-flight lease so the step can be retried (best-effort). */\nasync function releaseLease(\n\tidem: ResolvedIdempotency | null,\n\tkey: string | null,\n\tlease: IdempotencyLease | null,\n): Promise<void> {\n\tif (idem !== null && key !== null && lease !== null) {\n\t\ttry {\n\t\t\tawait idem.store.abandon(key, lease);\n\t\t} catch {\n\t\t\t// best-effort: the lease will also expire on its own (crash-recovery TTL).\n\t\t}\n\t}\n}\n\n/**\n * For the `\"await\"` in-flight policy, poll briefly for a concurrent twin to\n * complete. Returns its record to replay, or `null` to fall back to the reject\n * path (twin still running past the budget, or it died and freed the slot).\n */\nasync function resolveInFlight(\n\tidem: ResolvedIdempotency,\n\tkey: string,\n): Promise<IdempotencyRecord | null> {\n\tif (idem.inFlight !== \"await\") {\n\t\treturn null;\n\t}\n\tfor (let i = 0; i < IN_FLIGHT_MAX_POLLS; i += 1) {\n\t\tawait sleep(IN_FLIGHT_POLL_MS);\n\t\tlet lookup: IdempotencyLookupResult;\n\t\ttry {\n\t\t\tlookup = await idem.store.begin(key);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (lookup.status === \"completed\") {\n\t\t\treturn lookup.record;\n\t\t}\n\t\tif (lookup.status === \"fresh\") {\n\t\t\t// The twin died and we now hold the lease; release it and let the\n\t\t\t// caller reject (the client retries and settles cleanly).\n\t\t\tawait releaseLease(idem, key, lookup.lease);\n\t\t\treturn null;\n\t\t}\n\t\t// still in_flight → keep polling\n\t}\n\treturn null;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Builds an {@link X402RequestHandler} that wraps `params.handler` with the\n * x402 payment flow.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { parseUnits } from \"viem\";\n * import {\n * buildPaymentRequirements,\n * createSelfFacilitator,\n * createX402Handler,\n * JPYC_DECIMALS,\n * JPYC_V2_ADDRESS,\n * polygonAmoy,\n * } from \"kawasekit\";\n *\n * const handler = createX402Handler({\n * facilitator: createSelfFacilitator({ walletClient, publicClient }),\n * requirementsFor: (req) =>\n * new URL(req.url).pathname.startsWith(\"/weather\")\n * ? [buildPaymentRequirements({\n * chainId: polygonAmoy.id,\n * asset: JPYC_V2_ADDRESS,\n * payTo: \"0x...\",\n * amount: parseUnits(\"0.001\", JPYC_DECIMALS),\n * })]\n * : null,\n * handler: async (req) => new Response(JSON.stringify({ weather: \"sunny\" }), {\n * headers: { \"content-type\": \"application/json\" },\n * }),\n * });\n *\n * // Mount on any framework that exposes WHATWG Request → Response.\n * ```\n */\nexport function createX402Handler(params: CreateX402HandlerParams): X402RequestHandler {\n\tconst { facilitator, requirementsFor, handler, resourceFor, hooks } = params;\n\t// Resolved ONCE so the in-memory store persists across requests (the Hono\n\t// adapter rebuilds the handler per request, so this must live in the closure).\n\tconst idempotency = resolveIdempotency(params.idempotency);\n\n\treturn async function x402Handler(request: Request): Promise<Response> {\n\t\tconst startedAtMs = Date.now();\n\n\t\tconst emitPaymentRequired = (\n\t\t\treqs: readonly X402PaymentRequirements[],\n\t\t\terror: string,\n\t\t): Promise<Response> => {\n\t\t\tconst event: PaymentRequiredEvent = {\n\t\t\t\tkind: \"payment_required\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tacceptedNetworks: extractAcceptedNetworks(reqs),\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentRequired, event);\n\t\t\treturn paymentRequired(request, reqs, resourceFor, error);\n\t\t};\n\n\t\t// 1. Resolve requirements (or pass through)\n\t\tlet requirements: readonly X402PaymentRequirements[] | null;\n\t\ttry {\n\t\t\trequirements = await requirementsFor(request);\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"requirements_resolution_failed\", cause);\n\t\t}\n\t\tif (requirements === null || requirements.length === 0) {\n\t\t\treturn handler(request, null);\n\t\t}\n\n\t\t// 2. Read the PAYMENT-SIGNATURE header\n\t\tconst headerValue = request.headers.get(X402_HEADER_PAYMENT_SIGNATURE);\n\t\tif (headerValue === null || headerValue === \"\") {\n\t\t\treturn emitPaymentRequired(requirements, \"PAYMENT-SIGNATURE header is required\");\n\t\t}\n\n\t\t// 3. Decode the payment payload\n\t\tlet paymentPayload: X402PaymentPayload;\n\t\ttry {\n\t\t\tpaymentPayload = decodePaymentSignatureHeader(headerValue);\n\t\t} catch (cause) {\n\t\t\tconst reason =\n\t\t\t\tcause instanceof X402InvalidPayloadError\n\t\t\t\t\t? cause.reason\n\t\t\t\t\t: \"invalid PAYMENT-SIGNATURE header\";\n\t\t\treturn emitPaymentRequired(requirements, reason);\n\t\t}\n\n\t\t// 4. Match chosen requirements to an offered entry\n\t\tconst matchedRequirements = requirements.find((offered) =>\n\t\t\tisSameRequirements(offered, paymentPayload.accepted),\n\t\t);\n\t\tif (!matchedRequirements) {\n\t\t\treturn emitPaymentRequired(\n\t\t\t\trequirements,\n\t\t\t\t\"paymentPayload.accepted does not match any offered requirements\",\n\t\t\t);\n\t\t}\n\n\t\t// 5. Verify\n\t\tlet verifyResult: Awaited<ReturnType<Facilitator[\"verify\"]>>;\n\t\ttry {\n\t\t\tverifyResult = await facilitator.verify({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\treturn internalError(\"facilitator_verify_failed\", cause);\n\t\t}\n\t\tif (!verifyResult.isValid) {\n\t\t\treturn emitPaymentRequired(requirements, verifyResult.invalidReason ?? \"verify failed\");\n\t\t}\n\n\t\t// 5b. Reasoning-step idempotency gate (M5-1, Half A). Runs AFTER verify so a\n\t\t// cached response is only released against a re-verified authorization.\n\t\tconst auth = readAuthorization(paymentPayload);\n\t\tconst idemKey =\n\t\t\tidempotency !== null ? computeServerKey(request, matchedRequirements, auth) : null;\n\t\tlet lease: IdempotencyLease | null = null;\n\t\tif (idempotency !== null && idemKey !== null) {\n\t\t\tlet lookup: IdempotencyLookupResult;\n\t\t\ttry {\n\t\t\t\tlookup = await idempotency.store.begin(idemKey);\n\t\t\t} catch (cause) {\n\t\t\t\treturn internalError(\"idempotency_store_failed\", cause);\n\t\t\t}\n\t\t\tif (lookup.status === \"completed\") {\n\t\t\t\treturn replayResponse(lookup.record);\n\t\t\t}\n\t\t\tif (lookup.status === \"in_flight\") {\n\t\t\t\tconst awaited = await resolveInFlight(idempotency, idemKey);\n\t\t\t\tif (awaited !== null) {\n\t\t\t\t\treturn replayResponse(awaited);\n\t\t\t\t}\n\t\t\t\treturn emitPaymentRequired(requirements, \"payment_in_progress\");\n\t\t\t}\n\t\t\tlease = lookup.lease;\n\t\t}\n\n\t\t// 6. Settle\n\t\tlet settleResult: Awaited<ReturnType<Facilitator[\"settle\"]>>;\n\t\ttry {\n\t\t\tsettleResult = await facilitator.settle({\n\t\t\t\tx402Version: X402_VERSION,\n\t\t\t\tpaymentPayload,\n\t\t\t\tpaymentRequirements: matchedRequirements,\n\t\t\t});\n\t\t} catch (cause) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn internalError(\"facilitator_settle_failed\", cause);\n\t\t}\n\t\tif (!settleResult.success) {\n\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\treturn emitPaymentRequired(requirements, settleResult.errorReason ?? \"settle failed\");\n\t\t}\n\n\t\t// 7. Settled — emit onPaymentAccepted then invoke inner handler.\n\t\tif (settleResult.payer !== undefined) {\n\t\t\tconst acceptedEvent: PaymentAcceptedEvent = {\n\t\t\t\tkind: \"payment_accepted\",\n\t\t\t\tstartedAtMs,\n\t\t\t\tdurationMs: Date.now() - startedAtMs,\n\t\t\t\trequestUrl: request.url,\n\t\t\t\tpayer: settleResult.payer,\n\t\t\t\tamount: settleResult.amount ?? matchedRequirements.amount,\n\t\t\t\tnetwork: matchedRequirements.network,\n\t\t\t\ttransaction: settleResult.transaction as Hex,\n\t\t\t};\n\t\t\tinvokeHookSafely(hooks?.onPaymentAccepted, acceptedEvent);\n\t\t}\n\n\t\t// Inner handler errors propagate — settlement has already happened.\n\t\tconst context: X402HandlerContext = {\n\t\t\tpaymentPayload,\n\t\t\tmatchedRequirements,\n\t\t\tsettlement: settleResult,\n\t\t};\n\t\tconst innerResponse = await handler(request, context);\n\t\tconst finalResponse = withPaymentResponseHeader(innerResponse, settleResult);\n\n\t\t// 7b. Record the settled response for replay-on-duplicate (best-effort —\n\t\t// fund-correctness is guaranteed on-chain regardless of the store).\n\t\tif (idempotency !== null && idemKey !== null && lease !== null) {\n\t\t\tconst snapshot = await snapshotResponse(finalResponse, idempotency.maxSnapshotBytes);\n\t\t\tconst record = buildRecord(\n\t\t\t\tidemKey,\n\t\t\t\tsettleResult,\n\t\t\t\tmatchedRequirements,\n\t\t\t\tauth?.validBefore ?? 0n,\n\t\t\t\tidempotency.fallbackTtlSeconds,\n\t\t\t\tsnapshot,\n\t\t\t);\n\t\t\tif (record !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tawait idempotency.store.complete(idemKey, record, lease);\n\t\t\t\t} catch {\n\t\t\t\t\t// Completing the cache is best-effort; on-chain nonce is the backstop.\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait releaseLease(idempotency, idemKey, lease);\n\t\t\t}\n\t\t}\n\t\treturn finalResponse;\n\t};\n}\n"]}