@anywalletkit/protocol-swap2-0x 0.1.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -6
- package/dist/activity.cjs +4 -3
- package/dist/activity.cjs.map +1 -1
- package/dist/activity.d.cts +6 -1
- package/dist/activity.d.ts +6 -1
- package/dist/activity.js +3 -3
- package/dist/chains.cjs +16 -2
- package/dist/chains.cjs.map +1 -1
- package/dist/chains.d.cts +26 -6
- package/dist/chains.d.ts +26 -6
- package/dist/chains.js +5 -1
- package/dist/{chunk-ALMGGQS4.js → chunk-ABT2WYBK.js} +6 -6
- package/dist/{chunk-ALMGGQS4.js.map → chunk-ABT2WYBK.js.map} +1 -1
- package/dist/{chunk-CWZCAJBY.js → chunk-AMZ5DXN2.js} +17 -3
- package/dist/chunk-AMZ5DXN2.js.map +1 -0
- package/dist/{chunk-AX4RNHWE.js → chunk-KYVRMBZG.js} +2 -2
- package/dist/{chunk-RLNXMQJH.js → chunk-S2RUUV3X.js} +16 -6
- package/dist/chunk-S2RUUV3X.js.map +1 -0
- package/dist/{chunk-QFOKBJXP.js → chunk-V4HUFBY2.js} +5 -5
- package/dist/chunk-V4HUFBY2.js.map +1 -0
- package/dist/{chunk-NK3PQGI4.js → chunk-YHRPT6BS.js} +20 -5
- package/dist/chunk-YHRPT6BS.js.map +1 -0
- package/dist/index.cjs +46 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +16 -6
- package/dist/protocol.cjs +40 -9
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +1 -1
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +5 -5
- package/dist/provider.cjs +41 -9
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +13 -6
- package/dist/provider.d.ts +13 -6
- package/dist/provider.js +6 -4
- package/dist/remote.cjs +34 -9
- package/dist/remote.cjs.map +1 -1
- package/dist/remote.d.cts +1 -1
- package/dist/remote.d.ts +1 -1
- package/dist/remote.js +5 -5
- package/dist/{settler-KDFcfsKv.d.cts → settler-CeJFLW5t.d.cts} +21 -4
- package/dist/{settler-BpRGkBVV.d.ts → settler-DBLrnepW.d.ts} +21 -4
- package/dist/settler.cjs +20 -4
- package/dist/settler.cjs.map +1 -1
- package/dist/settler.d.cts +1 -1
- package/dist/settler.d.ts +1 -1
- package/dist/settler.js +6 -2
- package/module.json +1 -0
- package/package.json +6 -6
- package/dist/chunk-CWZCAJBY.js.map +0 -1
- package/dist/chunk-NK3PQGI4.js.map +0 -1
- package/dist/chunk-QFOKBJXP.js.map +0 -1
- package/dist/chunk-RLNXMQJH.js.map +0 -1
- /package/dist/{chunk-AX4RNHWE.js.map → chunk-KYVRMBZG.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/chains.ts","../src/settler.ts","../src/rpc.ts","../src/provider.ts","../src/activity.ts","../src/remote.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./chains.js\";\nexport * from \"./settler.js\";\nexport * from \"./provider.js\";\nexport * from \"./remote.js\";\nexport {ZeroExSwap2Protocol} from \"./protocol.js\";\nexport {ZeroExSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type {ZeroExSwap2Config} from \"./protocol.js\";\n","/**\n * Where 0x settles, per chain. Everything a swap is held to on the device starts from this table:\n * the Settler registry (read on-chain for the Settler in force), canonical Permit2, and the wrapped\n * native token (wrap/unwrap pairs are not 0x swaps and are left to the wrap provider).\n *\n * The table is config: `zeroExChains(config.chains)` merges an integrator's entries over these.\n */\nimport {PERMIT2_ADDRESS} from \"@anywalletkit/protocol-swap2-core/util\";\n\n/** Canonical Permit2 — the only allowance target and the only EIP-712 verifying contract this module accepts. */\nexport const ZEROEX_PERMIT2 = PERMIT2_ADDRESS;\n/**\n * The 0x Settler deployer/registry (ERC-721: `ownerOf(feature)` is the Settler in force for that feature,\n * `prev(feature)` the instance it replaced). Same address on every chain 0x deploys to.\n */\nexport const ZEROEX_SETTLER_REGISTRY = \"0x00000000000004533Fe15556B1E086BB1A72cEae\";\n/** Registry feature 2: taker-submitted Settlers — the ones a Permit2 quote is sent to by the taker itself. */\nexport const ZEROEX_TAKER_FEATURE = 2;\n/** How the 0x API (and Settler's slippage check) names the chain's native coin. */\nexport const ZEROEX_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\n/** 0x's AllowanceHolder (the flow the docs recommend today). Not used by this module; pinned so it can be told apart. */\nexport const ZEROEX_ALLOWANCE_HOLDER = \"0x0000000000001fF3684f28c67538d4D072C22734\";\n\nexport interface ZeroExChain {\n /** Display name. */\n name: string;\n /** The Settler registry on this chain. */\n registry: string;\n /**\n * The taker Settler deployment (the registry's taker-feature nonce, see `zeroExSettlerAddress`) the registry named as\n * the one in force when the table was pinned. A native-coin sale is sent only to this deployment or to\n * {@link previousLiveNonce}: its value goes straight to the Settler's address, so that address must be a Settler that\n * was live then. A token sale (Permit2) may also go to the next {@link ZEROEX_SETTLER_NONCE_MARGIN} deployments once\n * they hold code. Anything newer is refused, clearly, until the pin is raised — the watch job reports every new\n * deployment (`ownerOf(2)` per chain in watch.json, `verify:live` on the canary). 1…{@link ZEROEX_SETTLER_MAX_NONCE}.\n */\n newestLiveNonce: number;\n /**\n * The deployment the registry named as the previous one (`prev(2)`) when the table was pinned: the oldest accepted.\n * An older Settler — a replaced one, whose code predates what the checks rely on — is refused as the one in force\n * and dropped as the previous one. 1…{@link newestLiveNonce} (equal to it on a chain with a single deployment).\n */\n previousLiveNonce: number;\n /** Wrapped native token; native ↔ wrapped pairs are refused up front (0x answers them with a call to this token, not a Settler). */\n wrappedNative?: string;\n}\n\n/**\n * Deployments of the taker feature a token sale (Permit2) may use past {@link ZeroExChain.newestLiveNonce}: room for\n * 0x's next Settlers (about one a month per chain) before the pin must be raised. Within it the device relies on the\n * code check (a deployment that does not exist yet has no code) and on its RPC answering that check truthfully; a token\n * sale's permit can be spent only with the account itself as the caller, so a wrong answer costs nothing. Native-coin\n * sales get no margin: their value would be sent to the address as it is.\n */\nexport const ZEROEX_SETTLER_NONCE_MARGIN = 2;\n/** The highest {@link ZeroExChain.newestLiveNonce} a chain table may pin. */\nexport const ZEROEX_SETTLER_MAX_NONCE = 1024;\n\nconst chain = (name: string, wrappedNative: string, newestLiveNonce: number, previousLiveNonce: number): ZeroExChain =>\n Object.freeze({name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative});\n\n/**\n * The default chain table (EVM chain id → entry). The last two arguments are the taker Settler deployments the\n * registry named as current and previous when pinned (2026-11-25, after 0x's 2026-11-24 Settler release;\n * `pnpm verify:live`: both have code).\n */\nexport const ZEROEX_CHAINS: Readonly<Record<number, ZeroExChain>> = Object.freeze({\n 1: chain(\"Ethereum\", \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\", 22, 21),\n 10: chain(\"Optimism\", \"0x4200000000000000000000000000000000000006\", 22, 21),\n 56: chain(\"BNB Smart Chain\", \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\", 24, 23),\n 137: chain(\"Polygon\", \"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270\", 21, 20),\n 8453: chain(\"Base\", \"0x4200000000000000000000000000000000000006\", 23, 22),\n 42161: chain(\"Arbitrum\", \"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1\", 21, 20),\n 43114: chain(\"Avalanche\", \"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7\", 21, 20),\n});\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS = /^0x0{40}$/;\n\n/**\n * The chain table in force: the defaults with `overrides` merged over them (an entry replaces the default for that\n * chain id, `null` removes the chain). An entry whose registry or wrapped native is not an address, or whose pins are\n * missing or out of order (`newestLiveNonce` 1…{@link ZEROEX_SETTLER_MAX_NONCE}, `previousLiveNonce` 1…newestLiveNonce),\n * throws — a typo here would move the root of every check.\n */\nexport function zeroExChains(overrides?: Readonly<Record<number, ZeroExChain | null>>): Readonly<Record<number, ZeroExChain>> {\n if (!overrides) return ZEROEX_CHAINS;\n const out: Record<number, ZeroExChain> = {...ZEROEX_CHAINS};\n for (const key of Object.keys(overrides)) {\n const id = Number(key);\n if (!Number.isSafeInteger(id) || id <= 0) throw new Error(`zeroex: chain id ${key.slice(0, 20)} is not a positive integer`);\n const entry = overrides[id];\n if (entry === null || entry === undefined) {\n delete out[id];\n continue;\n }\n if (typeof entry.name !== \"string\" || !entry.name) throw new Error(`zeroex: chain ${id} has no name`);\n if (typeof entry.registry !== \"string\" || !ADDRESS.test(entry.registry) || ZERO_ADDRESS.test(entry.registry)) throw new Error(`zeroex: chain ${id} names no Settler registry address`);\n if (entry.wrappedNative !== undefined && (typeof entry.wrappedNative !== \"string\" || !ADDRESS.test(entry.wrappedNative))) throw new Error(`zeroex: chain ${id} wrapped native is not an address`);\n const newest = entry.newestLiveNonce;\n const previous = entry.previousLiveNonce;\n if (!Number.isSafeInteger(newest) || newest < 1 || newest > ZEROEX_SETTLER_MAX_NONCE) {\n throw new Error(`zeroex: chain ${id} pins no newest live Settler deployment (newestLiveNonce, 1 to ${ZEROEX_SETTLER_MAX_NONCE})`);\n }\n if (!Number.isSafeInteger(previous) || previous < 1 || previous > newest) {\n throw new Error(`zeroex: chain ${id} pins no previous live Settler deployment (previousLiveNonce, 1 to its newestLiveNonce)`);\n }\n out[id] = Object.freeze({name: entry.name, registry: entry.registry, newestLiveNonce: newest, previousLiveNonce: previous, ...(entry.wrappedNative ? {wrappedNative: entry.wrappedNative} : {})});\n }\n return Object.freeze(out);\n}\n\n/** The EVM chain id of a CAIP-2 `eip155:<id>` string, or `NaN`. */\nexport function zeroExChainId(caip2: string): number {\n return typeof caip2 === \"string\" && /^eip155:[1-9][0-9]{0,15}$/.test(caip2) ? Number(caip2.slice(7)) : NaN;\n}\n\n/** Own-property lookup (a chain id like `constructor` must not resolve to anything). */\nexport function zeroExChain(chains: Readonly<Record<number, ZeroExChain>>, chainId: number): ZeroExChain | undefined {\n return Number.isSafeInteger(chainId) && Object.prototype.hasOwnProperty.call(chains, chainId) ? chains[chainId] : undefined;\n}\n","/**\n * The device-side checks of a 0x Permit2 swap. Nothing here trusts the API.\n *\n * - {@link createSettlerResolver}: the Settler in force is read from the pinned on-chain registry\n * (`ownerOf(2)`, and `prev(2)` for 0x's dwell time after a new deployment) — never taken from a\n * quote — and held to a CREATE3 deployment of that registry between the chain's pinned previous\n * deployment and its newest plus the margin, with code. A paused or removed feature reverts there\n * and the swap is refused.\n * - {@link decodeSettlerExecute}: a word-level reader of `Settler.execute(slippage, actions, zid)`.\n * - {@link checkZeroExTransaction}: the transaction a quote carries, held to the request — target\n * (and, for a native-coin sale, a Settler live when the chain table was pinned), value, chain,\n * method, the recipient / buy token / minimum of Settler's own slippage check, and, for a token\n * sale, the Permit2 payload (rebuilt locally by the core reader) and the first action that\n * spends it.\n *\n * Why the slippage tuple is the anchor: `execute` ends in Settler's `_checkSlippageAndTransfer`,\n * which sends the Settler's whole balance of `buyToken` to `recipient` and reverts below\n * `minAmountOut`. With the target a registry Settler, that tuple and the signed amount fixed, the\n * worst a hostile route can do is revert: the account pays at most the signed input and receives at\n * least the minimum. What the actions between do (which pools, in what order) is not checked.\n *\n * Why the first action is always checked: Settler runs a Permit2-spending action (`TRANSFER_FROM`,\n * every `*_VIP`) only at index 0, and Permit2 pulls from the caller. A token sale's action 0 must\n * therefore spend exactly the permit about to be signed, and a native-coin sale's action 0 must be\n * `NATIVE_CHECK` — otherwise an earlier, unspent permit of this account (one whose swap reverted)\n * could be spent inside a swap that looks like a plain native sale.\n *\n * Every refusal carries a `Swap2RefusalReason` (CS-13); a request this side cannot hold a\n * transaction to (no chain, recipient, tokens or amounts) is the caller's error and stays unclassified.\n */\nimport {getAddress, getContractAddress, numberToHex, pad} from \"viem\";\nimport {refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {readPermit2Transfer, type Permit2Transfer} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ZEROEX_CHAINS, ZEROEX_NATIVE, ZEROEX_PERMIT2, ZEROEX_SETTLER_MAX_NONCE, ZEROEX_SETTLER_NONCE_MARGIN, ZEROEX_SETTLER_REGISTRY, ZEROEX_TAKER_FEATURE, zeroExChain, type ZeroExChain} from \"./chains.js\";\nimport {isRevert, rpcRequest, rpcUrlsFor, type RpcUrls} from \"./rpc.js\";\n\n/** `execute((address recipient, address buyToken, uint256 minAmountOut), bytes[] actions, bytes32 zidAndAffiliate)`. */\nexport const SETTLER_EXECUTE_SELECTOR = \"0x1fff991f\";\n/** `ownerOf(uint256)` on the registry: the Settler in force for a feature. */\nexport const REGISTRY_OWNER_OF_SELECTOR = \"0x6352211e\";\n/** `prev(uint128)` on the registry: the instance the current one replaced. */\nexport const REGISTRY_PREV_SELECTOR = \"0xe2603dc2\";\n/** `NATIVE_CHECK(uint256 deadline, uint256 msgValue)`: the action every native-coin sale opens with (no Permit2 involved). */\nexport const SETTLER_NATIVE_CHECK_SELECTOR = \"0xbd01c226\";\n/**\n * The longest a 0x permit may stay valid from now. 0x signs five minutes ahead; the core reader allows an hour for any\n * provider. A shorter window leaves less time for a permit that was published but not spent (its swap reverted).\n */\nexport const ZEROEX_MAX_PERMIT_SECONDS = 600;\n/**\n * The longest a native-coin sale's quote may stay valid from now. A token sale's quote is bounded by its permit's\n * deadline; a native sale signs nothing, so its quote is bounded here instead: the transaction goes out within this\n * window of the registry read it was checked against, or not at all.\n */\nexport const ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;\n\n/** How far inside {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS} a backend ends a native sale's quote, so an app whose clock runs behind the backend's still accepts it. */\nexport const ZEROEX_NATIVE_QUOTE_SKEW_SECONDS = 30;\n\nconst PERMIT = \"((address,uint256),uint256,uint256)\";\n/**\n * Settler actions through which a taker-submitted swap spends a Permit2 signature (`ISettlerActions.sol`), by\n * selector. Every one starts `(address recipient, PermitTransferFrom permit, …)`, so the permit sits in argument\n * words 1–4 (token, amount, nonce, deadline); `sigWord` is the head word holding the offset of `bytes sig`.\n * `RFQ_VIP` (a maker-signed order) is left out on purpose: a quote that opens with it is refused.\n */\nexport const SETTLER_PERMIT_ACTIONS: Readonly<Record<string, {name: string; signature: string; sigWord: number}>> = Object.freeze({\n \"0xc1fb425e\": Object.freeze({name: \"TRANSFER_FROM\", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5}),\n \"0x3036d6a6\": Object.freeze({name: \"UNISWAPV3_VIP\", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6}),\n \"0x6a92dacb\": Object.freeze({name: \"UNISWAPV4_VIP\", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x441d2492\": Object.freeze({name: \"PANCAKE_INFINITY_VIP\", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x4150c86c\": Object.freeze({name: \"BALANCERV3_VIP\", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x10cd6343\": Object.freeze({name: \"EKUBOV3_VIP\", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x0bcce50f\": Object.freeze({name: \"CURVE_TRICRYPTO_VIP\", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6}),\n});\n\n/** A refusal from one of the checks in this file. The message is safe to show and starts `zeroex: `; `reason` classifies it (CS-13). */\nexport class ZeroExTransactionError extends Error {\n declare readonly reason?: Swap2RefusalReason;\n constructor(why: string, reason?: Swap2RefusalReason) {\n super(`zeroex: ${why}`);\n this.name = \"ZeroExTransactionError\";\n if (reason) withReason(this, reason);\n }\n}\nconst refuse = (why: string, reason?: Swap2RefusalReason) => new ZeroExTransactionError(why, reason);\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS = /^0x0{40}$/;\nconst same = (a: string, b: string) => a.length === b.length && a.toLowerCase() === b.toLowerCase();\n/** The native coin, as the engine (zero address) or 0x (the `0xEeee…` sentinel) names it. */\nexport const isZeroExNative = (token: string): boolean => ZERO_ADDRESS.test(token) || same(token, ZEROEX_NATIVE);\n\n// ── which addresses are 0x Settlers at all ──────────────────────────────────\n\n/**\n * keccak256 of the CREATE3 shim (PUSH0 variant) through which the registry deploys every Settler: the registry\n * CREATE2s the shim with salt `feature << 128 | chainId << 64 | nonce`, and the shim CREATEs the Settler (nonce 1).\n */\nexport const ZEROEX_SETTLER_SHIM_INIT_HASH = \"0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f\";\n/**\n * How far past the newest deployment a chain accepts ({@link ZeroExChain.newestLiveNonce} plus the margin) the resolver\n * still derives, only to tell \"0x deployed a newer Settler than this module accepts\" (refused until the pin is raised)\n * from \"not a 0x Settler at all\".\n */\nexport const ZEROEX_SETTLER_LOOKAHEAD = 16;\n\n/** The newest deployment a token sale may use on a chain: the newest one live when pinned, plus the margin. */\nconst tokenCeiling = (chain: ZeroExChain): number => chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;\n\n/** The address the registry deploys taker-feature Settler number `nonce` to on `chainId` — computed, no network. */\nexport function zeroExSettlerAddress(chainId: number, nonce: number, registry: string = ZEROEX_SETTLER_REGISTRY): string {\n if (!Number.isSafeInteger(chainId) || chainId <= 0 || !Number.isSafeInteger(nonce) || nonce <= 0) throw new Error(\"zeroex: a Settler address needs a positive chain id and nonce\");\n const salt = pad(numberToHex((BigInt(ZEROEX_TAKER_FEATURE) << 128n) | (BigInt(chainId) << 64n) | BigInt(nonce)), {size: 32});\n const shim = getContractAddress({opcode: \"CREATE2\", from: registry as `0x${string}`, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH});\n return getContractAddress({opcode: \"CREATE\", from: shim, nonce: 1n});\n}\n\nconst derived = new Map<string, string[]>();\n/**\n * Which deployment of the registry's taker feature `address` is on `chainId` (its nonce), or null when it is none of\n * deployments 1…`maxNonce` — by default the newest one the default table accepts on the chain\n * ({@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}; a chain outside the table has none:\n * null). An RPC (or an API) can therefore only ever name a contract 0x's own registry deployed as a Settler — never an\n * arbitrary contract or account. Bounded by the pin, an address that is no Settler costs a few dozen derivations, not\n * a thousand. Memoized per chain.\n */\nexport function zeroExSettlerNonce(chainId: number, address: string, registry: string = ZEROEX_SETTLER_REGISTRY, maxNonce?: number): number | null {\n if (typeof address !== \"string\" || !ADDRESS.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS.test(registry)) return null;\n const pinned = zeroExChain(ZEROEX_CHAINS, chainId);\n const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);\n if (!Number.isSafeInteger(bound) || bound < 1) return null;\n const key = `${registry.toLowerCase()}:${chainId}`;\n let list = derived.get(key);\n if (!list) derived.set(key, (list = []));\n const want = address.toLowerCase();\n const hit = list.indexOf(want);\n if (hit >= 0) return hit < bound ? hit + 1 : null;\n while (list.length < bound) {\n const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();\n list.push(next);\n if (next === want) return list.length;\n }\n return null;\n}\n\n// ── the Settler in force ────────────────────────────────────────────────────\n\nexport interface SettlerResolverConfig {\n /** The chain table (registry per chain). */\n chains: Readonly<Record<number, ZeroExChain>>;\n /** JSON-RPC endpoints per EVM chain id. Without one for a chain, its Settler cannot be resolved and live quotes are refused. */\n rpcUrls?: RpcUrls | undefined;\n /** How long a registry read is reused, ms. Default 5 minutes; a miss always triggers a fresh read. */\n maxAgeMs?: number | undefined;\n /** Clock (tests). */\n now?: (() => number) | undefined;\n}\n\nexport interface SettlerResolver {\n /** The Settlers a swap on `chainId` may call: the one in force, then the one it replaced (if any). Throws when the registry cannot be read or the feature is paused. */\n resolve(chainId: number, options?: {fresh?: boolean}): Promise<readonly string[]>;\n /** The last resolved set while it is still fresh; empty otherwise. Never touches the network. */\n known(chainId: number): readonly string[];\n}\n\nconst DEFAULT_SETTLER_MAX_AGE_MS = 5 * 60_000;\n\n/** One 32-byte word that is an address (upper 12 bytes zero), as a checksummed address; null for anything else, the zero address included. */\nfunction addressWord(result: unknown): string | null {\n if (typeof result !== \"string\" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;\n const address = `0x${result.slice(26)}`;\n return ZERO_ADDRESS.test(address) ? null : getAddress(address);\n}\n\n/**\n * Reads the Settler in force from the registry and caches it per chain. The registry address comes from the chain\n * table; the answer comes from the integrator's own RPC — that RPC is what this module trusts for \"which contract\n * is 0x's Settler right now\", within hard bounds it cannot move: the answer must be a CREATE3 deployment of that\n * registry, no older than the chain's pinned {@link ZeroExChain.previousLiveNonce} and no newer than its\n * {@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}, with code at the address (read through\n * the same RPC). Which of these a native-coin sale may use is narrower still ({@link checkZeroExTransaction}).\n */\nexport function createSettlerResolver(config: SettlerResolverConfig): SettlerResolver {\n const maxAge = config.maxAgeMs !== undefined && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;\n const now = config.now ?? Date.now;\n const cache = new Map<number, {at: number; settlers: readonly string[]}>();\n const flights = new Map<number, Promise<readonly string[]>>();\n\n /** eth_call on the registry. `{reverted: true}` when the node says the call reverted; throws when nothing answered. */\n async function call(chainId: number, to: string, data: string): Promise<{result: string} | {reverted: true}> {\n if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} — the 0x Settler cannot be resolved`, \"policy_refused\");\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_call\", [{to, data}, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler cannot be resolved`, \"upstream_unavailable\");\n // An execution revert is an answer (the feature is paused / has no instance); any other error is the endpoint failing.\n if (\"error\" in answer) {\n if (isRevert(answer.error)) return {reverted: true};\n throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n }\n if (typeof answer.result !== \"string\") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n return {result: answer.result};\n }\n\n /** Addresses already seen holding code (per chain): a deployed Settler's code does not go away, so it is read once. */\n const withCode = new Set<string>();\n /** Whether `address` holds contract code, read over the same RPC as the registry. Throws when nothing answered. */\n async function hasCode(chainId: number, address: string): Promise<boolean> {\n const key = `${chainId}:${address.toLowerCase()}`;\n if (withCode.has(key)) return true;\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_getCode\", [address, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler's code cannot be read`, \"upstream_unavailable\");\n if (\"error\" in answer || typeof answer.result !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(answer.result)) throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler's code`, \"upstream_unavailable\");\n if (answer.result.length <= 2) return false;\n withCode.add(key);\n return true;\n }\n\n async function read(chainId: number): Promise<readonly string[]> {\n const entry = zeroExChain(config.chains, chainId);\n if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, \"0\");\n const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);\n if (\"reverted\" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, \"chain_halted\");\n const settler = addressWord(current.result);\n if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, \"vault_mismatch\");\n // The answer comes from one RPC: it must be a deployment the registry itself made, inside the window this module\n // pins for the chain, and a contract. A newer deployment is 0x moving on: refused, with what to do, until the pin\n // is raised (the watch job reports it the day it happens). An older one is a replaced Settler: refused.\n const oldest = entry.previousLiveNonce;\n const ceiling = tokenCeiling(entry);\n const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);\n if (nonce === null) {\n const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);\n if (newer !== null) {\n throw refuse(`the 0x registry on chain ${chainId} names Settler deployment ${newer} (${settler}), newer than the newest this module accepts there (${ceiling}) — update @anywalletkit/protocol-swap2-0x, or raise the chain's newestLiveNonce and previousLiveNonce once that deployment is checked`, \"vault_mismatch\");\n }\n throw refuse(`the RPC on chain ${chainId} names ${settler} as the 0x Settler, which is not an address the 0x registry deploys Settlers to`, \"vault_mismatch\");\n }\n if (nonce < oldest) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, older than the oldest this module accepts there (${oldest}) — a replaced Settler is not called`, \"vault_mismatch\");\n // A deployment that does not exist yet (inside the margin past the newest live one) has no code: value or tokens\n // sent there would be stranded until 0x deploys it.\n if (!(await hasCode(chainId, settler))) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, but no contract is deployed there`, \"vault_mismatch\");\n const settlers = [settler];\n // The instance it replaced: 0x keeps quoting it for a while after a new deployment. No previous instance reverts;\n // one outside the pinned window, or without code, is left out.\n try {\n const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);\n const prev = \"result\" in previous ? addressWord(previous.result) : null;\n const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;\n if (prev && prevNonce !== null && prevNonce >= oldest && (await hasCode(chainId, prev))) settlers.push(prev);\n } catch {\n // The current Settler alone is a valid (stricter) answer.\n }\n return Object.freeze(settlers);\n }\n\n return {\n async resolve(chainId, options) {\n const hit = cache.get(chainId);\n if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;\n const running = flights.get(chainId);\n if (running) return running;\n const flight = read(chainId).then((settlers) => {\n cache.set(chainId, {at: now(), settlers});\n return settlers;\n }).finally(() => {\n flights.delete(chainId);\n });\n flights.set(chainId, flight);\n return flight;\n },\n known(chainId) {\n const hit = cache.get(chainId);\n return hit && now() - hit.at <= maxAge ? hit.settlers : [];\n },\n };\n}\n\n// ── Settler.execute calldata ────────────────────────────────────────────────\n\nexport interface SettlerAction {\n /** 4-byte action selector, lowercase. */\n selector: string;\n /** Byte offset, inside the `execute` arguments, of the action's first argument word. */\n argsStart: number;\n /** The action's declared byte length (selector included). The first action of a Permit2 quote declares more than is there: its signature is appended later. */\n declaredLength: number;\n}\n\nexport interface SettlerExecute {\n /** Who Settler's slippage check pays. */\n recipient: string;\n /** The token that check measures (`0xEeee…` for the native coin). */\n buyToken: string;\n /** The least `recipient` receives, or the call reverts. */\n minAmountOut: bigint;\n /** 0x's trade id and affiliate tag (not checked). */\n zidAndAffiliate: string;\n actions: readonly SettlerAction[];\n /** Bytes of arguments after the 4-byte method selector. */\n bodyLength: number;\n /** The argument word at byte `offset`, as 64 hex characters; throws when it is out of range. */\n word(offset: number): string;\n}\n\nconst MAX_CALLDATA_BYTES = 65_536;\nconst MAX_ACTIONS = 256;\nconst ACTIONS_OFFSET = 0xa0;\n\n/**\n * Read `Settler.execute(slippage, actions, zidAndAffiliate)` calldata. Strict where it matters (method, the static\n * slippage tuple, the canonical position of the action array, every action inside the data) and tolerant where\n * Settler is: the data need not be a multiple of 32 bytes, and the first action may declare a length that runs past\n * the end (0x leaves room for the Permit2 signature there).\n */\nexport function decodeSettlerExecute(data: string): SettlerExecute {\n if (typeof data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse(\"the transaction data is not hex bytes\", \"policy_refused\");\n if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse(\"the transaction data is larger than any 0x swap\", \"policy_refused\");\n if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse(\"the transaction does not call Settler.execute\", \"policy_refused\");\n const body = data.slice(10).toLowerCase();\n const bodyLength = body.length / 2;\n const word = (offset: number): string => {\n if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse(\"the Settler call is cut short\", \"policy_refused\");\n return body.slice(offset * 2, offset * 2 + 64);\n };\n const address = (offset: number, what: string): string => {\n const w = word(offset);\n if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, \"policy_refused\");\n return getAddress(`0x${w.slice(24)}`);\n };\n /** A word that must be a small non-negative integer (an offset, a length, a count). */\n const small = (offset: number, what: string): number => {\n const w = word(offset);\n if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, \"policy_refused\");\n return parseInt(w.slice(56), 16);\n };\n\n const recipient = address(0x00, \"recipient\");\n const buyToken = address(0x20, \"buy token\");\n const minAmountOut = BigInt(`0x${word(0x40)}`);\n if (small(0x60, \"action array offset\") !== ACTIONS_OFFSET) throw refuse(\"the Settler call does not place its actions where the ABI does\", \"policy_refused\");\n const zidAndAffiliate = `0x${word(0x80)}`;\n const count = small(ACTIONS_OFFSET, \"action count\");\n if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, \"policy_refused\");\n const table = ACTIONS_OFFSET + 32;\n const actions: SettlerAction[] = [];\n for (let i = 0; i < count; i++) {\n const offset = small(table + 32 * i, \"action offset\");\n const at = table + offset;\n // Past the offset table, with room for the length word and a selector.\n if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, \"policy_refused\");\n const declaredLength = small(at, \"action length\");\n if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, \"policy_refused\");\n if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, \"policy_refused\");\n actions.push(Object.freeze({selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength}));\n }\n return Object.freeze({recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word});\n}\n\n// ── the transaction, held to the request ────────────────────────────────────\n\n/** What the user asked for — the only source of truth for the checks. */\nexport interface ZeroExExpectation {\n /** EVM chain id of the swap. */\n chainId: number;\n /**\n * The chain's entry in the table in force: its pins bound the target (a token sale: `previousLiveNonce` up to\n * `newestLiveNonce` plus the margin; a native-coin sale: exactly `newestLiveNonce` or `previousLiveNonce`). Default:\n * the default table's entry for `chainId`.\n */\n chain?: ZeroExChain | undefined;\n /** Settlers resolved from the registry for that chain ({@link SettlerResolver.resolve}). */\n settlers: readonly string[];\n /** The token sold: an ERC-20 address, or the zero address / `0xEeee…` for the native coin. */\n sellToken: string;\n /** The token bought, same convention. */\n buyToken: string;\n /** Exactly the input, base units. */\n sellAmount: bigint;\n /** Who must receive the output (the user's own address unless they named another). */\n recipient: string;\n /** The least the recipient must receive — the quote's minimum, already held to the requested slippage by the caller. */\n minBuyAmount: bigint;\n /** Clock for the Permit2 deadline (tests). */\n nowMs?: number;\n}\n\n/** The transaction fields the checks read (a quote's `txRequest` or a built `UnsignedTx`). */\nexport interface ZeroExTransaction {\n to?: string | undefined;\n data?: string | undefined;\n value?: string | undefined;\n chainId?: number | undefined;\n approvalAddress?: string | undefined;\n permit2Transfer?: string | undefined;\n gasLimit?: string | undefined;\n}\n\n/**\n * The most gas a 0x swap may be given. Unused gas is refunded, but a reverting route burns up to the limit, so a\n * quote that asks for a block's worth is refused. Real Settler swaps sit well under 2 million.\n */\nexport const ZEROEX_MAX_GAS_LIMIT = 6_000_000n;\n\nexport interface ZeroExCheckedTransaction {\n execute: SettlerExecute;\n /** The locally rebuilt Permit2 payload of a token sale; absent for a native-coin sale. */\n permit2?: Permit2Transfer;\n /** Name of the Settler action that spends the Permit2 signature (token sales). */\n permitAction?: string;\n}\n\n/**\n * Hold a 0x transaction to the request, or throw {@link ZeroExTransactionError}. Checked:\n *\n * 1. `to` is one of the registry's Settlers, and a deployment inside the chain's pinned window\n * (`previousLiveNonce` … `newestLiveNonce` + {@link ZEROEX_SETTLER_NONCE_MARGIN}); `chainId`, when present, is the\n * swap's chain.\n * 2. `value` is the input for a native-coin sale and zero for a token sale; a sale that sends value goes only to the\n * chain's `newestLiveNonce` or `previousLiveNonce` deployment — Settlers that were live when the table was pinned —\n * never into the margin; a gas limit, when given, is at most {@link ZEROEX_MAX_GAS_LIMIT}.\n * 3. The method is `execute`, and its slippage tuple names the expected recipient, the requested buy token and\n * exactly the expected minimum (never zero).\n * 4. Token sale: the allowance target is canonical Permit2; the Permit2 payload passes the core reader (Permit2\n * domain on this chain, the sell token, exactly the input, this very Settler as spender) and is rebuilt locally,\n * with a deadline at most {@link ZEROEX_MAX_PERMIT_SECONDS} away; the first action is a known Permit2-spending\n * action carrying that same token, amount, nonce and deadline, and its signature slot points at the end of the\n * data, where the signature is appended.\n * 5. Native-coin sale: no allowance target, no Permit2 payload, and the first action is `NATIVE_CHECK` — the only\n * place Settler would spend a Permit2 signature holds none.\n *\n * Not checked: the actions after the first (the route), the first action's own `recipient` (where Permit2 sends the\n * input: the Settler or a pool) and `zidAndAffiliate`. Settler's slippage check bounds what they can do.\n */\nexport function checkZeroExTransaction(tx: ZeroExTransaction, expected: ZeroExExpectation): ZeroExCheckedTransaction {\n if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse(\"the swap names no EVM chain\");\n if (!ADDRESS.test(expected.recipient) || ZERO_ADDRESS.test(expected.recipient)) throw refuse(\"the swap names no recipient\");\n if (!ADDRESS.test(expected.sellToken) || !ADDRESS.test(expected.buyToken)) throw refuse(\"the swap names no sell or buy token\");\n if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse(\"the swap has no input or no minimum output\");\n const nativeSell = isZeroExNative(expected.sellToken);\n const nativeBuy = isZeroExNative(expected.buyToken);\n if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse(\"the swap sells and buys the same token\");\n\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to)) throw refuse(\"the transaction has no target\", \"policy_refused\");\n const to = tx.to;\n if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, \"upstream_unavailable\");\n if (!expected.settlers.some((s) => same(s, to))) throw refuse(`the transaction target ${to} is not a 0x Settler from the on-chain registry`, \"vault_mismatch\");\n if (tx.chainId !== undefined && tx.chainId !== expected.chainId) throw refuse(`the transaction is for chain ${String(tx.chainId).slice(0, 20)}, not ${expected.chainId}`, \"vault_mismatch\");\n // Whatever settler list the caller hands in, the target is held to the chain's pins: a deployment of the registry\n // between the previous one live at pin time and the newest one a token sale may use.\n const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);\n if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));\n if (deployment === null || deployment < pin.previousLiveNonce) throw refuse(`the transaction target ${to} is not a 0x Settler deployment this module accepts on chain ${expected.chainId}`, \"vault_mismatch\");\n if (typeof tx.value !== \"string\" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse(\"the transaction value is not a decimal amount\", \"policy_refused\");\n const value = BigInt(tx.value);\n if (value !== (nativeSell ? expected.sellAmount : 0n)) throw refuse(nativeSell ? \"the transaction value is not the amount being sold\" : \"the transaction sends native coin with a token sale\", \"price_check_failed\");\n // Value goes straight to the target: only to a Settler that was live when the table was pinned. A deployment inside\n // the margin may not exist yet (its code is the RPC's word) — what is sent there would be stranded, or swept by\n // whatever 0x deploys there later. Refused until the package (its pins) is updated.\n if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {\n throw refuse(deployment > pin.newestLiveNonce\n ? `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, newer than the newest one live when this module's chain table was pinned (${pin.newestLiveNonce}) — a native-coin sale goes only to a pinned Settler: update @anywalletkit/protocol-swap2-0x`\n : `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, which was not live when this module's chain table was pinned (${pin.newestLiveNonce} and ${pin.previousLiveNonce} were) — a native-coin sale goes only to a pinned Settler`, \"vault_mismatch\");\n }\n if (tx.gasLimit !== undefined && (typeof tx.gasLimit !== \"string\" || !/^[0-9]{1,12}$/.test(tx.gasLimit) || BigInt(tx.gasLimit) === 0n || BigInt(tx.gasLimit) > ZEROEX_MAX_GAS_LIMIT)) {\n throw refuse(\"the transaction asks for more gas than any 0x swap needs\", \"policy_refused\");\n }\n if (typeof tx.data !== \"string\") throw refuse(\"the transaction has no data\", \"policy_refused\");\n\n const execute = decodeSettlerExecute(tx.data);\n if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, \"recipient_mismatch\");\n if (nativeBuy ? !same(execute.buyToken, ZEROEX_NATIVE) : !same(execute.buyToken, expected.buyToken)) throw refuse(`the swap delivers ${execute.buyToken}, not the token asked for`, \"price_check_failed\");\n if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, \"price_check_failed\");\n const first = execute.actions[0]!;\n\n if (nativeSell) {\n if (tx.approvalAddress !== undefined) throw refuse(\"a native-coin sale asks for a token allowance\", \"policy_refused\");\n if (tx.permit2Transfer !== undefined) throw refuse(\"a native-coin sale carries a Permit2 signature request\", \"policy_refused\");\n // Action 0 is where Settler would spend a Permit2 signature (any earlier, unspent permit of this account): a native\n // sale opens with NATIVE_CHECK and nothing else.\n if (first.selector !== SETTLER_NATIVE_CHECK_SELECTOR) throw refuse(`the swap's first action ${first.selector} is not the native-value check a native-coin sale opens with`, \"policy_refused\");\n return {execute};\n }\n\n if (typeof tx.approvalAddress !== \"string\" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse(\"the allowance target is not canonical Permit2\", \"vault_mismatch\");\n if (typeof tx.permit2Transfer !== \"string\") throw refuse(\"a token sale carries no Permit2 payload to sign\", \"policy_refused\");\n const nowMs = expected.nowMs ?? Date.now();\n let permit2: Permit2Transfer;\n try {\n permit2 = readPermit2Transfer(tx.permit2Transfer, {\n chainId: expected.chainId,\n token: expected.sellToken,\n amount: expected.sellAmount,\n spender: to,\n nowMs,\n });\n } catch (err) {\n throw refuse((err instanceof Error ? err.message : \"the Permit2 payload is refused\").replace(/^swap2: /, \"\"), refusalOf(err)?.reason ?? \"policy_refused\");\n }\n if (permit2.deadline > BigInt(Math.floor(nowMs / 1000) + ZEROEX_MAX_PERMIT_SECONDS)) throw refuse(`the Permit2 deadline is more than ${ZEROEX_MAX_PERMIT_SECONDS} s away`, \"policy_refused\");\n\n const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : undefined;\n if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, \"policy_refused\");\n const arg = (index: number) => execute.word(first.argsStart + 32 * index);\n // (address recipient, ((address token, uint256 amount), uint256 nonce, uint256 deadline), …): words 1–4.\n if (!/^0{24}/.test(arg(1)) || !same(`0x${arg(1).slice(24)}`, expected.sellToken)) throw refuse(`${action.name} pulls a token other than the one being sold`, \"policy_refused\");\n if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, \"policy_refused\");\n if (BigInt(`0x${arg(3)}`) !== permit2.nonce || BigInt(`0x${arg(4)}`) !== permit2.deadline) throw refuse(`${action.name} carries a different permit than the one to be signed`, \"policy_refused\");\n const sigOffset = arg(action.sigWord);\n if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {\n throw refuse(`${action.name} does not read its signature from the end of the data`, \"policy_refused\");\n }\n return {execute, permit2, permitAction: action.name};\n}\n","/**\n * Minimal JSON-RPC over the integrator's own endpoints (Hermes-safe: `timeoutSignal`, no AbortSignal.timeout).\n * The first endpoint that gives a JSON-RPC answer wins; an execution error is an answer, a transport failure is not.\n */\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\n\nexport type RpcUrls = Readonly<Record<number, readonly string[]>>;\nexport type RpcAnswer = {result: unknown} | {error: {code: unknown; message: string}};\n\nconst RPC_TIMEOUT_MS = 12_000;\n\n/** The endpoints configured for `chainId` (own property only). */\nexport function rpcUrlsFor(rpcUrls: RpcUrls | undefined, chainId: number): readonly string[] {\n if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];\n const urls = rpcUrls[chainId];\n return Array.isArray(urls) ? urls.filter((u): u is string => typeof u === \"string\" && u.length > 0) : [];\n}\n\n/** One request; null when no endpoint is configured or none answered. */\nexport async function rpcRequest(rpcUrls: RpcUrls | undefined, chainId: number, method: string, params: unknown[]): Promise<RpcAnswer | null> {\n for (const url of rpcUrlsFor(rpcUrls, chainId)) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}),\n signal: timeoutSignal(RPC_TIMEOUT_MS),\n });\n if (!res.ok) continue;\n const body = (await res.json()) as {result?: unknown; error?: {code?: unknown; message?: unknown} | null} | null;\n if (!body || typeof body !== \"object\") continue;\n if (body.error) return {error: {code: body.error.code, message: typeof body.error.message === \"string\" ? body.error.message : \"rpc error\"}};\n if (\"result\" in body) return {result: body.result ?? null};\n } catch {\n // next endpoint\n }\n }\n return null;\n}\n\n/** Whether a JSON-RPC error says the call itself reverted (as opposed to the endpoint failing). */\nexport function isRevert(error: {code: unknown; message: string}): boolean {\n return error.code === 3 || /revert/i.test(error.message);\n}\n","import {getAddress, hashTypedData} from \"viem\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\nimport {httpRefusal, refusal, refusalOf, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {anySignal, permit2TransferJson, readPermit2Transfer, sourceAssetOf, timeoutSignal, type Permit2Transfer} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {slippageFloor} from \"@anywalletkit/protocol-swap2-core/validate\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeZeroExActivity} from \"./activity.js\";\nimport {ZEROEX_NATIVE, ZEROEX_PERMIT2, zeroExChain, zeroExChainId, zeroExChains, type ZeroExChain} from \"./chains.js\";\nimport {rpcRequest, rpcUrlsFor, type RpcUrls} from \"./rpc.js\";\nimport {ZEROEX_MAX_NATIVE_QUOTE_SECONDS, ZEROEX_NATIVE_QUOTE_SKEW_SECONDS, checkZeroExTransaction, createSettlerResolver, isZeroExNative, type SettlerResolver, type ZeroExExpectation} from \"./settler.js\";\n\n/**\n * 0x Swap API v2 (docs.0x.org) as a same-chain swap2 provider, Permit2 flow: `/swap/permit2/price` for\n * indicative quotes, `/swap/permit2/quote` for the swap that is executed.\n *\n * The API needs a key on every request, so `zeroExProvider` with a key runs on your server only, and\n * `zeroExRemoteProvider` in the app: under React Native (Hermes or JSC) it refuses to be built with a\n * key at all — an app bundle keeps no secret, and React Native's fetch follows redirects with the key\n * header whatever `redirect` says. Whichever side quotes, nothing the API returns is signed as it\n * is: the Settler is read from the on-chain registry, the transaction is held to the request and the\n * Permit2 payload is rebuilt locally (see `settler.ts`); the engine then signs it as EIP-712 typed\n * data, appends the signature and estimates the signed call before broadcast. Every call goes out\n * with the account's own gas estimate (`ownGasEstimate`), never the quoted limit.\n *\n * Every refusal carries a `Swap2RefusalReason` next to its unchanged text (CS-13): HTTP 429 →\n * `rate_limited` (with Retry-After), 401/403 → `key_rejected`, 5xx or an unreachable / malformed\n * API → `upstream_unavailable`, no liquidity → `insufficient_liquidity`, a pair 0x does not serve →\n * `unsupported_pair`, a transaction or payload that fails the device's checks → `vault_mismatch` /\n * `recipient_mismatch` / `price_check_failed` / `policy_refused`. A malformed request is the\n * caller's own error and stays unclassified, and so does the caller's own abort.\n */\n\nexport const ZEROEX_PROVIDER = \"zeroex\";\nexport const ZEROEX_DEFAULT_BASE_URL = \"https://api.0x.org\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/**\n * A firm 0x quote is priced at one block; the Settler enforces the minimum, the engine re-checks this TTL before broadcast.\n * Two minutes so a mainnet approval (Ethereum: often past 45 s) still lands inside the quote; a token sale's TTL is cut to\n * the Permit2 deadline (quote + 300 s) − 20 s, a native sale's to 90 s.\n */\nconst DEFAULT_TTL_MS = 120_000;\nconst DEFAULT_TIMEOUT_MS = 10_000;\n/** The Permit2 deadline must outlive the quote by this much, so a signature is never made seconds before it lapses. */\nconst DEADLINE_MARGIN_MS = 20_000;\nconst MAX_RESPONSE_CHARS = 600_000;\n\nexport interface ZeroExProviderConfig {\n enabled?: boolean | undefined;\n /**\n * The 0x API key — server only. Best as a getter, read on every request, so the key lives where you keep secrets\n * (server env, a vault) and never in this config object; a string is accepted too (an env value read once). It is\n * sent only as the `0x-api-key` header to `baseUrl`; it is never put in a URL, a refusal, an error or a quote, and an\n * answer that came through a redirect is refused. Without a key (or with one that is not printable ASCII without\n * spaces) the provider serves no route. Under React Native a key is refused outright (the constructor throws): use\n * `zeroExRemoteProvider` in the app.\n */\n apiKey?: string | (() => string | undefined) | undefined;\n /** API origin. Default {@link ZEROEX_DEFAULT_BASE_URL}. Must be https (http only for localhost), or the key would travel in clear. */\n baseUrl?: string | undefined;\n /** Chain table entries merged over the defaults (EVM chain id → entry, `null` removes a chain). */\n chains?: Readonly<Record<number, ZeroExChain | null>> | undefined;\n /** JSON-RPC endpoints per EVM chain id: the Settler registry read (needed for every executable quote) and receipts. */\n rpcUrls?: RpcUrls | undefined;\n /** Slippage when the request names none, bps. Default 50. */\n defaultSlippageBps?: number | undefined;\n /** How long a quote is offered, ms. Default 120 s; never past the Permit2 deadline, and a native-coin sale's never past {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS}. */\n quoteTtlMs?: number | undefined;\n timeoutMs?: number | undefined;\n /** Liquidity sources 0x must not route through (its `excludedSources` names). */\n excludedSources?: readonly string[] | undefined;\n /** How long a Settler registry read is reused, ms. Default 5 minutes. */\n settlerMaxAgeMs?: number | undefined;\n /** Share a resolver (e.g. with `zeroExRemoteProvider`); built from `chains` / `rpcUrls` when absent. */\n settlerResolver?: SettlerResolver | undefined;\n}\n\n/** 0x error names (`{name, message, data}` bodies) as the refusal a wallet shows, and its reason. Anything else is reported by HTTP status. */\nconst API_ERRORS: Readonly<Record<string, readonly [string, Swap2RefusalReason]>> = Object.freeze({\n INPUT_INVALID: [\"0x rejected the request as invalid\", \"no_route\"],\n SWAP_VALIDATION_FAILED: [\"0x could not validate this swap\", \"no_route\"],\n TOKEN_NOT_SUPPORTED: [\"0x does not support one of these tokens\", \"unsupported_pair\"],\n RECIPIENT_NOT_SUPPORTED: [\"0x does not support a separate recipient for this swap\", \"unsupported_pair\"],\n USER_NOT_AUTHORIZED: [\"0x does not serve this account\", \"unsupported_pair\"],\n TAKER_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve this account\", \"unsupported_pair\"],\n RECIPIENT_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve this recipient\", \"unsupported_pair\"],\n BUY_TOKEN_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve the token being bought\", \"unsupported_pair\"],\n SELL_TOKEN_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve the token being sold\", \"unsupported_pair\"],\n XSTOCKS_NOT_AUTHORIZED: [\"0x does not serve this token for this account\", \"unsupported_pair\"],\n INSUFFICIENT_ASSET_LIQUIDITY: [\"0x has too little liquidity for this pair and amount\", \"insufficient_liquidity\"],\n INTERNAL_SERVER_ERROR: [\"0x had an internal error\", \"upstream_unavailable\"],\n UNCATEGORIZED: [\"0x could not quote this swap\", \"no_route\"],\n});\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst plain = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst own = (o: Record<string, unknown>, key: string): unknown => (Object.prototype.hasOwnProperty.call(o, key) ? o[key] : undefined);\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null);\nconst same = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^[0-9]{1,78}$/.test(a) && /^[0-9]{1,78}$/.test(b) && BigInt(a) === BigInt(b);\nconst isAddress = (v: unknown): v is string => typeof v === \"string\" && ADDRESS.test(v);\n/** How a fee token is named in a quote: `native` for the chain's coin, the checksummed address otherwise. */\nconst feeToken = (token: string): string => (isZeroExNative(token) ? \"native\" : getAddress(token));\n\n/** The key for one request: printable ASCII without spaces, or nothing. A throwing getter is \"no key\". */\nfunction readKey(source: ZeroExProviderConfig[\"apiKey\"]): string | undefined {\n let key: unknown = source;\n if (typeof source === \"function\") {\n try {\n key = source();\n } catch {\n return undefined;\n }\n }\n return typeof key === \"string\" && /^[\\x21-\\x7e]{1,200}$/.test(key) ? key : undefined;\n}\n\n/**\n * React Native (Hermes or JSC): an app bundle keeps no secret, and its fetch (OkHttp / NSURLSession) follows redirects\n * — carrying the key header along — whatever `redirect` says.\n */\nfunction onReactNative(): boolean {\n const g = globalThis as {HermesInternal?: unknown; navigator?: {product?: unknown}};\n return g.HermesInternal !== undefined || g.navigator?.product === \"ReactNative\";\n}\n\n/** `scheme://host[:port]` of a URL, lowercase; \"\" when it has none. No URL class: React Native's lacks `origin`. */\nconst originOf = (url: string): string => (/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i.exec(url)?.[0] ?? \"\").toLowerCase();\n\n/** The API origin, refused unless https (or http on this machine): the key rides on every request to it. */\nfunction apiOrigin(baseUrl: string | undefined): string {\n const url = (baseUrl ?? ZEROEX_DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n if (/^https:\\/\\/[^\\s/?#@]+(?:\\/[^\\s?#]*)?$/i.test(url)) return url;\n if (/^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?(?:\\/[^\\s?#]*)?$/i.test(url)) return url;\n throw new Error(\"zeroex: baseUrl must be an https:// origin (http only for localhost) — the API key is sent to it\");\n}\n\ntype Fee = NonNullable<Quote[\"fees\"]>[number];\n\n/**\n * The fees of a 0x answer as quote fee entries, or the reason they cannot be read. Strict on purpose: a quote whose\n * fees do not parse is refused, never shown as free.\n *\n * - `zeroExFee` (0x's on-chain fee, taken out of the trade; `buyAmount` is already net of it) → `protocol`, included.\n * - `integratorFee` / `integratorFees` — this module asks for none, so anything above zero is refused.\n * - `gasFee` (only gasless trades carry one) → `network`, included.\n * - `totalNetworkFee` (wei the taker pays for gas; `gas × gasPrice` when 0x leaves it null) → `network`, not included.\n */\n/** The one fee refusal that is a policy (an integrator fee nobody asked for); every other one is a quote that cannot be read. */\nconst UNASKED_INTEGRATOR_FEE = \"the quote carries an integrator fee this wallet did not ask for\";\n\nexport function zeroExFees(response: Record<string, unknown>, gas: {gas: unknown; gasPrice: unknown}): {fees: Fee[]; networkFeeKnown: boolean} | string {\n const fees = own(response, \"fees\");\n if (!plain(fees)) return \"the quote's fees are missing\";\n if (!Object.prototype.hasOwnProperty.call(fees, \"zeroExFee\")) return \"the quote does not say what 0x charges\";\n const out: Fee[] = [];\n const amountAndToken = (v: unknown): {amount: bigint; token: string} | null => {\n if (!plain(v)) return null;\n const amount = uint(own(v, \"amount\"));\n const token = own(v, \"token\");\n return amount !== null && isAddress(token) ? {amount, token} : null;\n };\n\n const zeroEx = own(fees, \"zeroExFee\");\n if (zeroEx !== null) {\n const fee = amountAndToken(zeroEx);\n if (!fee) return \"the 0x fee cannot be read\";\n if (fee.amount > 0n) out.push({type: \"protocol\", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: \"0x fee (taken on-chain, already out of the quoted amount)\"});\n }\n\n const integrator = own(fees, \"integratorFee\");\n if (integrator !== null && integrator !== undefined) {\n const fee = amountAndToken(integrator);\n if (!fee) return \"the integrator fee cannot be read\";\n if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;\n }\n const integrators = own(fees, \"integratorFees\");\n if (integrators !== null && integrators !== undefined) {\n if (!Array.isArray(integrators) || integrators.length > 16) return \"the integrator fees cannot be read\";\n for (const entry of integrators) {\n const fee = amountAndToken(entry);\n if (!fee) return \"the integrator fees cannot be read\";\n if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;\n }\n }\n\n const gasFee = own(fees, \"gasFee\");\n if (gasFee !== null && gasFee !== undefined) {\n const fee = amountAndToken(gasFee);\n if (!fee) return \"the gas fee cannot be read\";\n if (fee.amount > 0n) out.push({type: \"network\", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: \"Gas charged by 0x inside the trade\"});\n }\n\n const total = own(response, \"totalNetworkFee\");\n let network: bigint | null = null;\n if (total !== null && total !== undefined) {\n network = uint(total);\n if (network === null) return \"the network fee cannot be read\";\n } else if (gas.gas !== null && gas.gas !== undefined && gas.gasPrice !== null && gas.gasPrice !== undefined) {\n const units = uint(gas.gas);\n const price = uint(gas.gasPrice);\n if (units === null || price === null) return \"the gas estimate cannot be read\";\n network = units * price;\n }\n if (network !== null) out.push({type: \"network\", amount: network.toString(), token: \"native\", included: false, description: \"Estimated network fee (gas × gas price, as 0x reports it)\"});\n return {fees: out, networkFeeKnown: network !== null};\n}\n\n/** A tax in bps from `tokenMetadata`: a number or a decimal string; null when the API does not know it. */\nfunction taxBps(v: unknown): number | null | undefined {\n if (v === null || v === undefined) return null;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n if (typeof v === \"string\" && /^[0-9]{1,6}$/.test(v)) return Number(v);\n return undefined;\n}\n\nlet sequence = 0;\n\n/** What {@link zeroExProvider} returns: a swap2 provider, plus the Settler resolver it reads through (for signing policies, `zeroExKnownSpenders`). */\nexport type ZeroExProvider = CrossChainProvider & {readonly ownGasEstimate: true; readonly settlerResolver: SettlerResolver};\n\nexport function zeroExProvider(config: ZeroExProviderConfig): ZeroExProvider {\n if (config.apiKey !== undefined && onReactNative()) {\n throw new Error(\"zeroex: the 0x API key belongs on a server — in a React Native app it would ship in the bundle, and React Native's fetch follows redirects with the key attached. Run zeroExProvider({apiKey}) on your backend (createSwap2Handler) and zeroExRemoteProvider({baseUrl, rpcUrls}) in the app.\");\n }\n const baseUrl = apiOrigin(config.baseUrl);\n const apiOriginOnly = originOf(baseUrl);\n const chains = zeroExChains(config.chains);\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const excluded = (config.excludedSources ?? []).filter((s) => typeof s === \"string\" && /^[A-Za-z0-9_.\\- ]{1,60}$/.test(s));\n const resolver = config.settlerResolver ?? createSettlerResolver({chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs});\n\n /** The chain id when the chain is in the table and a key is there to ask with. */\n const chainIdOf = (caip2: string): number | null => {\n const id = zeroExChainId(caip2);\n return zeroExChain(chains, id) && readKey(config.apiKey) !== undefined ? id : null;\n };\n const chainOfIntent = (intentId: string): number => {\n const id = Number(intentId.split(\":\")[1]);\n return zeroExChain(chains, id) ? id : NaN;\n };\n\n return {\n name: ZEROEX_PROVIDER,\n describeActivity: describeZeroExActivity,\n supportsSameChain: true,\n // The quoted gas limit is the API's word: a native sale (like a Permit2 call) goes out with the account's own estimate.\n ownGasEstimate: true,\n settlerResolver: resolver,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => from.chain === to.chain && chainIdOf(from.chain) !== null,\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`zeroex: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n /** A refusal raised by the checks (settler.ts, the core reader): its text without the prefix, and its reason. */\n const refuseError = (e: unknown, prefix: RegExp, fallback: string): null =>\n refuse(e instanceof Error ? e.message.replace(prefix, \"\") : fallback, refusalOf(e) ?? \"policy_refused\");\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = zeroExChainId(params.sourceChain);\n const chain = zeroExChain(chains, chainId);\n if (!chain) return refuse(`0x is not configured for ${String(params.sourceChain).slice(0, 40)}`, \"unsupported_pair\");\n const key = readKey(config.apiKey);\n if (key === undefined) return refuse(\"no 0x API key is configured\", \"key_rejected\");\n\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${String(params.sourceToken).slice(0, 60)}`, \"unsupported_pair\");\n if (src.contract && !ADDRESS.test(src.contract)) return refuse(\"source token must be an EVM address\");\n const sellToken = src.contract ? getAddress(src.contract) : ZEROEX_NATIVE;\n if (typeof params.destToken !== \"string\" || !ADDRESS.test(params.destToken)) return refuse(\"destination token must be an EVM address\");\n const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : getAddress(params.destToken);\n const nativeSell = sellToken === ZEROEX_NATIVE;\n const nativeBuy = buyToken === ZEROEX_NATIVE;\n if (same(sellToken, buyToken)) return refuse(\"same token in and out\", \"unsupported_pair\");\n if (chain.wrappedNative && ((nativeSell && same(buyToken, chain.wrappedNative)) || (nativeBuy && same(sellToken, chain.wrappedNative)))) {\n return refuse(\"wrapping and unwrapping are not 0x swaps\", \"unsupported_pair\");\n }\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return refuse(\"invalid slippage\");\n let floor: bigint | null = null;\n if (params.minAmountOut !== undefined) {\n floor = uint(params.minAmountOut);\n if (floor === null) return refuse(\"minimum output is not an integer\");\n }\n\n const dry = params.dry !== false;\n let taker: string | undefined;\n let recipient: string | undefined;\n if (dry) {\n // An indicative price needs no account; with one, 0x can also report the balance and allowance it sees.\n const known = isAddress(params.refundAddress) ? params.refundAddress : isAddress(params.destAddress) ? params.destAddress : undefined;\n taker = known ? getAddress(known) : undefined;\n } else {\n if (!isAddress(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n recipient = getAddress(params.destAddress);\n taker = getAddress(isAddress(params.refundAddress) ? params.refundAddress : params.destAddress);\n }\n\n // The Settler comes from the chain before anything is asked of the API: no registry answer, no executable quote.\n let settlers: readonly string[] = [];\n if (!dry) {\n try {\n settlers = await resolver.resolve(chainId);\n } catch (e) {\n return refuseError(e, /^zeroex: /, \"the 0x Settler cannot be resolved\");\n }\n }\n\n const query: [string, string][] = [\n [\"chainId\", String(chainId)],\n [\"sellToken\", sellToken],\n [\"buyToken\", buyToken],\n [\"sellAmount\", amountIn.toString()],\n [\"slippageBps\", String(bps)],\n ];\n if (taker) query.push([\"taker\", taker]);\n if (recipient && taker && !same(recipient, taker)) query.push([\"recipient\", recipient]);\n if (excluded.length) query.push([\"excludedSources\", excluded.join(\",\")]);\n const url = `${baseUrl}/swap/permit2/${dry ? \"price\" : \"quote\"}?${query.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(\"&\")}`;\n\n let status: number;\n let text: string;\n let retryAfter: string | null = null;\n try {\n const timeout = timeoutSignal(timeoutMs);\n // The key rides in a header: a redirect (a misconfigured baseUrl, a compromised edge) must not carry it on.\n const res = await fetch(url, {method: \"GET\", redirect: \"error\", headers: {accept: \"application/json\", \"0x-api-key\": key, \"0x-version\": \"v2\"}, signal: signal ? anySignal([signal, timeout]) : timeout});\n // A fetch that ignores `redirect: \"error\"` (React Native's does): an answer that came through a redirect, or\n // from another origin than the configured one, is not used.\n if (res.redirected === true || (typeof res.url === \"string\" && res.url !== \"\" && originOf(res.url) !== apiOriginOnly)) {\n return refuse(\"the API answer came through a redirect or from another origin — refused (the key must not follow one)\", \"policy_refused\");\n }\n status = res.status;\n retryAfter = res.headers?.get?.(\"retry-after\") ?? null;\n text = await res.text();\n } catch (e) {\n // The caller's own abort is not the venue failing.\n return refuse(`API unreachable (${e instanceof Error ? e.name.slice(0, 40) : \"error\"})`, signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (text.length > MAX_RESPONSE_CHARS) return refuse(\"the API answer is larger than any quote\", \"upstream_unavailable\");\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n if (status < 200 || status >= 300) {\n const byStatus = httpRefusal(status, retryAfter);\n const name = plain(body) ? own(body, \"name\") : undefined;\n if (typeof name === \"string\" && Object.prototype.hasOwnProperty.call(API_ERRORS, name)) {\n const [why, reason] = API_ERRORS[name]!;\n // A 429 stays a rate limit (with its wait) whatever the body names; an upstream failure keeps its status.\n return refuse(`${why} (${name})`, byStatus?.reason === \"rate_limited\" ? byStatus : reason === \"upstream_unavailable\" || reason === \"key_rejected\" ? {reason, httpStatus: status} : reason);\n }\n if (status === 401 || status === 403) return refuse(`API key rejected (HTTP ${status})`, byStatus);\n if (status === 429) return refuse(\"rate limited (HTTP 429)\", byStatus);\n // Any other status: a JSON refusal is a quote 0x does not have; anything else is an answer of another shape.\n return refuse(`API answered HTTP ${status}`, byStatus ?? (plain(body) ? \"no_route\" : {reason: \"upstream_unavailable\", httpStatus: status}));\n }\n if (!plain(body)) return refuse(\"malformed API response\", \"upstream_unavailable\");\n const r = body;\n\n if (own(r, \"liquidityAvailable\") === false) return refuse(\"no liquidity for this pair and amount\", \"insufficient_liquidity\");\n if (own(r, \"liquidityAvailable\") !== true) return refuse(\"malformed API response (liquidity)\", \"upstream_unavailable\");\n const mode = own(r, \"mode\");\n if (mode !== undefined && mode !== \"exact-in\") return refuse(\"the API answered a quote that is not exact-input\", \"policy_refused\");\n const echoedSell = own(r, \"sellToken\");\n const echoedBuy = own(r, \"buyToken\");\n if (!isAddress(echoedSell) || !same(echoedSell, sellToken) || !isAddress(echoedBuy) || !same(echoedBuy, buyToken)) return refuse(\"the API quoted other tokens than the ones asked for\", \"policy_refused\");\n const quotedIn = uint(own(r, \"sellAmount\"));\n const buyAmount = uint(own(r, \"buyAmount\"));\n const minBuyAmount = uint(own(r, \"minBuyAmount\"));\n if (quotedIn === null || buyAmount === null || minBuyAmount === null) return refuse(\"malformed quote amounts\", \"upstream_unavailable\");\n if (quotedIn !== amountIn) return refuse(`quoted ${quotedIn}, not the requested ${amountIn}`, \"policy_refused\");\n if (minBuyAmount <= 0n || minBuyAmount > buyAmount) return refuse(\"the quoted minimum is not between zero and the quoted output\", \"price_check_failed\");\n if (minBuyAmount < slippageFloor(buyAmount, bps)) return refuse(`the quoted minimum ${minBuyAmount} is below the requested slippage (${bps} bps of ${buyAmount})`, \"price_check_failed\");\n if (floor !== null && minBuyAmount < floor) return refuse(`floor breach (min=${minBuyAmount} < floor=${floor})`, \"price_check_failed\");\n\n // A buy token that taxes transfers arrives short of the minimum Settler measured: refused rather than promised.\n // Only what 0x reports can be judged: a tax it does not flag (null / absent counts as none) is not caught here.\n const metadata = own(r, \"tokenMetadata\");\n const buyMeta = plain(metadata) ? own(metadata, \"buyToken\") : undefined;\n if (buyMeta !== undefined && buyMeta !== null) {\n if (!plain(buyMeta)) return refuse(\"malformed API response (token metadata)\", \"upstream_unavailable\");\n for (const field of [\"buyTaxBps\", \"transferTaxBps\"]) {\n const tax = taxBps(own(buyMeta, field));\n if (tax === undefined) return refuse(\"malformed API response (token tax)\", \"upstream_unavailable\");\n if (tax !== null && tax > 0) return refuse(\"the token being bought taxes transfers — the amount received cannot be guaranteed\", \"unsupported_pair\");\n }\n }\n\n const transaction = own(r, \"transaction\");\n if (!dry && !plain(transaction)) return refuse(\"the quote carries no transaction\", \"upstream_unavailable\");\n const tx = plain(transaction) ? transaction : undefined;\n const parsedFees = zeroExFees(r, tx ? {gas: own(tx, \"gas\"), gasPrice: own(tx, \"gasPrice\")} : {gas: own(r, \"gas\"), gasPrice: own(r, \"gasPrice\")});\n if (typeof parsedFees === \"string\") return refuse(parsedFees, parsedFees === UNASKED_INTEGRATOR_FEE ? \"policy_refused\" : \"upstream_unavailable\");\n\n // What 0x says about the account: informative only (the engine checks balance and allowance itself).\n const flags: string[] = [];\n const issues = own(r, \"issues\");\n if (plain(issues)) {\n if (own(issues, \"balance\")) flags.push(\"balance\");\n if (own(issues, \"simulationIncomplete\") === true) flags.push(\"simulationIncomplete\");\n const allowance = own(issues, \"allowance\");\n if (plain(allowance)) {\n const spender = own(allowance, \"spender\");\n if (!isAddress(spender) || !same(spender, ZEROEX_PERMIT2)) return refuse(\"the API asks for an allowance to something other than canonical Permit2\", \"vault_mismatch\");\n flags.push(\"allowance\");\n }\n // A source name 0x does not know is silently not excluded: a misspelt exclusion must not pass as applied.\n const invalid = own(issues, \"invalidSourcesPassed\");\n if (Array.isArray(invalid) && invalid.length) {\n const names = invalid.filter((n): n is string => typeof n === \"string\" && /^[A-Za-z0-9_.\\- ]{1,60}$/.test(n)).slice(0, 3);\n return refuse(`0x does not know the excluded source${invalid.length > 1 ? \"s\" : \"\"} ${names.length ? names.join(\", \") : \"it was given\"}${invalid.length > names.length ? \" and more\" : \"\"} — they would not be excluded`, \"policy_refused\");\n }\n }\n // 0x names canonical Permit2 as the allowance target of every answer, native sales included (where nothing is\n // approved: the transaction below carries no allowance target then). Anything else is refused.\n const allowanceTarget = own(r, \"allowanceTarget\");\n if (allowanceTarget !== null && allowanceTarget !== undefined) {\n const permit2Target = isAddress(allowanceTarget) && same(allowanceTarget, ZEROEX_PERMIT2);\n if (nativeSell && !permit2Target) return refuse(\"the API asks for a token allowance on a native-coin sale\", \"policy_refused\");\n if (!permit2Target) return refuse(\"the API asks for an allowance to something other than canonical Permit2\", \"vault_mismatch\");\n }\n const zidRaw = own(r, \"zid\");\n const zid = typeof zidRaw === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(zidRaw) ? zidRaw : undefined;\n\n const now = Date.now();\n let validUntilMs = now + ttl;\n let txRequest: Quote[\"txRequest\"];\n let settler: string | undefined;\n if (!dry && tx && recipient) {\n const to = own(tx, \"to\");\n const data = own(tx, \"data\");\n const value = uint(own(tx, \"value\"));\n if (!isAddress(to) || typeof data !== \"string\" || value === null) return refuse(\"malformed quote transaction\", \"upstream_unavailable\");\n\n let permit2Transfer: string | undefined;\n let permit2: Permit2Transfer | undefined;\n const permit = own(r, \"permit2\");\n if (nativeSell) {\n if (permit !== null && permit !== undefined) return refuse(\"the API asks for a Permit2 signature on a native-coin sale\", \"policy_refused\");\n // A native sale signs nothing that would lapse: its quote is bounded here, inside the app verifier's bound by the clock-skew allowance.\n validUntilMs = Math.min(validUntilMs, now + (ZEROEX_MAX_NATIVE_QUOTE_SECONDS - ZEROEX_NATIVE_QUOTE_SKEW_SECONDS) * 1000);\n } else {\n const eip712 = plain(permit) ? own(permit, \"eip712\") : undefined;\n if (!plain(permit) || !plain(eip712)) return refuse(\"the quote carries no Permit2 payload to sign\", \"policy_refused\");\n try {\n // Only these four members are read; the reader holds them to this swap and the payload is rebuilt from that.\n permit2 = readPermit2Transfer(JSON.stringify({domain: own(eip712, \"domain\"), types: own(eip712, \"types\"), primaryType: own(eip712, \"primaryType\"), message: own(eip712, \"message\")}), {\n chainId,\n token: sellToken,\n amount: amountIn,\n spender: to,\n nowMs: now,\n });\n } catch (e) {\n return refuseError(e, /^swap2: /, \"the Permit2 payload is refused\");\n }\n // 0x states the digest it expects signed; the locally rebuilt payload must hash to it.\n const hash = own(permit, \"hash\");\n if (hash !== null && hash !== undefined) {\n const local = hashTypedData({\n domain: permit2.domain,\n types: {PermitTransferFrom: permit2.types.PermitTransferFrom, TokenPermissions: permit2.types.TokenPermissions},\n primaryType: permit2.primaryType,\n message: permit2.message,\n } as unknown as Parameters<typeof hashTypedData>[0]);\n if (typeof hash !== \"string\" || !same(hash, local)) return refuse(\"the Permit2 payload does not hash to what the API says is being signed\", \"policy_refused\");\n }\n permit2Transfer = permit2TransferJson(permit2);\n // The quote lapses before the signature it asks for does (the reader bounds the deadline to the next hour).\n const lapse = permit2.deadline * 1000n - BigInt(DEADLINE_MARGIN_MS);\n if (lapse <= BigInt(now)) return refuse(\"the Permit2 deadline is too close to sign against\", \"quote_expired\");\n if (lapse < BigInt(validUntilMs)) validUntilMs = bigintToNumber(lapse);\n }\n\n const gas = uint(own(tx, \"gas\"));\n // 0x's own limit for the call, with room for the appended signature and a moved route.\n const gasLimit = gas !== null && gas > 0n ? ((gas * 12n) / 10n + 20_000n).toString() : undefined;\n const candidate = {\n to,\n data,\n value: value.toString(),\n chainId,\n ...(gasLimit !== undefined ? {gasLimit} : {}),\n ...(nativeSell ? {} : {approvalAddress: ZEROEX_PERMIT2}),\n ...(permit2Transfer !== undefined ? {permit2Transfer} : {}),\n };\n const expectation = (set: readonly string[]): ZeroExExpectation => ({chainId, chain, settlers: set, sellToken, buyToken, sellAmount: amountIn, recipient: recipient!, minBuyAmount, nowMs: now});\n try {\n try {\n checkZeroExTransaction(candidate, expectation(settlers));\n } catch (first) {\n // 0x may already quote a Settler deployed after the cached registry read: read again, once.\n if (settlers.some((s) => same(s, to))) throw first;\n settlers = await resolver.resolve(chainId, {fresh: true});\n checkZeroExTransaction(candidate, expectation(settlers));\n }\n } catch (e) {\n return refuseError(e, /^zeroex: /, \"the transaction is refused\");\n }\n settler = getAddress(to);\n txRequest = {\n to: settler,\n data,\n value: value.toString(),\n chainId,\n ...(gasLimit !== undefined ? {gasLimit} : {}),\n ...(nativeSell ? {} : {approvalAddress: getAddress(ZEROEX_PERMIT2)}),\n ...(permit2Transfer !== undefined ? {permit2Transfer} : {}),\n };\n }\n\n const sources = zeroExSources(own(r, \"route\"));\n return {\n provider: ZEROEX_PROVIDER,\n intentId: `zeroex:${chainId}:${now.toString(36)}${(sequence = (sequence + 1) % 1_000_000).toString(36)}`,\n depositAddress: \"\",\n depositMemo: null,\n ...(txRequest ? {txRequest} : {}),\n sourceAmount: amountIn.toString(),\n destAmount: buyAmount.toString(),\n minDestAmount: minBuyAmount.toString(),\n feeUsd: 0,\n fees: parsedFees.fees,\n etaSeconds: 15,\n reliability: 0.96,\n validUntilMs,\n providerData: {\n minOut: minBuyAmount.toString(),\n slippageBps: String(bps),\n ...(taker ? {sender: taker} : {}),\n ...(settler ? {settler} : {}),\n ...(zid ? {zid} : {}),\n ...(sources ? {sources} : {}),\n ...(parsedFees.networkFeeKnown ? {} : {networkFee: \"unknown\"}),\n ...(flags.length ? {issues: flags.join(\",\")} : {}),\n },\n };\n },\n\n /**\n * Before the engine signs: the transaction must be the quoted one, and its target must still be a Settler in the\n * registry now ({@link zeroExPreflightDeposit}). The call itself cannot be simulated yet: it needs the Permit2\n * signature, which the engine makes next and then estimates as signed.\n */\n preflightDeposit: (quote: Quote, tx: UnsignedTx): Promise<void> => zeroExPreflightDeposit(quote, tx, {chains, resolver}),\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"zeroex: not a live quote — it carries no transaction\");\n return {\n chain: \"\",\n to: tx.to,\n value: tx.value ?? \"0\",\n data: tx.data,\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n ...(tx.permit2Transfer !== undefined ? {permit2Transfer: tx.permit2Transfer} : {}),\n };\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash || !/^0x[0-9a-fA-F]{64}$/.test(ref.sourceTxHash)) return {state: \"pending\"};\n const chainId = chainOfIntent(ref.intentId);\n if (Number.isNaN(chainId) || !rpcUrlsFor(config.rpcUrls, chainId).length) return {state: \"pending\"};\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash]);\n if (!answer || \"error\" in answer || !plain(answer.result)) return {state: \"pending\"};\n const status = own(answer.result, \"status\");\n if (status === \"0x1\") return {state: \"completed\", destTxHash: ref.sourceTxHash};\n return status === \"0x0\" ? {state: \"failed\"} : {state: \"pending\"};\n },\n };\n}\n\n/**\n * The device's last check before the engine signs a 0x swap, run by the `preflightDeposit` of both providers (in remote\n * mode before the backend's own preflight is asked): the transaction must be the quoted one, and its target must still\n * be a Settler the registry names now — a fresh read through `resolver` (the device's own RPC), so a Settler paused,\n * replaced or removed since the quote (on the review screen, during an approval) is refused here, with nothing signed\n * or sent.\n */\nexport async function zeroExPreflightDeposit(quote: Quote, tx: UnsignedTx, ctx: {chains: Readonly<Record<number, ZeroExChain>>; resolver: SettlerResolver}): Promise<void> {\n const quoted = quote.txRequest;\n if (\n !quoted?.to || !quoted.data || typeof tx.to !== \"string\" || typeof tx.data !== \"string\" ||\n !same(tx.to, quoted.to) || !same(tx.data, quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\") ||\n tx.permit2Transfer !== quoted.permit2Transfer\n ) {\n throw refusal(\"policy_refused\", \"zeroex: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n const chainId = typeof quote.intentId === \"string\" ? Number(quote.intentId.split(\":\")[1]) : NaN;\n if (!zeroExChain(ctx.chains, chainId)) throw refusal(\"policy_refused\", \"zeroex: the quote names no chain this provider serves. Nothing was sent.\");\n const settlers = await ctx.resolver.resolve(chainId, {fresh: true});\n if (!settlers.some((s) => same(s, quoted.to!))) {\n throw refusal(\"vault_mismatch\", \"zeroex: the quoted 0x Settler is no longer in the on-chain registry. Nothing was sent; refresh the quote.\");\n }\n}\n\n/** The liquidity sources of `route.fills`, at most six short names, for display. */\nfunction zeroExSources(route: unknown): string | undefined {\n const fills = plain(route) ? own(route, \"fills\") : undefined;\n if (!Array.isArray(fills)) return undefined;\n const names: string[] = [];\n for (const fill of fills.slice(0, 64)) {\n const source = plain(fill) ? own(fill, \"source\") : undefined;\n if (typeof source !== \"string\" || !/^[A-Za-z0-9_.\\- ]{1,40}$/.test(source)) continue;\n if (!names.includes(source)) names.push(source);\n if (names.length === 6) break;\n }\n return names.length ? names.join(\",\") : undefined;\n}\n","/**\n * Activity recognition for 0x: a `Settler.execute` call to a 0x Settler on a chain the module serves\n * → `swap`, \"Swapped A → B\" from the owner's net transfers.\n *\n * 0x replaces its Settler contracts regularly (the registry names the one in force), so past swaps\n * were sent to addresses no pinned list can hold. Every Settler, past or present, is however an\n * address the registry deploys to (CREATE3, see `zeroExSettlerNonce`), which is computed offline: a\n * transaction is recognized by its target being one, by the method (`execute`, selector `0x1fff991f`)\n * and, when its calldata is there, by that calldata reading as a Settler call. A contract that only\n * copies the selector is not labelled a 0x swap. This only labels history; nothing is signed on it.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {callSelector, chainLabel, describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {ZEROEX_CHAINS, ZEROEX_SETTLER_NONCE_MARGIN, zeroExChain, zeroExChainId} from \"./chains.js\";\nimport {SETTLER_EXECUTE_SELECTOR, decodeSettlerExecute, zeroExSettlerNonce} from \"./settler.js\";\n\nexport const ZEROEX_MODULE = \"@anywalletkit/protocol-swap2-0x\";\n\nexport function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n const chainId = zeroExChainId(tx.chain);\n const chain = zeroExChain(ZEROEX_CHAINS, chainId);\n if (!chain) return null;\n if (callSelector(tx) !== SETTLER_EXECUTE_SELECTOR) return null;\n const target = tx.call?.to ?? tx.to;\n // Any deployment up to the newest one the chain accepts (past swaps went to older Settlers too); bounded by the pin,\n // an address that is no Settler costs a few dozen derivations.\n if (typeof target !== \"string\" || zeroExSettlerNonce(chainId, target, chain.registry, chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN) === null) return null;\n const data = tx.call?.data;\n if (typeof data === \"string\" && data.length > 10) {\n try {\n decodeSettlerExecute(data);\n } catch {\n return null;\n }\n }\n return describeSwapLike(tx, ctx, {protocol: ZEROEX_MODULE, subtitle: `0x · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * The app's side of 0x when the API key stays on a server.\n *\n * `zeroExRemoteProvider({baseUrl, rpcUrls})` forwards quotes and builds to your backend (which runs\n * `zeroExProvider` with the key) and checks, on the device, everything that comes back before the\n * engine signs: the Settler from the on-chain registry read through the app's own RPC, the\n * transaction and the Permit2 payload held to the request the app itself sent\n * ({@link zeroExVerifyQuote} on the quote, {@link zeroExVerifyBuild} on the build), and, right\n * before the broadcast, the registry read once more ({@link zeroExPreflightDeposit}) ahead of the\n * backend's own preflight. The backend is what these checks guard against; it never names its own\n * Settler, spender, recipient or minimum.\n *\n * Every text the verifiers return is classified (`zeroExPins.reasonOf`, CS-13), so a remote stub's\n * refusal carries its `Swap2RefusalReason`; the app's own malformed request stays unclassified.\n */\nimport {getAddress} from \"viem\";\nimport {refusalNotes, refusalOf, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {remoteProvider, type RemoteProviderOptions} from \"@anywalletkit/protocol-swap2-core/remote\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {slippageFloor} from \"@anywalletkit/protocol-swap2-core/validate\";\nimport type {CrossChainProvider, Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeZeroExActivity} from \"./activity.js\";\nimport {ZEROEX_NATIVE, ZEROEX_PERMIT2, zeroExChain, zeroExChainId, zeroExChains, type ZeroExChain} from \"./chains.js\";\nimport {ZEROEX_PROVIDER, zeroExPreflightDeposit} from \"./provider.js\";\nimport type {RpcUrls} from \"./rpc.js\";\nimport {ZEROEX_MAX_NATIVE_QUOTE_SECONDS, checkZeroExTransaction, createSettlerResolver, isZeroExNative, type SettlerResolver} from \"./settler.js\";\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst same = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null);\nconst message = (e: unknown, fallback: string): string => (e instanceof Error ? e.message.replace(/^zeroex: /, \"\") : fallback);\n\n/** The reason behind each text {@link zeroExVerifyQuote} / {@link zeroExVerifyBuild} return (`zeroExPins.reasonOf`). */\nconst notes = refusalNotes();\n/** A verifier's answer: the text, its reason remembered (none: the app's own malformed request). */\nconst note = (text: string, reason?: Swap2RefusalReason): string =>\n // Noted without a valid reason, a text is unclassified (and forgets any earlier classification of the same text).\n notes.note(text, reason ?? ({} as Swap2RefusalReason));\n/** A refusal raised by the checks: its text without the prefix, and the reason it carries. */\nconst noteError = (e: unknown, fallback: string): string => note(message(e, fallback), refusalOf(e)?.reason ?? \"policy_refused\");\n\n/** The reason a text from {@link zeroExVerifyQuote} or {@link zeroExVerifyBuild} carries; undefined for any other text. */\nexport const zeroExRefusalReason = (text: string) => notes.reasonOf(text);\n\nexport interface ZeroExVerifyContext {\n /** The chain table in force. */\n chains: Readonly<Record<number, ZeroExChain>>;\n /** Settlers the app resolved from the registry for a chain (never the backend's word). */\n settlers(chainId: number): readonly string[];\n /** The most slippage accepted when the request named none, bps. Default 50 — the provider's own default. */\n defaultSlippageBps?: number | undefined;\n /** Clock (tests). */\n nowMs?: number | undefined;\n}\n\n/**\n * A remote 0x quote, held to the request the app sent. Null when it passes, the reason otherwise.\n *\n * An indicative quote (`dry`) carries no transaction and only its amounts are checked. A live quote must carry one,\n * and it goes through {@link checkZeroExTransaction} with an expectation built only from `params`: the sell token and\n * amount, the buy token, the app's recipient, the quote's minimum (itself held to the requested slippage and floor),\n * the chain's pins and the Settlers the app resolved. It may stay valid no longer than its Permit2 deadline (a token\n * sale) or {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS} from now (a native-coin sale).\n */\nexport function zeroExVerifyQuote(params: QuoteParams, quote: Quote, ctx: ZeroExVerifyContext): string | null {\n if (quote.provider !== ZEROEX_PROVIDER) return note(\"the quote is not a 0x quote\", \"policy_refused\");\n if (params.sourceChain !== params.destChain) return note(\"0x swaps stay on one chain\", \"unsupported_pair\");\n const chainId = zeroExChainId(params.sourceChain);\n const chain = zeroExChain(ctx.chains, chainId);\n if (!chain) return note(\"the chain is not in the 0x chain table\", \"unsupported_pair\");\n if (quote.intentId.replace(/~[0-9a-f]{32}$/, \"\").split(\":\").slice(0, 2).join(\":\") !== `zeroex:${chainId}`) return note(\"the intent id does not name this chain\", \"policy_refused\");\n const src = sourceAssetOf(params);\n if (!src) return note(\"unknown source token\");\n if (src.contract && !ADDRESS.test(src.contract)) return note(\"the source token is not an EVM address\");\n if (typeof params.destToken !== \"string\" || !ADDRESS.test(params.destToken)) return note(\"the destination token is not an EVM address\");\n const sellToken = src.contract ? getAddress(src.contract) : ZEROEX_NATIVE;\n const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : getAddress(params.destToken);\n\n const amountIn = uint(params.amountIn);\n const quotedIn = uint(quote.sourceAmount);\n const dest = uint(quote.destAmount);\n const min = uint(quote.minDestAmount);\n if (amountIn === null || quotedIn === null || dest === null || min === null) return note(\"the quote's amounts are not integers\", amountIn === null ? undefined : \"upstream_unavailable\");\n if (quotedIn !== amountIn) return note(`the quote spends ${quotedIn}, not the ${amountIn} input`, \"policy_refused\");\n if (min <= 0n || min > dest) return note(\"the quoted minimum is not between zero and the quoted output\", \"price_check_failed\");\n const bps = params.slippageBps ?? ctx.defaultSlippageBps ?? 50;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return note(\"invalid slippage\");\n if (min < slippageFloor(dest, bps)) return note(`the quoted minimum ${min} is below ${bps} bps of the quoted output`, \"price_check_failed\");\n if (params.minAmountOut !== undefined) {\n const floor = uint(params.minAmountOut);\n if (floor === null || min < floor) return note(`the quoted minimum ${min} is below the caller's floor`, floor === null ? undefined : \"price_check_failed\");\n }\n\n const tx = quote.txRequest;\n const dry = params.dry !== false;\n if (!tx) return dry ? null : note(\"a live quote carries no transaction\", \"upstream_unavailable\");\n if (dry) return note(\"an indicative quote carries a transaction\", \"policy_refused\");\n if (tx.serializedTx !== undefined || tx.nativeFee !== undefined) return note(\"the quote carries more than a Settler call\", \"policy_refused\");\n if (typeof params.destAddress !== \"string\" || !ADDRESS.test(params.destAddress)) return note(\"a live quote needs the recipient\", \"recipient_mismatch\");\n try {\n const checked = checkZeroExTransaction(tx, {\n chainId,\n chain,\n settlers: ctx.settlers(chainId),\n sellToken,\n buyToken,\n sellAmount: amountIn,\n recipient: params.destAddress,\n minBuyAmount: min,\n ...(ctx.nowMs !== undefined ? {nowMs: ctx.nowMs} : {}),\n });\n // The quote must lapse before the signature it asks for does; a native sale, which signs nothing, within a short window.\n if (checked.permit2 && !(Number.isFinite(quote.validUntilMs) && BigInt(Math.ceil(quote.validUntilMs)) <= checked.permit2.deadline * 1000n)) return note(\"the quote outlives its Permit2 deadline\", \"policy_refused\");\n if (!checked.permit2 && !(Number.isFinite(quote.validUntilMs) && quote.validUntilMs <= (ctx.nowMs ?? Date.now()) + ZEROEX_MAX_NATIVE_QUOTE_SECONDS * 1000)) {\n return note(`the native-coin sale's quote is valid for more than ${ZEROEX_MAX_NATIVE_QUOTE_SECONDS} s`, \"policy_refused\");\n }\n } catch (e) {\n return noteError(e, \"the transaction is refused\");\n }\n return null;\n}\n\n/**\n * A remote 0x build, held to its quote and to the request: the built transaction must be the quote's own (target,\n * data, value, chain, allowance target, Permit2 payload), and that quote must pass {@link zeroExVerifyQuote} again\n * against Settlers read from the registry just now. Without the request (`params`) nothing can be checked: refused.\n */\nexport async function zeroExVerifyBuild(quote: Quote, tx: UnsignedTx, params: QuoteParams | undefined, ctx: ZeroExVerifyContext & {resolver: SettlerResolver}): Promise<string | null> {\n if (!params) return note(\"the request this quote answered is not known to the app\", \"policy_refused\");\n const quoted = quote.txRequest;\n if (!quoted?.to || !quoted.data) return note(\"the quote carries no transaction\", \"policy_refused\");\n if (\n typeof tx.to !== \"string\" || typeof tx.data !== \"string\" || !same(tx.to, quoted.to) || !same(tx.data, quoted.data) ||\n uint(tx.value || \"0\") === null || uint(tx.value || \"0\") !== uint(quoted.value ?? \"0\") ||\n (tx.chainId !== undefined && tx.chainId !== quoted.chainId) ||\n tx.approvalAddress !== quoted.approvalAddress || tx.permit2Transfer !== quoted.permit2Transfer || tx.gasLimit !== quoted.gasLimit ||\n tx.serializedTx !== undefined || tx.typedData !== undefined || tx.memo !== undefined\n ) {\n return note(\"the built transaction is not the quoted swap\", \"policy_refused\");\n }\n let settlers: readonly string[];\n try {\n settlers = await ctx.resolver.resolve(zeroExChainId(params.sourceChain), {fresh: true});\n } catch (e) {\n return noteError(e, \"the 0x Settler cannot be resolved\");\n }\n return zeroExVerifyQuote({...params, dry: false}, quote, {...ctx, settlers: () => settlers});\n}\n\nexport interface ZeroExPinsConfig {\n chains?: Readonly<Record<number, ZeroExChain | null>> | undefined;\n /** JSON-RPC endpoints per EVM chain id — the app's own, for the Settler registry read. */\n rpcUrls?: RpcUrls | undefined;\n settlerMaxAgeMs?: number | undefined;\n settlerResolver?: SettlerResolver | undefined;\n /** The most slippage accepted when a request names none, bps. Default 50; keep it in step with the backend's default. */\n defaultSlippageBps?: number | undefined;\n}\n\n/**\n * The app's pins for a remote 0x provider. Unlike a provider with one fixed router, the call target is whatever the\n * registry names now, so the pins hold a resolver: `callTargets` answers from its last fresh read (empty until one is\n * made — use {@link zeroExRemoteProvider}, which reads before every live quote and build), `spenders` is canonical\n * Permit2 and nothing else. `reasonOf` classifies every text the verifiers return.\n *\n * For a signing policy's known Permit2 spenders (wallet-evm `describeTypedData({knownSpenders})`, a kit allowlist)\n * use {@link zeroExKnownSpenders} with the provider the app swaps through: the Settler rotates, so no static table can\n * hold it, and a fresh `zeroExPins()` has a resolver of its own that has read nothing yet.\n */\nexport function zeroExPins(config: ZeroExPinsConfig = {}): RemotePins & {resolver: SettlerResolver; chains: Readonly<Record<number, ZeroExChain>>} {\n const chains = zeroExChains(config.chains);\n const resolver = config.settlerResolver ?? createSettlerResolver({chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs});\n const ctx: ZeroExVerifyContext = {chains, settlers: (chainId) => resolver.known(chainId), defaultSlippageBps: config.defaultSlippageBps};\n return Object.freeze({\n resolver,\n chains,\n callTargets: (chain: string): readonly string[] => (zeroExChain(chains, zeroExChainId(chain)) ? resolver.known(zeroExChainId(chain)) : []),\n spenders: (chain: string): readonly string[] => (zeroExChain(chains, zeroExChainId(chain)) ? [ZEROEX_PERMIT2] : []),\n verifyQuote: (params: QuoteParams, quote: Quote) => zeroExVerifyQuote(params, quote, ctx),\n verifyBuild: (quote: Quote, tx: UnsignedTx, params?: QuoteParams) => zeroExVerifyBuild(quote, tx, params, {...ctx, resolver}),\n reasonOf: zeroExRefusalReason,\n });\n}\n\nexport interface ZeroExRemoteOptions extends ZeroExPinsConfig, Pick<RemoteProviderOptions, \"baseUrl\" | \"enabled\" | \"fetchImpl\" | \"headers\" | \"timeoutMs\" | \"allowInsecureBaseUrl\"> {}\n\n/** What {@link zeroExRemoteProvider} returns: a remote swap2 provider, plus the Settler resolver it reads through. */\nexport type ZeroExRemoteProvider = CrossChainProvider & {readonly ownGasEstimate: true; readonly settlerResolver: SettlerResolver};\n\n/** How long a live quote's Settler set stays a call target after the quote, at most (its own `validUntilMs` first). */\nconst QUOTED_SET_MAX_MS = 120_000;\n\n/**\n * 0x through your backend: `remoteProvider` with {@link zeroExPins}, plus the registry reads the pins need — the\n * Settler is resolved through the app's RPC before a live quote is asked for (and once more, fresh, if the backend\n * quotes a Settler the app has not seen yet), and the quote is held to exactly that set, however long the backend\n * takes to answer; right before the broadcast `preflightDeposit` reads the registry again on the device and refuses a\n * Settler no longer in it ({@link zeroExPreflightDeposit}), then asks the backend's preflight. Indicative quotes need\n * no RPC. `settlerResolver` is the resolver it reads through (signing policies: {@link zeroExKnownSpenders}).\n */\nexport function zeroExRemoteProvider(options: ZeroExRemoteOptions): ZeroExRemoteProvider {\n const pins = zeroExPins(options);\n const served = (caip2: string): boolean => !!zeroExChain(pins.chains, zeroExChainId(caip2));\n // The Settlers each live quote request was resolved against, by request: the verifier holds the backend's answer to\n // that set, not to whatever the resolver's cache holds once the backend answered (its max age may pass meanwhile).\n const checkedAgainst = new WeakMap<QuoteParams, readonly string[]>();\n // …and, per chain, while that quote may still be used: the router's pin check (callTargets) runs after the answer too.\n const quoted = new Map<number, {settlers: readonly string[]; untilMs: number}>();\n const callTargets = (chain: string): readonly string[] => {\n const chainId = zeroExChainId(chain);\n const known = pins.callTargets(chain);\n const held = quoted.get(chainId);\n if (!held || held.untilMs < Date.now() || !zeroExChain(pins.chains, chainId)) return known;\n return [...known, ...held.settlers.filter((s) => !known.some((k) => same(k, s)))];\n };\n const verifyCtx: ZeroExVerifyContext = {chains: pins.chains, settlers: (chainId) => pins.resolver.known(chainId), defaultSlippageBps: options.defaultSlippageBps};\n const inner = remoteProvider({\n name: ZEROEX_PROVIDER,\n baseUrl: options.baseUrl,\n supportsSameChain: true,\n supportsChain: served,\n supportsChainPair: (from, to) => from === to && served(from),\n supportsRoute: (from, to) => from.chain === to.chain && served(from.chain),\n callTargets,\n spenders: pins.spenders,\n verifyQuote: (params, quote) => {\n const set = checkedAgainst.get(params);\n return zeroExVerifyQuote(params, quote, set ? {...verifyCtx, settlers: () => set} : verifyCtx);\n },\n verifyBuild: pins.verifyBuild!,\n reasonOf: pins.reasonOf!,\n ...(options.enabled ? {enabled: options.enabled} : {}),\n ...(options.fetchImpl ? {fetchImpl: options.fetchImpl} : {}),\n ...(options.headers ? {headers: options.headers} : {}),\n ...(options.timeoutMs !== undefined ? {timeoutMs: options.timeoutMs} : {}),\n ...(options.allowInsecureBaseUrl !== undefined ? {allowInsecureBaseUrl: options.allowInsecureBaseUrl} : {}),\n });\n return {\n ...inner,\n describeActivity: describeZeroExActivity,\n // The quoted gas limit is the backend's word: every call goes out with the account's own estimate.\n ownGasEstimate: true,\n settlerResolver: pins.resolver,\n // The backend's preflight is its own word: the device reads the registry first (a Settler paused, replaced or\n // removed while the user was on the review screen is refused here, nothing sent), then asks the backend.\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n await zeroExPreflightDeposit(quote, tx, {chains: pins.chains, resolver: pins.resolver});\n await inner.preflightDeposit!(quote, tx);\n },\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n if (params.dry !== false) return inner.getQuote(params, signal);\n const chainId = zeroExChainId(params.sourceChain);\n const ask = async (settlers: readonly string[]): Promise<Quote | null> => {\n checkedAgainst.set(params, settlers);\n const q = await inner.getQuote(params, signal);\n if (q) quoted.set(chainId, {settlers, untilMs: Math.min(Number.isFinite(q.validUntilMs) ? q.validUntilMs : 0, Date.now() + QUOTED_SET_MAX_MS)});\n return q;\n };\n const before = await pins.resolver.resolve(chainId);\n try {\n return await ask(before);\n } catch (e) {\n // A Settler the app has not seen: read the registry again and, only if it changed, ask once more.\n if (!(e instanceof Error) || !/is not a 0x Settler from the on-chain registry/.test(e.message)) throw e;\n const after = await pins.resolver.resolve(chainId, {fresh: true});\n if (after.length === before.length && after.every((s, i) => same(s, before[i]!))) throw e;\n return ask(after);\n }\n },\n };\n}\n\n/**\n * The 0x Settlers a signing policy should know as Permit2 spenders on `chainId`, labelled — the `knownSpenders` of\n * wallet-evm's `describeTypedData`, and the addresses a kit allowlist needs next to Permit2 and the token. Pass the\n * provider the app swaps through (`zeroExRemoteProvider` / `zeroExProvider`, or its `settlerResolver`): the set is the\n * one that resolver read from the registry, cached for its max age and read again after it. Empty when the registry\n * cannot be read: the permit is then described as a grant to an unknown spender, never silently trusted.\n *\n * ```ts\n * const zeroex = zeroExRemoteProvider({baseUrl, rpcUrls});\n * describeTypedData(typed, {chainId: 8453, account, knownSpenders: await zeroExKnownSpenders(zeroex, 8453)});\n * ```\n */\nexport async function zeroExKnownSpenders(source: SettlerResolver | {readonly settlerResolver: SettlerResolver}, chainId: number, label = \"0x Settler\"): Promise<Record<string, string>> {\n const resolver = \"settlerResolver\" in source ? source.settlerResolver : source;\n try {\n return Object.fromEntries((await resolver.resolve(chainId)).map((settler) => [settler, label]));\n } catch {\n return {};\n }\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {zeroExProvider, type ZeroExProviderConfig} from \"./provider.js\";\n\nexport interface ZeroExSwap2Config extends Swap2EngineConfig, ZeroExProviderConfig {}\n\n/** 0x as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class ZeroExSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: ZeroExSwap2Config) {\n super(account, config);\n this.provider = zeroExProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return this.provider.supportsChain?.(caip2) === true;\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AN,cAAkC,kCAAoB;AAAA,EACxC;AAAA,EACnB,YAAY,SAAmC,QAA2B;AACxE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,eAAe,MAAM;AAAA,EACvC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,KAAK,SAAS,gBAAgB,KAAK,MAAM;AAAA,EAClD;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,cAAc,WAAW,KAAK,eAAe,SAAS;AAAA,EAC/D;AACF;","names":["import_util","import_util","ADDRESS","ZERO_ADDRESS","chain","import_viem","import_errors","import_util","chain","ADDRESS","same","refuse","chain","import_viem","import_errors","import_util","import_validate","ADDRESS","same","uint","chain"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/chains.ts","../src/settler.ts","../src/rpc.ts","../src/provider.ts","../src/activity.ts","../src/remote.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./chains.js\";\nexport * from \"./settler.js\";\nexport * from \"./provider.js\";\nexport * from \"./remote.js\";\nexport {ZeroExSwap2Protocol} from \"./protocol.js\";\nexport {ZeroExSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type {ZeroExSwap2Config} from \"./protocol.js\";\n","/**\n * Where 0x settles, per chain. Everything a swap is held to on the device starts from this table:\n * the Settler registry (read on-chain for the Settler in force), canonical Permit2, and the wrapped\n * native token (wrap/unwrap pairs are not 0x swaps and are left to the wrap provider).\n *\n * The table is config: `zeroExChains(config.chains)` merges an integrator's entries over these.\n */\nimport {PERMIT2_ADDRESS} from \"@anywalletkit/protocol-swap2-core/util\";\n\n/** Canonical Permit2 — the only allowance target and the only EIP-712 verifying contract this module accepts. */\nexport const ZEROEX_PERMIT2 = PERMIT2_ADDRESS;\n/**\n * The 0x Settler deployer/registry (ERC-721: `ownerOf(feature)` is the Settler in force for that feature,\n * `prev(feature)` the instance it replaced). Same address on every chain 0x deploys to.\n */\nexport const ZEROEX_SETTLER_REGISTRY = \"0x00000000000004533Fe15556B1E086BB1A72cEae\";\n/** Registry feature 2: taker-submitted Settlers — the ones a Permit2 quote is sent to by the taker itself. */\nexport const ZEROEX_TAKER_FEATURE = 2;\n/** How the 0x API (and Settler's slippage check) names the chain's native coin. */\nexport const ZEROEX_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\n/** 0x's AllowanceHolder (the flow the docs recommend today). Not used by this module; pinned so it can be told apart. */\nexport const ZEROEX_ALLOWANCE_HOLDER = \"0x0000000000001fF3684f28c67538d4D072C22734\";\n\nexport interface ZeroExChain {\n /** Display name. */\n name: string;\n /** The Settler registry on this chain. */\n registry: string;\n /**\n * The taker Settler deployment (the registry's taker-feature nonce, see `zeroExSettlerAddress`) the registry named as\n * the one in force when the table was pinned. A native-coin sale is sent only to this deployment or to\n * {@link previousLiveNonce}: its value goes straight to the Settler's address, so that address must be a Settler that\n * was live then. A token sale (Permit2) may also go to the next {@link ZEROEX_SETTLER_NONCE_MARGIN} deployments once\n * they hold code. Anything newer is refused, clearly, until the pin is raised — the watch job reports every new\n * deployment (`ownerOf(2)` per chain in watch.json, `verify:live` on the canary). 1…{@link ZEROEX_SETTLER_MAX_NONCE}.\n */\n newestLiveNonce: number;\n /**\n * The deployment the registry named as the previous one (`prev(2)`) when the table was pinned: the oldest accepted.\n * An older Settler — a replaced one, whose code predates what the checks rely on — is refused as the one in force\n * and dropped as the previous one. 1…{@link newestLiveNonce} (equal to it on a chain with a single deployment).\n */\n previousLiveNonce: number;\n /** Wrapped native token; native ↔ wrapped pairs are refused up front (0x answers them with a call to this token, not a Settler). */\n wrappedNative?: string;\n /**\n * The most gas a 0x swap on this chain may be given (the padded limit: 0x's `transaction.gas` × 1.2 + 20,000), for a\n * chain where Settler swaps need more than the cap every other chain keeps (`ZEROEX_MAX_GAS_LIMIT`, 6,000,000). A\n * bigint, 1…{@link ZEROEX_GAS_CAP_CEILING}; absent: that default. In the default table only Monad sets one (15,000,000).\n */\n maxGasLimit?: bigint;\n}\n\n/**\n * The highest gas cap a chain table entry may set ({@link ZeroExChain.maxGasLimit}): Monad's per-transaction gas limit,\n * 30,000,000. Config can raise a chain's cap up to it, never remove the bound.\n */\nexport const ZEROEX_GAS_CAP_CEILING = 30_000_000n;\n/** Whether `v` is a gas cap a chain table entry may set: a bigint from 1 to {@link ZEROEX_GAS_CAP_CEILING}. */\nexport const isZeroExGasCap = (v: unknown): v is bigint => typeof v === \"bigint\" && v >= 1n && v <= ZEROEX_GAS_CAP_CEILING;\n\n/**\n * Deployments of the taker feature a token sale (Permit2) may use past {@link ZeroExChain.newestLiveNonce}: room for\n * 0x's next Settlers (about one a month per chain) before the pin must be raised. Within it the device relies on the\n * code check (a deployment that does not exist yet has no code) and on its RPC answering that check truthfully; a token\n * sale's permit can be spent only with the account itself as the caller, so a wrong answer costs nothing. Native-coin\n * sales get no margin: their value would be sent to the address as it is.\n */\nexport const ZEROEX_SETTLER_NONCE_MARGIN = 2;\n/** The highest {@link ZeroExChain.newestLiveNonce} a chain table may pin. */\nexport const ZEROEX_SETTLER_MAX_NONCE = 1024;\n\nconst chain = (name: string, wrappedNative: string, newestLiveNonce: number, previousLiveNonce: number, maxGasLimit?: bigint): ZeroExChain =>\n Object.freeze({name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative, ...(maxGasLimit !== undefined ? {maxGasLimit} : {})});\n\n/**\n * The default chain table (EVM chain id → entry). The two numbers are the taker Settler deployments the registry named\n * as current and previous when pinned (2026-11-25, after 0x's 2026-11-24 Settler release; `pnpm verify:live`: both\n * have code). Monad (143) joined in 0.2.0 from the same reads: deployment 12, made on 2026-11-24, and 11; its wrapped\n * native is WMON, the one 0x names as `wnative` there. Monad is also the one chain with a gas cap of its own,\n * 15,000,000 (every other chain keeps `ZEROEX_MAX_GAS_LIMIT`, 6,000,000): its gas grows with the size of the sale, 0x\n * splitting a large one across many pools (about 1.6 times Base's on a $25 swap, 6,140,730 for 1,000,000 MON → AUSD on\n * 2026-11-26), so under one 6,000,000 cap 0x sales of MON from about $10,000 were refused (README). The engine\n * never sends the quoted limit, so the cap only decides which quotes are refused.\n */\nexport const ZEROEX_CHAINS: Readonly<Record<number, ZeroExChain>> = Object.freeze({\n 1: chain(\"Ethereum\", \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\", 22, 21),\n 10: chain(\"Optimism\", \"0x4200000000000000000000000000000000000006\", 22, 21),\n 56: chain(\"BNB Smart Chain\", \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\", 24, 23),\n 137: chain(\"Polygon\", \"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270\", 21, 20),\n 143: chain(\"Monad\", \"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A\", 12, 11, 15_000_000n),\n 8453: chain(\"Base\", \"0x4200000000000000000000000000000000000006\", 23, 22),\n 42161: chain(\"Arbitrum\", \"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1\", 21, 20),\n 43114: chain(\"Avalanche\", \"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7\", 21, 20),\n});\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS = /^0x0{40}$/;\n\n/**\n * The chain table in force: the defaults with `overrides` merged over them (an entry replaces the default for that\n * chain id, `null` removes the chain). An entry whose registry or wrapped native is not an address, whose pins are\n * missing or out of order (`newestLiveNonce` 1…{@link ZEROEX_SETTLER_MAX_NONCE}, `previousLiveNonce` 1…newestLiveNonce),\n * or whose gas cap is given but is not a bigint from 1 to {@link ZEROEX_GAS_CAP_CEILING} (`maxGasLimit`), throws — a\n * typo here would move the root of every check. An entry replaces the default whole: one without `maxGasLimit` has the\n * default cap, Monad's included.\n */\nexport function zeroExChains(overrides?: Readonly<Record<number, ZeroExChain | null>>): Readonly<Record<number, ZeroExChain>> {\n if (!overrides) return ZEROEX_CHAINS;\n const out: Record<number, ZeroExChain> = {...ZEROEX_CHAINS};\n for (const key of Object.keys(overrides)) {\n const id = Number(key);\n if (!Number.isSafeInteger(id) || id <= 0) throw new Error(`zeroex: chain id ${key.slice(0, 20)} is not a positive integer`);\n const entry = overrides[id];\n if (entry === null || entry === undefined) {\n delete out[id];\n continue;\n }\n if (typeof entry.name !== \"string\" || !entry.name) throw new Error(`zeroex: chain ${id} has no name`);\n if (typeof entry.registry !== \"string\" || !ADDRESS.test(entry.registry) || ZERO_ADDRESS.test(entry.registry)) throw new Error(`zeroex: chain ${id} names no Settler registry address`);\n if (entry.wrappedNative !== undefined && (typeof entry.wrappedNative !== \"string\" || !ADDRESS.test(entry.wrappedNative))) throw new Error(`zeroex: chain ${id} wrapped native is not an address`);\n const newest = entry.newestLiveNonce;\n const previous = entry.previousLiveNonce;\n if (!Number.isSafeInteger(newest) || newest < 1 || newest > ZEROEX_SETTLER_MAX_NONCE) {\n throw new Error(`zeroex: chain ${id} pins no newest live Settler deployment (newestLiveNonce, 1 to ${ZEROEX_SETTLER_MAX_NONCE})`);\n }\n if (!Number.isSafeInteger(previous) || previous < 1 || previous > newest) {\n throw new Error(`zeroex: chain ${id} pins no previous live Settler deployment (previousLiveNonce, 1 to its newestLiveNonce)`);\n }\n const gasCap = entry.maxGasLimit;\n if (gasCap !== undefined && !isZeroExGasCap(gasCap)) throw new Error(`zeroex: chain ${id} gas cap (maxGasLimit) is not a bigint from 1 to ${ZEROEX_GAS_CAP_CEILING}`);\n out[id] = Object.freeze({\n name: entry.name, registry: entry.registry, newestLiveNonce: newest, previousLiveNonce: previous,\n ...(entry.wrappedNative ? {wrappedNative: entry.wrappedNative} : {}), ...(gasCap !== undefined ? {maxGasLimit: gasCap} : {}),\n });\n }\n return Object.freeze(out);\n}\n\n/** The EVM chain id of a CAIP-2 `eip155:<id>` string, or `NaN`. */\nexport function zeroExChainId(caip2: string): number {\n return typeof caip2 === \"string\" && /^eip155:[1-9][0-9]{0,15}$/.test(caip2) ? Number(caip2.slice(7)) : NaN;\n}\n\n/** Own-property lookup (a chain id like `constructor` must not resolve to anything). */\nexport function zeroExChain(chains: Readonly<Record<number, ZeroExChain>>, chainId: number): ZeroExChain | undefined {\n return Number.isSafeInteger(chainId) && Object.prototype.hasOwnProperty.call(chains, chainId) ? chains[chainId] : undefined;\n}\n","/**\n * The device-side checks of a 0x Permit2 swap. Nothing here trusts the API.\n *\n * - {@link createSettlerResolver}: the Settler in force is read from the pinned on-chain registry\n * (`ownerOf(2)`, and `prev(2)` for 0x's dwell time after a new deployment) — never taken from a\n * quote — and held to a CREATE3 deployment of that registry between the chain's pinned previous\n * deployment and its newest plus the margin, with code. A paused or removed feature reverts there\n * and the swap is refused.\n * - {@link decodeSettlerExecute}: a word-level reader of `Settler.execute(slippage, actions, zid)`.\n * - {@link checkZeroExTransaction}: the transaction a quote carries, held to the request — target\n * (and, for a native-coin sale, a Settler live when the chain table was pinned), value, chain,\n * method, the recipient / buy token / minimum of Settler's own slippage check, and, for a token\n * sale, the Permit2 payload (rebuilt locally by the core reader) and the first action that\n * spends it.\n *\n * Why the slippage tuple is the anchor: `execute` ends in Settler's `_checkSlippageAndTransfer`,\n * which sends the Settler's whole balance of `buyToken` to `recipient` and reverts below\n * `minAmountOut`. With the target a registry Settler, that tuple and the signed amount fixed, the\n * worst a hostile route can do is revert: the account pays at most the signed input and receives at\n * least the minimum. What the actions between do (which pools, in what order) is not checked.\n *\n * Why the first action is always checked: Settler runs a Permit2-spending action (`TRANSFER_FROM`,\n * every `*_VIP`) only at index 0, and Permit2 pulls from the caller. A token sale's action 0 must\n * therefore spend exactly the permit about to be signed, and a native-coin sale's action 0 must be\n * `NATIVE_CHECK` — otherwise an earlier, unspent permit of this account (one whose swap reverted)\n * could be spent inside a swap that looks like a plain native sale.\n *\n * Every refusal carries a `Swap2RefusalReason` (CS-13); a request this side cannot hold a\n * transaction to (no chain, recipient, tokens or amounts) is the caller's error and stays unclassified.\n */\nimport {getAddress, getContractAddress, numberToHex, pad} from \"viem\";\nimport {refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {readPermit2Transfer, type Permit2Transfer} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ZEROEX_CHAINS, ZEROEX_GAS_CAP_CEILING, ZEROEX_NATIVE, ZEROEX_PERMIT2, ZEROEX_SETTLER_MAX_NONCE, ZEROEX_SETTLER_NONCE_MARGIN, ZEROEX_SETTLER_REGISTRY, ZEROEX_TAKER_FEATURE, isZeroExGasCap, zeroExChain, type ZeroExChain} from \"./chains.js\";\nimport {isRevert, rpcRequest, rpcUrlsFor, type RpcUrls} from \"./rpc.js\";\n\n/** `execute((address recipient, address buyToken, uint256 minAmountOut), bytes[] actions, bytes32 zidAndAffiliate)`. */\nexport const SETTLER_EXECUTE_SELECTOR = \"0x1fff991f\";\n/** `ownerOf(uint256)` on the registry: the Settler in force for a feature. */\nexport const REGISTRY_OWNER_OF_SELECTOR = \"0x6352211e\";\n/** `prev(uint128)` on the registry: the instance the current one replaced. */\nexport const REGISTRY_PREV_SELECTOR = \"0xe2603dc2\";\n/** `NATIVE_CHECK(uint256 deadline, uint256 msgValue)`: the action every native-coin sale opens with (no Permit2 involved). */\nexport const SETTLER_NATIVE_CHECK_SELECTOR = \"0xbd01c226\";\n/**\n * The longest a 0x permit may stay valid from now. 0x signs five minutes ahead; the core reader allows an hour for any\n * provider. A shorter window leaves less time for a permit that was published but not spent (its swap reverted).\n */\nexport const ZEROEX_MAX_PERMIT_SECONDS = 600;\n/**\n * The longest a native-coin sale's quote may stay valid from now. A token sale's quote is bounded by its permit's\n * deadline; a native sale signs nothing, so its quote is bounded here instead: the transaction goes out within this\n * window of the registry read it was checked against, or not at all.\n */\nexport const ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;\n\n/** How far inside {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS} a backend ends a native sale's quote, so an app whose clock runs behind the backend's still accepts it. */\nexport const ZEROEX_NATIVE_QUOTE_SKEW_SECONDS = 30;\n\nconst PERMIT = \"((address,uint256),uint256,uint256)\";\n/**\n * Settler actions through which a taker-submitted swap spends a Permit2 signature (`ISettlerActions.sol`), by\n * selector. Every one starts `(address recipient, PermitTransferFrom permit, …)`, so the permit sits in argument\n * words 1–4 (token, amount, nonce, deadline); `sigWord` is the head word holding the offset of `bytes sig`.\n * `RFQ_VIP` (a maker-signed order) is left out on purpose: a quote that opens with it is refused.\n */\nexport const SETTLER_PERMIT_ACTIONS: Readonly<Record<string, {name: string; signature: string; sigWord: number}>> = Object.freeze({\n \"0xc1fb425e\": Object.freeze({name: \"TRANSFER_FROM\", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5}),\n \"0x3036d6a6\": Object.freeze({name: \"UNISWAPV3_VIP\", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6}),\n \"0x6a92dacb\": Object.freeze({name: \"UNISWAPV4_VIP\", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x441d2492\": Object.freeze({name: \"PANCAKE_INFINITY_VIP\", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x4150c86c\": Object.freeze({name: \"BALANCERV3_VIP\", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x10cd6343\": Object.freeze({name: \"EKUBOV3_VIP\", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x0bcce50f\": Object.freeze({name: \"CURVE_TRICRYPTO_VIP\", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6}),\n});\n\n/** A refusal from one of the checks in this file. The message is safe to show and starts `zeroex: `; `reason` classifies it (CS-13). */\nexport class ZeroExTransactionError extends Error {\n declare readonly reason?: Swap2RefusalReason;\n constructor(why: string, reason?: Swap2RefusalReason) {\n super(`zeroex: ${why}`);\n this.name = \"ZeroExTransactionError\";\n if (reason) withReason(this, reason);\n }\n}\nconst refuse = (why: string, reason?: Swap2RefusalReason) => new ZeroExTransactionError(why, reason);\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS = /^0x0{40}$/;\nconst same = (a: string, b: string) => a.length === b.length && a.toLowerCase() === b.toLowerCase();\n/** The native coin, as the engine (zero address) or 0x (the `0xEeee…` sentinel) names it. */\nexport const isZeroExNative = (token: string): boolean => ZERO_ADDRESS.test(token) || same(token, ZEROEX_NATIVE);\n\n// ── which addresses are 0x Settlers at all ──────────────────────────────────\n\n/**\n * keccak256 of the CREATE3 shim (PUSH0 variant) through which the registry deploys every Settler: the registry\n * CREATE2s the shim with salt `feature << 128 | chainId << 64 | nonce`, and the shim CREATEs the Settler (nonce 1).\n */\nexport const ZEROEX_SETTLER_SHIM_INIT_HASH = \"0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f\";\n/**\n * How far past the newest deployment a chain accepts ({@link ZeroExChain.newestLiveNonce} plus the margin) the resolver\n * still derives, only to tell \"0x deployed a newer Settler than this module accepts\" (refused until the pin is raised)\n * from \"not a 0x Settler at all\".\n */\nexport const ZEROEX_SETTLER_LOOKAHEAD = 16;\n\n/** The newest deployment a token sale may use on a chain: the newest one live when pinned, plus the margin. */\nconst tokenCeiling = (chain: ZeroExChain): number => chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;\n\n/** The address the registry deploys taker-feature Settler number `nonce` to on `chainId` — computed, no network. */\nexport function zeroExSettlerAddress(chainId: number, nonce: number, registry: string = ZEROEX_SETTLER_REGISTRY): string {\n if (!Number.isSafeInteger(chainId) || chainId <= 0 || !Number.isSafeInteger(nonce) || nonce <= 0) throw new Error(\"zeroex: a Settler address needs a positive chain id and nonce\");\n const salt = pad(numberToHex((BigInt(ZEROEX_TAKER_FEATURE) << 128n) | (BigInt(chainId) << 64n) | BigInt(nonce)), {size: 32});\n const shim = getContractAddress({opcode: \"CREATE2\", from: registry as `0x${string}`, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH});\n return getContractAddress({opcode: \"CREATE\", from: shim, nonce: 1n});\n}\n\nconst derived = new Map<string, string[]>();\n/**\n * Which deployment of the registry's taker feature `address` is on `chainId` (its nonce), or null when it is none of\n * deployments 1…`maxNonce` — by default the newest one the default table accepts on the chain\n * ({@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}; a chain outside the table has none:\n * null). An RPC (or an API) can therefore only ever name a contract 0x's own registry deployed as a Settler — never an\n * arbitrary contract or account. Bounded by the pin, an address that is no Settler costs a few dozen derivations, not\n * a thousand. Memoized per chain.\n */\nexport function zeroExSettlerNonce(chainId: number, address: string, registry: string = ZEROEX_SETTLER_REGISTRY, maxNonce?: number): number | null {\n if (typeof address !== \"string\" || !ADDRESS.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS.test(registry)) return null;\n const pinned = zeroExChain(ZEROEX_CHAINS, chainId);\n const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);\n if (!Number.isSafeInteger(bound) || bound < 1) return null;\n const key = `${registry.toLowerCase()}:${chainId}`;\n let list = derived.get(key);\n if (!list) derived.set(key, (list = []));\n const want = address.toLowerCase();\n const hit = list.indexOf(want);\n if (hit >= 0) return hit < bound ? hit + 1 : null;\n while (list.length < bound) {\n const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();\n list.push(next);\n if (next === want) return list.length;\n }\n return null;\n}\n\n// ── the Settler in force ────────────────────────────────────────────────────\n\nexport interface SettlerResolverConfig {\n /** The chain table (registry per chain). */\n chains: Readonly<Record<number, ZeroExChain>>;\n /** JSON-RPC endpoints per EVM chain id. Without one for a chain, its Settler cannot be resolved and live quotes are refused. */\n rpcUrls?: RpcUrls | undefined;\n /** How long a registry read is reused, ms. Default 5 minutes; a miss always triggers a fresh read. */\n maxAgeMs?: number | undefined;\n /** Clock (tests). */\n now?: (() => number) | undefined;\n}\n\nexport interface SettlerResolver {\n /** The Settlers a swap on `chainId` may call: the one in force, then the one it replaced (if any). Throws when the registry cannot be read or the feature is paused. */\n resolve(chainId: number, options?: {fresh?: boolean}): Promise<readonly string[]>;\n /** The last resolved set while it is still fresh; empty otherwise. Never touches the network. */\n known(chainId: number): readonly string[];\n}\n\nconst DEFAULT_SETTLER_MAX_AGE_MS = 5 * 60_000;\n\n/** One 32-byte word that is an address (upper 12 bytes zero), as a checksummed address; null for anything else, the zero address included. */\nfunction addressWord(result: unknown): string | null {\n if (typeof result !== \"string\" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;\n const address = `0x${result.slice(26)}`;\n return ZERO_ADDRESS.test(address) ? null : getAddress(address);\n}\n\n/**\n * Reads the Settler in force from the registry and caches it per chain. The registry address comes from the chain\n * table; the answer comes from the integrator's own RPC — that RPC is what this module trusts for \"which contract\n * is 0x's Settler right now\", within hard bounds it cannot move: the answer must be a CREATE3 deployment of that\n * registry, no older than the chain's pinned {@link ZeroExChain.previousLiveNonce} and no newer than its\n * {@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}, with code at the address (read through\n * the same RPC). Which of these a native-coin sale may use is narrower still ({@link checkZeroExTransaction}).\n */\nexport function createSettlerResolver(config: SettlerResolverConfig): SettlerResolver {\n const maxAge = config.maxAgeMs !== undefined && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;\n const now = config.now ?? Date.now;\n const cache = new Map<number, {at: number; settlers: readonly string[]}>();\n const flights = new Map<number, Promise<readonly string[]>>();\n\n /** eth_call on the registry. `{reverted: true}` when the node says the call reverted; throws when nothing answered. */\n async function call(chainId: number, to: string, data: string): Promise<{result: string} | {reverted: true}> {\n if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} — the 0x Settler cannot be resolved`, \"policy_refused\");\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_call\", [{to, data}, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler cannot be resolved`, \"upstream_unavailable\");\n // An execution revert is an answer (the feature is paused / has no instance); any other error is the endpoint failing.\n if (\"error\" in answer) {\n if (isRevert(answer.error)) return {reverted: true};\n throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n }\n if (typeof answer.result !== \"string\") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n return {result: answer.result};\n }\n\n /** Addresses already seen holding code (per chain): a deployed Settler's code does not go away, so it is read once. */\n const withCode = new Set<string>();\n /** Whether `address` holds contract code, read over the same RPC as the registry. Throws when nothing answered. */\n async function hasCode(chainId: number, address: string): Promise<boolean> {\n const key = `${chainId}:${address.toLowerCase()}`;\n if (withCode.has(key)) return true;\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_getCode\", [address, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler's code cannot be read`, \"upstream_unavailable\");\n if (\"error\" in answer || typeof answer.result !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(answer.result)) throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler's code`, \"upstream_unavailable\");\n if (answer.result.length <= 2) return false;\n withCode.add(key);\n return true;\n }\n\n async function read(chainId: number): Promise<readonly string[]> {\n const entry = zeroExChain(config.chains, chainId);\n if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, \"0\");\n const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);\n if (\"reverted\" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, \"chain_halted\");\n const settler = addressWord(current.result);\n if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, \"vault_mismatch\");\n // The answer comes from one RPC: it must be a deployment the registry itself made, inside the window this module\n // pins for the chain, and a contract. A newer deployment is 0x moving on: refused, with what to do, until the pin\n // is raised (the watch job reports it the day it happens). An older one is a replaced Settler: refused.\n const oldest = entry.previousLiveNonce;\n const ceiling = tokenCeiling(entry);\n const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);\n if (nonce === null) {\n const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);\n if (newer !== null) {\n throw refuse(`the 0x registry on chain ${chainId} names Settler deployment ${newer} (${settler}), newer than the newest this module accepts there (${ceiling}) — update @anywalletkit/protocol-swap2-0x, or raise the chain's newestLiveNonce and previousLiveNonce once that deployment is checked`, \"vault_mismatch\");\n }\n throw refuse(`the RPC on chain ${chainId} names ${settler} as the 0x Settler, which is not an address the 0x registry deploys Settlers to`, \"vault_mismatch\");\n }\n if (nonce < oldest) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, older than the oldest this module accepts there (${oldest}) — a replaced Settler is not called`, \"vault_mismatch\");\n // A deployment that does not exist yet (inside the margin past the newest live one) has no code: value or tokens\n // sent there would be stranded until 0x deploys it.\n if (!(await hasCode(chainId, settler))) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, but no contract is deployed there`, \"vault_mismatch\");\n const settlers = [settler];\n // The instance it replaced: 0x keeps quoting it for a while after a new deployment. No previous instance reverts;\n // one outside the pinned window, or without code, is left out.\n try {\n const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);\n const prev = \"result\" in previous ? addressWord(previous.result) : null;\n const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;\n if (prev && prevNonce !== null && prevNonce >= oldest && (await hasCode(chainId, prev))) settlers.push(prev);\n } catch {\n // The current Settler alone is a valid (stricter) answer.\n }\n return Object.freeze(settlers);\n }\n\n return {\n async resolve(chainId, options) {\n const hit = cache.get(chainId);\n if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;\n const running = flights.get(chainId);\n if (running) return running;\n const flight = read(chainId).then((settlers) => {\n cache.set(chainId, {at: now(), settlers});\n return settlers;\n }).finally(() => {\n flights.delete(chainId);\n });\n flights.set(chainId, flight);\n return flight;\n },\n known(chainId) {\n const hit = cache.get(chainId);\n return hit && now() - hit.at <= maxAge ? hit.settlers : [];\n },\n };\n}\n\n// ── Settler.execute calldata ────────────────────────────────────────────────\n\nexport interface SettlerAction {\n /** 4-byte action selector, lowercase. */\n selector: string;\n /** Byte offset, inside the `execute` arguments, of the action's first argument word. */\n argsStart: number;\n /** The action's declared byte length (selector included). The first action of a Permit2 quote declares more than is there: its signature is appended later. */\n declaredLength: number;\n}\n\nexport interface SettlerExecute {\n /** Who Settler's slippage check pays. */\n recipient: string;\n /** The token that check measures (`0xEeee…` for the native coin). */\n buyToken: string;\n /** The least `recipient` receives, or the call reverts. */\n minAmountOut: bigint;\n /** 0x's trade id and affiliate tag (not checked). */\n zidAndAffiliate: string;\n actions: readonly SettlerAction[];\n /** Bytes of arguments after the 4-byte method selector. */\n bodyLength: number;\n /** The argument word at byte `offset`, as 64 hex characters; throws when it is out of range. */\n word(offset: number): string;\n}\n\nconst MAX_CALLDATA_BYTES = 65_536;\nconst MAX_ACTIONS = 256;\nconst ACTIONS_OFFSET = 0xa0;\n\n/**\n * Read `Settler.execute(slippage, actions, zidAndAffiliate)` calldata. Strict where it matters (method, the static\n * slippage tuple, the canonical position of the action array, every action inside the data) and tolerant where\n * Settler is: the data need not be a multiple of 32 bytes, and the first action may declare a length that runs past\n * the end (0x leaves room for the Permit2 signature there).\n */\nexport function decodeSettlerExecute(data: string): SettlerExecute {\n if (typeof data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse(\"the transaction data is not hex bytes\", \"policy_refused\");\n if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse(\"the transaction data is larger than any 0x swap\", \"policy_refused\");\n if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse(\"the transaction does not call Settler.execute\", \"policy_refused\");\n const body = data.slice(10).toLowerCase();\n const bodyLength = body.length / 2;\n const word = (offset: number): string => {\n if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse(\"the Settler call is cut short\", \"policy_refused\");\n return body.slice(offset * 2, offset * 2 + 64);\n };\n const address = (offset: number, what: string): string => {\n const w = word(offset);\n if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, \"policy_refused\");\n return getAddress(`0x${w.slice(24)}`);\n };\n /** A word that must be a small non-negative integer (an offset, a length, a count). */\n const small = (offset: number, what: string): number => {\n const w = word(offset);\n if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, \"policy_refused\");\n return parseInt(w.slice(56), 16);\n };\n\n const recipient = address(0x00, \"recipient\");\n const buyToken = address(0x20, \"buy token\");\n const minAmountOut = BigInt(`0x${word(0x40)}`);\n if (small(0x60, \"action array offset\") !== ACTIONS_OFFSET) throw refuse(\"the Settler call does not place its actions where the ABI does\", \"policy_refused\");\n const zidAndAffiliate = `0x${word(0x80)}`;\n const count = small(ACTIONS_OFFSET, \"action count\");\n if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, \"policy_refused\");\n const table = ACTIONS_OFFSET + 32;\n const actions: SettlerAction[] = [];\n for (let i = 0; i < count; i++) {\n const offset = small(table + 32 * i, \"action offset\");\n const at = table + offset;\n // Past the offset table, with room for the length word and a selector.\n if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, \"policy_refused\");\n const declaredLength = small(at, \"action length\");\n if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, \"policy_refused\");\n if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, \"policy_refused\");\n actions.push(Object.freeze({selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength}));\n }\n return Object.freeze({recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word});\n}\n\n// ── the transaction, held to the request ────────────────────────────────────\n\n/** What the user asked for — the only source of truth for the checks. */\nexport interface ZeroExExpectation {\n /** EVM chain id of the swap. */\n chainId: number;\n /**\n * The chain's entry in the table in force: its pins bound the target (a token sale: `previousLiveNonce` up to\n * `newestLiveNonce` plus the margin; a native-coin sale: exactly `newestLiveNonce` or `previousLiveNonce`). Default:\n * the default table's entry for `chainId`.\n */\n chain?: ZeroExChain | undefined;\n /** Settlers resolved from the registry for that chain ({@link SettlerResolver.resolve}). */\n settlers: readonly string[];\n /** The token sold: an ERC-20 address, or the zero address / `0xEeee…` for the native coin. */\n sellToken: string;\n /** The token bought, same convention. */\n buyToken: string;\n /** Exactly the input, base units. */\n sellAmount: bigint;\n /** Who must receive the output (the user's own address unless they named another). */\n recipient: string;\n /** The least the recipient must receive — the quote's minimum, already held to the requested slippage by the caller. */\n minBuyAmount: bigint;\n /** Clock for the Permit2 deadline (tests). */\n nowMs?: number;\n}\n\n/** The transaction fields the checks read (a quote's `txRequest` or a built `UnsignedTx`). */\nexport interface ZeroExTransaction {\n to?: string | undefined;\n data?: string | undefined;\n value?: string | undefined;\n chainId?: number | undefined;\n approvalAddress?: string | undefined;\n permit2Transfer?: string | undefined;\n gasLimit?: string | undefined;\n}\n\n/**\n * The most gas a 0x swap may be given on a chain whose table entry sets no cap of its own: the padded limit (0x's gas ×\n * 1.2 + 20,000). Unused gas is refunded, but a reverting route burns up to the limit, so a quote that asks for a block's\n * worth is refused. Settler swaps on the first seven chains sit well under 2 million, and they keep this cap. Monad sets\n * its own ({@link ZeroExChain.maxGasLimit}: 15,000,000): its gas grows with the size of the sale, to millions on large\n * MON sales, and under this cap 0x sales of MON from about $10,000 were refused on 2026-11-26 (see the README). The\n * engine never sends the quoted limit (`ownGasEstimate`: the account's own estimate after a dry run), so a cap only\n * decides which quotes are refused.\n */\nexport const ZEROEX_MAX_GAS_LIMIT = 6_000_000n;\n\n/**\n * The gas cap of a chain table entry: its own `maxGasLimit`, else {@link ZEROEX_MAX_GAS_LIMIT}. An entry whose cap is\n * not a bigint from 1 to `ZEROEX_GAS_CAP_CEILING` (one built by hand rather than through `zeroExChains`) throws: a\n * chain table cannot remove the bound.\n */\nexport function zeroExMaxGasLimit(chain: ZeroExChain, chainId?: number): bigint {\n const cap: unknown = chain.maxGasLimit;\n if (cap === undefined) return ZEROEX_MAX_GAS_LIMIT;\n if (!isZeroExGasCap(cap)) throw refuse(`the chain table's gas cap${chainId !== undefined ? ` for chain ${chainId}` : \"\"} is not a bigint from 1 to ${ZEROEX_GAS_CAP_CEILING}`);\n return cap;\n}\n\n/**\n * Hold a transaction's gas limit, when it carries one, to the chain's cap ({@link zeroExMaxGasLimit}): decimal, above\n * zero, at most the cap. Throws {@link ZeroExTransactionError} (`policy_refused`) naming the chain and its cap.\n */\nexport function checkZeroExGasLimit(gasLimit: unknown, chain: ZeroExChain, chainId: number): void {\n const cap = zeroExMaxGasLimit(chain, chainId);\n if (gasLimit === undefined) return;\n if (typeof gasLimit !== \"string\" || !/^[0-9]{1,12}$/.test(gasLimit) || BigInt(gasLimit) === 0n || BigInt(gasLimit) > cap) {\n throw refuse(`the transaction asks for more gas than any 0x swap needs (its gas limit must be 1 to ${cap} on chain ${chainId})`, \"policy_refused\");\n }\n}\n\nexport interface ZeroExCheckedTransaction {\n execute: SettlerExecute;\n /** The locally rebuilt Permit2 payload of a token sale; absent for a native-coin sale. */\n permit2?: Permit2Transfer;\n /** Name of the Settler action that spends the Permit2 signature (token sales). */\n permitAction?: string;\n}\n\n/**\n * Hold a 0x transaction to the request, or throw {@link ZeroExTransactionError}. Checked:\n *\n * 1. `to` is one of the registry's Settlers, and a deployment inside the chain's pinned window\n * (`previousLiveNonce` … `newestLiveNonce` + {@link ZEROEX_SETTLER_NONCE_MARGIN}); `chainId`, when present, is the\n * swap's chain.\n * 2. `value` is the input for a native-coin sale and zero for a token sale; a sale that sends value goes only to the\n * chain's `newestLiveNonce` or `previousLiveNonce` deployment — Settlers that were live when the table was pinned —\n * never into the margin; a gas limit, when given, is at most the chain's cap ({@link zeroExMaxGasLimit}: its own\n * `maxGasLimit`, else {@link ZEROEX_MAX_GAS_LIMIT}).\n * 3. The method is `execute`, and its slippage tuple names the expected recipient, the requested buy token and\n * exactly the expected minimum (never zero).\n * 4. Token sale: the allowance target is canonical Permit2; the Permit2 payload passes the core reader (Permit2\n * domain on this chain, the sell token, exactly the input, this very Settler as spender) and is rebuilt locally,\n * with a deadline at most {@link ZEROEX_MAX_PERMIT_SECONDS} away; the first action is a known Permit2-spending\n * action carrying that same token, amount, nonce and deadline, and its signature slot points at the end of the\n * data, where the signature is appended.\n * 5. Native-coin sale: no allowance target, no Permit2 payload, and the first action is `NATIVE_CHECK` — the only\n * place Settler would spend a Permit2 signature holds none.\n *\n * Not checked: the actions after the first (the route), the first action's own `recipient` (where Permit2 sends the\n * input: the Settler or a pool) and `zidAndAffiliate`. Settler's slippage check bounds what they can do.\n */\nexport function checkZeroExTransaction(tx: ZeroExTransaction, expected: ZeroExExpectation): ZeroExCheckedTransaction {\n if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse(\"the swap names no EVM chain\");\n if (!ADDRESS.test(expected.recipient) || ZERO_ADDRESS.test(expected.recipient)) throw refuse(\"the swap names no recipient\");\n if (!ADDRESS.test(expected.sellToken) || !ADDRESS.test(expected.buyToken)) throw refuse(\"the swap names no sell or buy token\");\n if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse(\"the swap has no input or no minimum output\");\n const nativeSell = isZeroExNative(expected.sellToken);\n const nativeBuy = isZeroExNative(expected.buyToken);\n if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse(\"the swap sells and buys the same token\");\n\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to)) throw refuse(\"the transaction has no target\", \"policy_refused\");\n const to = tx.to;\n if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, \"upstream_unavailable\");\n if (!expected.settlers.some((s) => same(s, to))) throw refuse(`the transaction target ${to} is not a 0x Settler from the on-chain registry`, \"vault_mismatch\");\n if (tx.chainId !== undefined && tx.chainId !== expected.chainId) throw refuse(`the transaction is for chain ${String(tx.chainId).slice(0, 20)}, not ${expected.chainId}`, \"vault_mismatch\");\n // Whatever settler list the caller hands in, the target is held to the chain's pins: a deployment of the registry\n // between the previous one live at pin time and the newest one a token sale may use.\n const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);\n if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));\n if (deployment === null || deployment < pin.previousLiveNonce) throw refuse(`the transaction target ${to} is not a 0x Settler deployment this module accepts on chain ${expected.chainId}`, \"vault_mismatch\");\n if (typeof tx.value !== \"string\" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse(\"the transaction value is not a decimal amount\", \"policy_refused\");\n const value = BigInt(tx.value);\n if (value !== (nativeSell ? expected.sellAmount : 0n)) throw refuse(nativeSell ? \"the transaction value is not the amount being sold\" : \"the transaction sends native coin with a token sale\", \"price_check_failed\");\n // Value goes straight to the target: only to a Settler that was live when the table was pinned. A deployment inside\n // the margin may not exist yet (its code is the RPC's word) — what is sent there would be stranded, or swept by\n // whatever 0x deploys there later. Refused until the package (its pins) is updated.\n if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {\n throw refuse(deployment > pin.newestLiveNonce\n ? `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, newer than the newest one live when this module's chain table was pinned (${pin.newestLiveNonce}) — a native-coin sale goes only to a pinned Settler: update @anywalletkit/protocol-swap2-0x`\n : `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, which was not live when this module's chain table was pinned (${pin.newestLiveNonce} and ${pin.previousLiveNonce} were) — a native-coin sale goes only to a pinned Settler`, \"vault_mismatch\");\n }\n checkZeroExGasLimit(tx.gasLimit, pin, expected.chainId);\n if (typeof tx.data !== \"string\") throw refuse(\"the transaction has no data\", \"policy_refused\");\n\n const execute = decodeSettlerExecute(tx.data);\n if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, \"recipient_mismatch\");\n if (nativeBuy ? !same(execute.buyToken, ZEROEX_NATIVE) : !same(execute.buyToken, expected.buyToken)) throw refuse(`the swap delivers ${execute.buyToken}, not the token asked for`, \"price_check_failed\");\n if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, \"price_check_failed\");\n const first = execute.actions[0]!;\n\n if (nativeSell) {\n if (tx.approvalAddress !== undefined) throw refuse(\"a native-coin sale asks for a token allowance\", \"policy_refused\");\n if (tx.permit2Transfer !== undefined) throw refuse(\"a native-coin sale carries a Permit2 signature request\", \"policy_refused\");\n // Action 0 is where Settler would spend a Permit2 signature (any earlier, unspent permit of this account): a native\n // sale opens with NATIVE_CHECK and nothing else.\n if (first.selector !== SETTLER_NATIVE_CHECK_SELECTOR) throw refuse(`the swap's first action ${first.selector} is not the native-value check a native-coin sale opens with`, \"policy_refused\");\n return {execute};\n }\n\n if (typeof tx.approvalAddress !== \"string\" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse(\"the allowance target is not canonical Permit2\", \"vault_mismatch\");\n if (typeof tx.permit2Transfer !== \"string\") throw refuse(\"a token sale carries no Permit2 payload to sign\", \"policy_refused\");\n const nowMs = expected.nowMs ?? Date.now();\n let permit2: Permit2Transfer;\n try {\n permit2 = readPermit2Transfer(tx.permit2Transfer, {\n chainId: expected.chainId,\n token: expected.sellToken,\n amount: expected.sellAmount,\n spender: to,\n nowMs,\n });\n } catch (err) {\n throw refuse((err instanceof Error ? err.message : \"the Permit2 payload is refused\").replace(/^swap2: /, \"\"), refusalOf(err)?.reason ?? \"policy_refused\");\n }\n if (permit2.deadline > BigInt(Math.floor(nowMs / 1000) + ZEROEX_MAX_PERMIT_SECONDS)) throw refuse(`the Permit2 deadline is more than ${ZEROEX_MAX_PERMIT_SECONDS} s away`, \"policy_refused\");\n\n const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : undefined;\n if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, \"policy_refused\");\n const arg = (index: number) => execute.word(first.argsStart + 32 * index);\n // (address recipient, ((address token, uint256 amount), uint256 nonce, uint256 deadline), …): words 1–4.\n if (!/^0{24}/.test(arg(1)) || !same(`0x${arg(1).slice(24)}`, expected.sellToken)) throw refuse(`${action.name} pulls a token other than the one being sold`, \"policy_refused\");\n if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, \"policy_refused\");\n if (BigInt(`0x${arg(3)}`) !== permit2.nonce || BigInt(`0x${arg(4)}`) !== permit2.deadline) throw refuse(`${action.name} carries a different permit than the one to be signed`, \"policy_refused\");\n const sigOffset = arg(action.sigWord);\n if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {\n throw refuse(`${action.name} does not read its signature from the end of the data`, \"policy_refused\");\n }\n return {execute, permit2, permitAction: action.name};\n}\n","/**\n * Minimal JSON-RPC over the integrator's own endpoints (Hermes-safe: `timeoutSignal`, no AbortSignal.timeout).\n * The first endpoint that gives a JSON-RPC answer wins; an execution error is an answer, a transport failure is not.\n */\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\n\nexport type RpcUrls = Readonly<Record<number, readonly string[]>>;\nexport type RpcAnswer = {result: unknown} | {error: {code: unknown; message: string}};\n\nconst RPC_TIMEOUT_MS = 12_000;\n\n/** The endpoints configured for `chainId` (own property only). */\nexport function rpcUrlsFor(rpcUrls: RpcUrls | undefined, chainId: number): readonly string[] {\n if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];\n const urls = rpcUrls[chainId];\n return Array.isArray(urls) ? urls.filter((u): u is string => typeof u === \"string\" && u.length > 0) : [];\n}\n\n/** One request; null when no endpoint is configured or none answered. */\nexport async function rpcRequest(rpcUrls: RpcUrls | undefined, chainId: number, method: string, params: unknown[]): Promise<RpcAnswer | null> {\n for (const url of rpcUrlsFor(rpcUrls, chainId)) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}),\n signal: timeoutSignal(RPC_TIMEOUT_MS),\n });\n if (!res.ok) continue;\n const body = (await res.json()) as {result?: unknown; error?: {code?: unknown; message?: unknown} | null} | null;\n if (!body || typeof body !== \"object\") continue;\n if (body.error) return {error: {code: body.error.code, message: typeof body.error.message === \"string\" ? body.error.message : \"rpc error\"}};\n if (\"result\" in body) return {result: body.result ?? null};\n } catch {\n // next endpoint\n }\n }\n return null;\n}\n\n/** Whether a JSON-RPC error says the call itself reverted (as opposed to the endpoint failing). */\nexport function isRevert(error: {code: unknown; message: string}): boolean {\n return error.code === 3 || /revert/i.test(error.message);\n}\n","import {getAddress, hashTypedData} from \"viem\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\nimport {httpRefusal, refusal, refusalOf, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {anySignal, permit2TransferJson, readPermit2Transfer, sourceAssetOf, timeoutSignal, type Permit2Transfer} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {slippageFloor} from \"@anywalletkit/protocol-swap2-core/validate\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeZeroExActivity} from \"./activity.js\";\nimport {ZEROEX_NATIVE, ZEROEX_PERMIT2, zeroExChain, zeroExChainId, zeroExChains, type ZeroExChain} from \"./chains.js\";\nimport {rpcRequest, rpcUrlsFor, type RpcUrls} from \"./rpc.js\";\nimport {ZEROEX_MAX_NATIVE_QUOTE_SECONDS, ZEROEX_NATIVE_QUOTE_SKEW_SECONDS, checkZeroExGasLimit, checkZeroExTransaction, createSettlerResolver, isZeroExNative, type SettlerResolver, type ZeroExExpectation} from \"./settler.js\";\n\n/**\n * 0x Swap API v2 (docs.0x.org) as a same-chain swap2 provider, Permit2 flow: `/swap/permit2/price` for\n * indicative quotes, `/swap/permit2/quote` for the swap that is executed.\n *\n * The API needs a key on every request, so `zeroExProvider` with a key runs on your server only, and\n * `zeroExRemoteProvider` in the app: under React Native (Hermes or JSC) it refuses to be built with a\n * key at all — an app bundle keeps no secret, and React Native's fetch follows redirects with the key\n * header whatever `redirect` says. Whichever side quotes, nothing the API returns is signed as it\n * is: the Settler is read from the on-chain registry, the transaction is held to the request and the\n * Permit2 payload is rebuilt locally (see `settler.ts`); the engine then signs it as EIP-712 typed\n * data, appends the signature and estimates the signed call before broadcast. Every call goes out\n * with the account's own gas estimate (`ownGasEstimate`), never the quoted limit.\n *\n * Every refusal carries a `Swap2RefusalReason` next to its unchanged text (CS-13): HTTP 429 →\n * `rate_limited` (with Retry-After), 401/403 → `key_rejected`, 5xx or an unreachable / malformed\n * API → `upstream_unavailable`, no liquidity → `insufficient_liquidity`, a pair 0x does not serve →\n * `unsupported_pair`, a transaction or payload that fails the device's checks → `vault_mismatch` /\n * `recipient_mismatch` / `price_check_failed` / `policy_refused`. A malformed request is the\n * caller's own error and stays unclassified, and so does the caller's own abort.\n */\n\nexport const ZEROEX_PROVIDER = \"zeroex\";\nexport const ZEROEX_DEFAULT_BASE_URL = \"https://api.0x.org\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/**\n * A firm 0x quote is priced at one block; the Settler enforces the minimum, the engine re-checks this TTL before broadcast.\n * Two minutes so a mainnet approval (Ethereum: often past 45 s) still lands inside the quote; a token sale's TTL is cut to\n * the Permit2 deadline (quote + 300 s) − 20 s, a native sale's to 90 s.\n */\nconst DEFAULT_TTL_MS = 120_000;\nconst DEFAULT_TIMEOUT_MS = 10_000;\n/** The Permit2 deadline must outlive the quote by this much, so a signature is never made seconds before it lapses. */\nconst DEADLINE_MARGIN_MS = 20_000;\nconst MAX_RESPONSE_CHARS = 600_000;\n\nexport interface ZeroExProviderConfig {\n enabled?: boolean | undefined;\n /**\n * The 0x API key — server only. Best as a getter, read on every request, so the key lives where you keep secrets\n * (server env, a vault) and never in this config object; a string is accepted too (an env value read once). It is\n * sent only as the `0x-api-key` header to `baseUrl`; it is never put in a URL, a refusal, an error or a quote, and an\n * answer that came through a redirect is refused. Without a key (or with one that is not printable ASCII without\n * spaces) the provider serves no route. Under React Native a key is refused outright (the constructor throws): use\n * `zeroExRemoteProvider` in the app.\n */\n apiKey?: string | (() => string | undefined) | undefined;\n /** API origin. Default {@link ZEROEX_DEFAULT_BASE_URL}. Must be https (http only for localhost), or the key would travel in clear. */\n baseUrl?: string | undefined;\n /** Chain table entries merged over the defaults (EVM chain id → entry, `null` removes a chain). */\n chains?: Readonly<Record<number, ZeroExChain | null>> | undefined;\n /** JSON-RPC endpoints per EVM chain id: the Settler registry read (needed for every executable quote) and receipts. */\n rpcUrls?: RpcUrls | undefined;\n /** Slippage when the request names none, bps. Default 50. */\n defaultSlippageBps?: number | undefined;\n /** How long a quote is offered, ms. Default 120 s; never past the Permit2 deadline, and a native-coin sale's never past {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS}. */\n quoteTtlMs?: number | undefined;\n timeoutMs?: number | undefined;\n /** Liquidity sources 0x must not route through (its `excludedSources` names). */\n excludedSources?: readonly string[] | undefined;\n /** How long a Settler registry read is reused, ms. Default 5 minutes. */\n settlerMaxAgeMs?: number | undefined;\n /** Share a resolver (e.g. with `zeroExRemoteProvider`); built from `chains` / `rpcUrls` when absent. */\n settlerResolver?: SettlerResolver | undefined;\n}\n\n/** 0x error names (`{name, message, data}` bodies) as the refusal a wallet shows, and its reason. Anything else is reported by HTTP status. */\nconst API_ERRORS: Readonly<Record<string, readonly [string, Swap2RefusalReason]>> = Object.freeze({\n INPUT_INVALID: [\"0x rejected the request as invalid\", \"no_route\"],\n SWAP_VALIDATION_FAILED: [\"0x could not validate this swap\", \"no_route\"],\n TOKEN_NOT_SUPPORTED: [\"0x does not support one of these tokens\", \"unsupported_pair\"],\n RECIPIENT_NOT_SUPPORTED: [\"0x does not support a separate recipient for this swap\", \"unsupported_pair\"],\n USER_NOT_AUTHORIZED: [\"0x does not serve this account\", \"unsupported_pair\"],\n TAKER_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve this account\", \"unsupported_pair\"],\n RECIPIENT_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve this recipient\", \"unsupported_pair\"],\n BUY_TOKEN_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve the token being bought\", \"unsupported_pair\"],\n SELL_TOKEN_NOT_AUTHORIZED_FOR_TRADE: [\"0x does not serve the token being sold\", \"unsupported_pair\"],\n XSTOCKS_NOT_AUTHORIZED: [\"0x does not serve this token for this account\", \"unsupported_pair\"],\n INSUFFICIENT_ASSET_LIQUIDITY: [\"0x has too little liquidity for this pair and amount\", \"insufficient_liquidity\"],\n INTERNAL_SERVER_ERROR: [\"0x had an internal error\", \"upstream_unavailable\"],\n UNCATEGORIZED: [\"0x could not quote this swap\", \"no_route\"],\n});\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst plain = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\nconst own = (o: Record<string, unknown>, key: string): unknown => (Object.prototype.hasOwnProperty.call(o, key) ? o[key] : undefined);\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null);\nconst same = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^[0-9]{1,78}$/.test(a) && /^[0-9]{1,78}$/.test(b) && BigInt(a) === BigInt(b);\nconst isAddress = (v: unknown): v is string => typeof v === \"string\" && ADDRESS.test(v);\n/** How a fee token is named in a quote: `native` for the chain's coin, the checksummed address otherwise. */\nconst feeToken = (token: string): string => (isZeroExNative(token) ? \"native\" : getAddress(token));\n\n/** The key for one request: printable ASCII without spaces, or nothing. A throwing getter is \"no key\". */\nfunction readKey(source: ZeroExProviderConfig[\"apiKey\"]): string | undefined {\n let key: unknown = source;\n if (typeof source === \"function\") {\n try {\n key = source();\n } catch {\n return undefined;\n }\n }\n return typeof key === \"string\" && /^[\\x21-\\x7e]{1,200}$/.test(key) ? key : undefined;\n}\n\n/**\n * React Native (Hermes or JSC): an app bundle keeps no secret, and its fetch (OkHttp / NSURLSession) follows redirects\n * — carrying the key header along — whatever `redirect` says.\n */\nfunction onReactNative(): boolean {\n const g = globalThis as {HermesInternal?: unknown; navigator?: {product?: unknown}};\n return g.HermesInternal !== undefined || g.navigator?.product === \"ReactNative\";\n}\n\n/** `scheme://host[:port]` of a URL, lowercase; \"\" when it has none. No URL class: React Native's lacks `origin`. */\nconst originOf = (url: string): string => (/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i.exec(url)?.[0] ?? \"\").toLowerCase();\n\n/** The API origin, refused unless https (or http on this machine): the key rides on every request to it. */\nfunction apiOrigin(baseUrl: string | undefined): string {\n const url = (baseUrl ?? ZEROEX_DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n if (/^https:\\/\\/[^\\s/?#@]+(?:\\/[^\\s?#]*)?$/i.test(url)) return url;\n if (/^http:\\/\\/(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?(?:\\/[^\\s?#]*)?$/i.test(url)) return url;\n throw new Error(\"zeroex: baseUrl must be an https:// origin (http only for localhost) — the API key is sent to it\");\n}\n\ntype Fee = NonNullable<Quote[\"fees\"]>[number];\n\n/**\n * The fees of a 0x answer as quote fee entries, or the reason they cannot be read. Strict on purpose: a quote whose\n * fees do not parse is refused, never shown as free.\n *\n * - `zeroExFee` (0x's on-chain fee, taken out of the trade; `buyAmount` is already net of it) → `protocol`, included.\n * - `integratorFee` / `integratorFees` — this module asks for none, so anything above zero is refused.\n * - `gasFee` (only gasless trades carry one) → `network`, included.\n * - `totalNetworkFee` (wei the taker pays for gas; `gas × gasPrice` when 0x leaves it null) → `network`, not included.\n */\n/** The one fee refusal that is a policy (an integrator fee nobody asked for); every other one is a quote that cannot be read. */\nconst UNASKED_INTEGRATOR_FEE = \"the quote carries an integrator fee this wallet did not ask for\";\n\nexport function zeroExFees(response: Record<string, unknown>, gas: {gas: unknown; gasPrice: unknown}): {fees: Fee[]; networkFeeKnown: boolean} | string {\n const fees = own(response, \"fees\");\n if (!plain(fees)) return \"the quote's fees are missing\";\n if (!Object.prototype.hasOwnProperty.call(fees, \"zeroExFee\")) return \"the quote does not say what 0x charges\";\n const out: Fee[] = [];\n const amountAndToken = (v: unknown): {amount: bigint; token: string} | null => {\n if (!plain(v)) return null;\n const amount = uint(own(v, \"amount\"));\n const token = own(v, \"token\");\n return amount !== null && isAddress(token) ? {amount, token} : null;\n };\n\n const zeroEx = own(fees, \"zeroExFee\");\n if (zeroEx !== null) {\n const fee = amountAndToken(zeroEx);\n if (!fee) return \"the 0x fee cannot be read\";\n if (fee.amount > 0n) out.push({type: \"protocol\", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: \"0x fee (taken on-chain, already out of the quoted amount)\"});\n }\n\n const integrator = own(fees, \"integratorFee\");\n if (integrator !== null && integrator !== undefined) {\n const fee = amountAndToken(integrator);\n if (!fee) return \"the integrator fee cannot be read\";\n if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;\n }\n const integrators = own(fees, \"integratorFees\");\n if (integrators !== null && integrators !== undefined) {\n if (!Array.isArray(integrators) || integrators.length > 16) return \"the integrator fees cannot be read\";\n for (const entry of integrators) {\n const fee = amountAndToken(entry);\n if (!fee) return \"the integrator fees cannot be read\";\n if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;\n }\n }\n\n const gasFee = own(fees, \"gasFee\");\n if (gasFee !== null && gasFee !== undefined) {\n const fee = amountAndToken(gasFee);\n if (!fee) return \"the gas fee cannot be read\";\n if (fee.amount > 0n) out.push({type: \"network\", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: \"Gas charged by 0x inside the trade\"});\n }\n\n const total = own(response, \"totalNetworkFee\");\n let network: bigint | null = null;\n if (total !== null && total !== undefined) {\n network = uint(total);\n if (network === null) return \"the network fee cannot be read\";\n } else if (gas.gas !== null && gas.gas !== undefined && gas.gasPrice !== null && gas.gasPrice !== undefined) {\n const units = uint(gas.gas);\n const price = uint(gas.gasPrice);\n if (units === null || price === null) return \"the gas estimate cannot be read\";\n network = units * price;\n }\n if (network !== null) out.push({type: \"network\", amount: network.toString(), token: \"native\", included: false, description: \"Estimated network fee (gas × gas price, as 0x reports it)\"});\n return {fees: out, networkFeeKnown: network !== null};\n}\n\n/**\n * A quote's `gasEstimate`: 0x's own gas figure for the call — `transaction.gas` on a live quote, `gas` on an indicative\n * price — as canonical digits, read the way the gas limit and the network fee read it (decimal digits only). Undefined\n * when 0x states none, zero, a figure in another notation, or one past the contract's ten digits: no figure is made up.\n * 0x calls it the gas limit to send with; measured against the gas the call used, it runs high (see the README).\n */\nexport function zeroExGasEstimate(gas: unknown): string | undefined {\n const units = uint(gas);\n return units !== null && units > 0n && units < 10_000_000_000n ? units.toString() : undefined;\n}\n\n/** A tax in bps from `tokenMetadata`: a number or a decimal string; null when the API does not know it. */\nfunction taxBps(v: unknown): number | null | undefined {\n if (v === null || v === undefined) return null;\n if (typeof v === \"number\" && Number.isFinite(v) && v >= 0) return v;\n if (typeof v === \"string\" && /^[0-9]{1,6}$/.test(v)) return Number(v);\n return undefined;\n}\n\nlet sequence = 0;\n\n/** What {@link zeroExProvider} returns: a swap2 provider, plus the Settler resolver it reads through (for signing policies, `zeroExKnownSpenders`). */\nexport type ZeroExProvider = CrossChainProvider & {readonly ownGasEstimate: true; readonly settlerResolver: SettlerResolver};\n\nexport function zeroExProvider(config: ZeroExProviderConfig): ZeroExProvider {\n if (config.apiKey !== undefined && onReactNative()) {\n throw new Error(\"zeroex: the 0x API key belongs on a server — in a React Native app it would ship in the bundle, and React Native's fetch follows redirects with the key attached. Run zeroExProvider({apiKey}) on your backend (createSwap2Handler) and zeroExRemoteProvider({baseUrl, rpcUrls}) in the app.\");\n }\n const baseUrl = apiOrigin(config.baseUrl);\n const apiOriginOnly = originOf(baseUrl);\n const chains = zeroExChains(config.chains);\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const excluded = (config.excludedSources ?? []).filter((s) => typeof s === \"string\" && /^[A-Za-z0-9_.\\- ]{1,60}$/.test(s));\n const resolver = config.settlerResolver ?? createSettlerResolver({chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs});\n\n /** The chain id when the chain is in the table and a key is there to ask with. */\n const chainIdOf = (caip2: string): number | null => {\n const id = zeroExChainId(caip2);\n return zeroExChain(chains, id) && readKey(config.apiKey) !== undefined ? id : null;\n };\n const chainOfIntent = (intentId: string): number => {\n const id = Number(intentId.split(\":\")[1]);\n return zeroExChain(chains, id) ? id : NaN;\n };\n\n return {\n name: ZEROEX_PROVIDER,\n describeActivity: (tx, ctx) => describeZeroExActivity(tx, ctx, chains),\n supportsSameChain: true,\n // The quoted gas limit is the API's word: a native sale (like a Permit2 call) goes out with the account's own estimate.\n ownGasEstimate: true,\n settlerResolver: resolver,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => from.chain === to.chain && chainIdOf(from.chain) !== null,\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`zeroex: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n /** A refusal raised by the checks (settler.ts, the core reader): its text without the prefix, and its reason. */\n const refuseError = (e: unknown, prefix: RegExp, fallback: string): null =>\n refuse(e instanceof Error ? e.message.replace(prefix, \"\") : fallback, refusalOf(e) ?? \"policy_refused\");\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = zeroExChainId(params.sourceChain);\n const chain = zeroExChain(chains, chainId);\n if (!chain) return refuse(`0x is not configured for ${String(params.sourceChain).slice(0, 40)}`, \"unsupported_pair\");\n const key = readKey(config.apiKey);\n if (key === undefined) return refuse(\"no 0x API key is configured\", \"key_rejected\");\n\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${String(params.sourceToken).slice(0, 60)}`, \"unsupported_pair\");\n if (src.contract && !ADDRESS.test(src.contract)) return refuse(\"source token must be an EVM address\");\n const sellToken = src.contract ? getAddress(src.contract) : ZEROEX_NATIVE;\n if (typeof params.destToken !== \"string\" || !ADDRESS.test(params.destToken)) return refuse(\"destination token must be an EVM address\");\n const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : getAddress(params.destToken);\n const nativeSell = sellToken === ZEROEX_NATIVE;\n const nativeBuy = buyToken === ZEROEX_NATIVE;\n if (same(sellToken, buyToken)) return refuse(\"same token in and out\", \"unsupported_pair\");\n if (chain.wrappedNative && ((nativeSell && same(buyToken, chain.wrappedNative)) || (nativeBuy && same(sellToken, chain.wrappedNative)))) {\n return refuse(\"wrapping and unwrapping are not 0x swaps\", \"unsupported_pair\");\n }\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return refuse(\"invalid slippage\");\n let floor: bigint | null = null;\n if (params.minAmountOut !== undefined) {\n floor = uint(params.minAmountOut);\n if (floor === null) return refuse(\"minimum output is not an integer\");\n }\n\n const dry = params.dry !== false;\n let taker: string | undefined;\n let recipient: string | undefined;\n if (dry) {\n // An indicative price needs no account; with one, 0x can also report the balance and allowance it sees.\n const known = isAddress(params.refundAddress) ? params.refundAddress : isAddress(params.destAddress) ? params.destAddress : undefined;\n taker = known ? getAddress(known) : undefined;\n } else {\n if (!isAddress(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n recipient = getAddress(params.destAddress);\n taker = getAddress(isAddress(params.refundAddress) ? params.refundAddress : params.destAddress);\n }\n\n // The Settler comes from the chain before anything is asked of the API: no registry answer, no executable quote.\n let settlers: readonly string[] = [];\n if (!dry) {\n try {\n settlers = await resolver.resolve(chainId);\n } catch (e) {\n return refuseError(e, /^zeroex: /, \"the 0x Settler cannot be resolved\");\n }\n }\n\n const query: [string, string][] = [\n [\"chainId\", String(chainId)],\n [\"sellToken\", sellToken],\n [\"buyToken\", buyToken],\n [\"sellAmount\", amountIn.toString()],\n [\"slippageBps\", String(bps)],\n ];\n if (taker) query.push([\"taker\", taker]);\n if (recipient && taker && !same(recipient, taker)) query.push([\"recipient\", recipient]);\n if (excluded.length) query.push([\"excludedSources\", excluded.join(\",\")]);\n const url = `${baseUrl}/swap/permit2/${dry ? \"price\" : \"quote\"}?${query.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(\"&\")}`;\n\n let status: number;\n let text: string;\n let retryAfter: string | null = null;\n try {\n const timeout = timeoutSignal(timeoutMs);\n // The key rides in a header: a redirect (a misconfigured baseUrl, a compromised edge) must not carry it on.\n const res = await fetch(url, {method: \"GET\", redirect: \"error\", headers: {accept: \"application/json\", \"0x-api-key\": key, \"0x-version\": \"v2\"}, signal: signal ? anySignal([signal, timeout]) : timeout});\n // A fetch that ignores `redirect: \"error\"` (React Native's does): an answer that came through a redirect, or\n // from another origin than the configured one, is not used.\n if (res.redirected === true || (typeof res.url === \"string\" && res.url !== \"\" && originOf(res.url) !== apiOriginOnly)) {\n return refuse(\"the API answer came through a redirect or from another origin — refused (the key must not follow one)\", \"policy_refused\");\n }\n status = res.status;\n retryAfter = res.headers?.get?.(\"retry-after\") ?? null;\n text = await res.text();\n } catch (e) {\n // The caller's own abort is not the venue failing.\n return refuse(`API unreachable (${e instanceof Error ? e.name.slice(0, 40) : \"error\"})`, signal?.aborted ? undefined : \"upstream_unavailable\");\n }\n if (text.length > MAX_RESPONSE_CHARS) return refuse(\"the API answer is larger than any quote\", \"upstream_unavailable\");\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n if (status < 200 || status >= 300) {\n const byStatus = httpRefusal(status, retryAfter);\n const name = plain(body) ? own(body, \"name\") : undefined;\n if (typeof name === \"string\" && Object.prototype.hasOwnProperty.call(API_ERRORS, name)) {\n const [why, reason] = API_ERRORS[name]!;\n // A 429 stays a rate limit (with its wait) whatever the body names; an upstream failure keeps its status.\n return refuse(`${why} (${name})`, byStatus?.reason === \"rate_limited\" ? byStatus : reason === \"upstream_unavailable\" || reason === \"key_rejected\" ? {reason, httpStatus: status} : reason);\n }\n if (status === 401 || status === 403) return refuse(`API key rejected (HTTP ${status})`, byStatus);\n if (status === 429) return refuse(\"rate limited (HTTP 429)\", byStatus);\n // Any other status: a JSON refusal is a quote 0x does not have; anything else is an answer of another shape.\n return refuse(`API answered HTTP ${status}`, byStatus ?? (plain(body) ? \"no_route\" : {reason: \"upstream_unavailable\", httpStatus: status}));\n }\n if (!plain(body)) return refuse(\"malformed API response\", \"upstream_unavailable\");\n const r = body;\n\n if (own(r, \"liquidityAvailable\") === false) return refuse(\"no liquidity for this pair and amount\", \"insufficient_liquidity\");\n if (own(r, \"liquidityAvailable\") !== true) return refuse(\"malformed API response (liquidity)\", \"upstream_unavailable\");\n const mode = own(r, \"mode\");\n if (mode !== undefined && mode !== \"exact-in\") return refuse(\"the API answered a quote that is not exact-input\", \"policy_refused\");\n const echoedSell = own(r, \"sellToken\");\n const echoedBuy = own(r, \"buyToken\");\n if (!isAddress(echoedSell) || !same(echoedSell, sellToken) || !isAddress(echoedBuy) || !same(echoedBuy, buyToken)) return refuse(\"the API quoted other tokens than the ones asked for\", \"policy_refused\");\n const quotedIn = uint(own(r, \"sellAmount\"));\n const buyAmount = uint(own(r, \"buyAmount\"));\n const minBuyAmount = uint(own(r, \"minBuyAmount\"));\n if (quotedIn === null || buyAmount === null || minBuyAmount === null) return refuse(\"malformed quote amounts\", \"upstream_unavailable\");\n if (quotedIn !== amountIn) return refuse(`quoted ${quotedIn}, not the requested ${amountIn}`, \"policy_refused\");\n if (minBuyAmount <= 0n || minBuyAmount > buyAmount) return refuse(\"the quoted minimum is not between zero and the quoted output\", \"price_check_failed\");\n if (minBuyAmount < slippageFloor(buyAmount, bps)) return refuse(`the quoted minimum ${minBuyAmount} is below the requested slippage (${bps} bps of ${buyAmount})`, \"price_check_failed\");\n if (floor !== null && minBuyAmount < floor) return refuse(`floor breach (min=${minBuyAmount} < floor=${floor})`, \"price_check_failed\");\n\n // A buy token that taxes transfers arrives short of the minimum Settler measured: refused rather than promised.\n // Only what 0x reports can be judged: a tax it does not flag (null / absent counts as none) is not caught here.\n const metadata = own(r, \"tokenMetadata\");\n const buyMeta = plain(metadata) ? own(metadata, \"buyToken\") : undefined;\n if (buyMeta !== undefined && buyMeta !== null) {\n if (!plain(buyMeta)) return refuse(\"malformed API response (token metadata)\", \"upstream_unavailable\");\n for (const field of [\"buyTaxBps\", \"transferTaxBps\"]) {\n const tax = taxBps(own(buyMeta, field));\n if (tax === undefined) return refuse(\"malformed API response (token tax)\", \"upstream_unavailable\");\n if (tax !== null && tax > 0) return refuse(\"the token being bought taxes transfers — the amount received cannot be guaranteed\", \"unsupported_pair\");\n }\n }\n\n const transaction = own(r, \"transaction\");\n if (!dry && !plain(transaction)) return refuse(\"the quote carries no transaction\", \"upstream_unavailable\");\n const tx = plain(transaction) ? transaction : undefined;\n const parsedFees = zeroExFees(r, tx ? {gas: own(tx, \"gas\"), gasPrice: own(tx, \"gasPrice\")} : {gas: own(r, \"gas\"), gasPrice: own(r, \"gasPrice\")});\n if (typeof parsedFees === \"string\") return refuse(parsedFees, parsedFees === UNASKED_INTEGRATOR_FEE ? \"policy_refused\" : \"upstream_unavailable\");\n // 0x's gas figure for this call (a live quote's `transaction.gas`, a price's `gas`), for comparing routes only.\n const gasEstimate = zeroExGasEstimate(tx ? own(tx, \"gas\") : own(r, \"gas\"));\n\n // What 0x says about the account: informative only (the engine checks balance and allowance itself).\n const flags: string[] = [];\n const issues = own(r, \"issues\");\n if (plain(issues)) {\n if (own(issues, \"balance\")) flags.push(\"balance\");\n if (own(issues, \"simulationIncomplete\") === true) flags.push(\"simulationIncomplete\");\n const allowance = own(issues, \"allowance\");\n if (plain(allowance)) {\n const spender = own(allowance, \"spender\");\n if (!isAddress(spender) || !same(spender, ZEROEX_PERMIT2)) return refuse(\"the API asks for an allowance to something other than canonical Permit2\", \"vault_mismatch\");\n flags.push(\"allowance\");\n }\n // A source name 0x does not know is silently not excluded: a misspelt exclusion must not pass as applied.\n const invalid = own(issues, \"invalidSourcesPassed\");\n if (Array.isArray(invalid) && invalid.length) {\n const names = invalid.filter((n): n is string => typeof n === \"string\" && /^[A-Za-z0-9_.\\- ]{1,60}$/.test(n)).slice(0, 3);\n return refuse(`0x does not know the excluded source${invalid.length > 1 ? \"s\" : \"\"} ${names.length ? names.join(\", \") : \"it was given\"}${invalid.length > names.length ? \" and more\" : \"\"} — they would not be excluded`, \"policy_refused\");\n }\n }\n // 0x names canonical Permit2 as the allowance target of every answer, native sales included (where nothing is\n // approved: the transaction below carries no allowance target then). Anything else is refused.\n const allowanceTarget = own(r, \"allowanceTarget\");\n if (allowanceTarget !== null && allowanceTarget !== undefined) {\n const permit2Target = isAddress(allowanceTarget) && same(allowanceTarget, ZEROEX_PERMIT2);\n if (nativeSell && !permit2Target) return refuse(\"the API asks for a token allowance on a native-coin sale\", \"policy_refused\");\n if (!permit2Target) return refuse(\"the API asks for an allowance to something other than canonical Permit2\", \"vault_mismatch\");\n }\n const zidRaw = own(r, \"zid\");\n const zid = typeof zidRaw === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(zidRaw) ? zidRaw : undefined;\n\n const now = Date.now();\n let validUntilMs = now + ttl;\n let txRequest: Quote[\"txRequest\"];\n let settler: string | undefined;\n if (!dry && tx && recipient) {\n const to = own(tx, \"to\");\n const data = own(tx, \"data\");\n const value = uint(own(tx, \"value\"));\n if (!isAddress(to) || typeof data !== \"string\" || value === null) return refuse(\"malformed quote transaction\", \"upstream_unavailable\");\n\n let permit2Transfer: string | undefined;\n let permit2: Permit2Transfer | undefined;\n const permit = own(r, \"permit2\");\n if (nativeSell) {\n if (permit !== null && permit !== undefined) return refuse(\"the API asks for a Permit2 signature on a native-coin sale\", \"policy_refused\");\n // A native sale signs nothing that would lapse: its quote is bounded here, inside the app verifier's bound by the clock-skew allowance.\n validUntilMs = Math.min(validUntilMs, now + (ZEROEX_MAX_NATIVE_QUOTE_SECONDS - ZEROEX_NATIVE_QUOTE_SKEW_SECONDS) * 1000);\n } else {\n const eip712 = plain(permit) ? own(permit, \"eip712\") : undefined;\n if (!plain(permit) || !plain(eip712)) return refuse(\"the quote carries no Permit2 payload to sign\", \"policy_refused\");\n try {\n // Only these four members are read; the reader holds them to this swap and the payload is rebuilt from that.\n permit2 = readPermit2Transfer(JSON.stringify({domain: own(eip712, \"domain\"), types: own(eip712, \"types\"), primaryType: own(eip712, \"primaryType\"), message: own(eip712, \"message\")}), {\n chainId,\n token: sellToken,\n amount: amountIn,\n spender: to,\n nowMs: now,\n });\n } catch (e) {\n return refuseError(e, /^swap2: /, \"the Permit2 payload is refused\");\n }\n // 0x states the digest it expects signed; the locally rebuilt payload must hash to it.\n const hash = own(permit, \"hash\");\n if (hash !== null && hash !== undefined) {\n const local = hashTypedData({\n domain: permit2.domain,\n types: {PermitTransferFrom: permit2.types.PermitTransferFrom, TokenPermissions: permit2.types.TokenPermissions},\n primaryType: permit2.primaryType,\n message: permit2.message,\n } as unknown as Parameters<typeof hashTypedData>[0]);\n if (typeof hash !== \"string\" || !same(hash, local)) return refuse(\"the Permit2 payload does not hash to what the API says is being signed\", \"policy_refused\");\n }\n permit2Transfer = permit2TransferJson(permit2);\n // The quote lapses before the signature it asks for does (the reader bounds the deadline to the next hour).\n const lapse = permit2.deadline * 1000n - BigInt(DEADLINE_MARGIN_MS);\n if (lapse <= BigInt(now)) return refuse(\"the Permit2 deadline is too close to sign against\", \"quote_expired\");\n if (lapse < BigInt(validUntilMs)) validUntilMs = bigintToNumber(lapse);\n }\n\n const gas = uint(own(tx, \"gas\"));\n // 0x's own limit for the call, with room for the appended signature and a moved route.\n const gasLimit = gas !== null && gas > 0n ? ((gas * 12n) / 10n + 20_000n).toString() : undefined;\n const candidate = {\n to,\n data,\n value: value.toString(),\n chainId,\n ...(gasLimit !== undefined ? {gasLimit} : {}),\n ...(nativeSell ? {} : {approvalAddress: ZEROEX_PERMIT2}),\n ...(permit2Transfer !== undefined ? {permit2Transfer} : {}),\n };\n const expectation = (set: readonly string[]): ZeroExExpectation => ({chainId, chain, settlers: set, sellToken, buyToken, sellAmount: amountIn, recipient: recipient!, minBuyAmount, nowMs: now});\n try {\n try {\n checkZeroExTransaction(candidate, expectation(settlers));\n } catch (first) {\n // 0x may already quote a Settler deployed after the cached registry read: read again, once.\n if (settlers.some((s) => same(s, to))) throw first;\n settlers = await resolver.resolve(chainId, {fresh: true});\n checkZeroExTransaction(candidate, expectation(settlers));\n }\n } catch (e) {\n return refuseError(e, /^zeroex: /, \"the transaction is refused\");\n }\n settler = getAddress(to);\n txRequest = {\n to: settler,\n data,\n value: value.toString(),\n chainId,\n ...(gasLimit !== undefined ? {gasLimit} : {}),\n ...(nativeSell ? {} : {approvalAddress: getAddress(ZEROEX_PERMIT2)}),\n ...(permit2Transfer !== undefined ? {permit2Transfer} : {}),\n };\n }\n\n const sources = zeroExSources(own(r, \"route\"));\n return {\n provider: ZEROEX_PROVIDER,\n intentId: `zeroex:${chainId}:${now.toString(36)}${(sequence = (sequence + 1) % 1_000_000).toString(36)}`,\n depositAddress: \"\",\n depositMemo: null,\n ...(txRequest ? {txRequest} : {}),\n sourceAmount: amountIn.toString(),\n destAmount: buyAmount.toString(),\n minDestAmount: minBuyAmount.toString(),\n feeUsd: 0,\n fees: parsedFees.fees,\n ...(gasEstimate !== undefined ? {gasEstimate, gasEstimateSource: \"venue\" as const} : {}),\n etaSeconds: 15,\n reliability: 0.96,\n validUntilMs,\n providerData: {\n minOut: minBuyAmount.toString(),\n slippageBps: String(bps),\n ...(taker ? {sender: taker} : {}),\n ...(settler ? {settler} : {}),\n ...(zid ? {zid} : {}),\n ...(sources ? {sources} : {}),\n ...(parsedFees.networkFeeKnown ? {} : {networkFee: \"unknown\"}),\n ...(flags.length ? {issues: flags.join(\",\")} : {}),\n },\n };\n },\n\n /**\n * Before the engine signs: the transaction must be the quoted one, and its target must still be a Settler in the\n * registry now ({@link zeroExPreflightDeposit}). The call itself cannot be simulated yet: it needs the Permit2\n * signature, which the engine makes next and then estimates as signed.\n */\n preflightDeposit: (quote: Quote, tx: UnsignedTx): Promise<void> => zeroExPreflightDeposit(quote, tx, {chains, resolver}),\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"zeroex: not a live quote — it carries no transaction\");\n return {\n chain: \"\",\n to: tx.to,\n value: tx.value ?? \"0\",\n data: tx.data,\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n ...(tx.permit2Transfer !== undefined ? {permit2Transfer: tx.permit2Transfer} : {}),\n };\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash || !/^0x[0-9a-fA-F]{64}$/.test(ref.sourceTxHash)) return {state: \"pending\"};\n const chainId = chainOfIntent(ref.intentId);\n if (Number.isNaN(chainId) || !rpcUrlsFor(config.rpcUrls, chainId).length) return {state: \"pending\"};\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash]);\n if (!answer || \"error\" in answer || !plain(answer.result)) return {state: \"pending\"};\n const status = own(answer.result, \"status\");\n if (status === \"0x1\") return {state: \"completed\", destTxHash: ref.sourceTxHash};\n return status === \"0x0\" ? {state: \"failed\"} : {state: \"pending\"};\n },\n };\n}\n\n/**\n * The device's last check before the engine signs a 0x swap, run by the `preflightDeposit` of both providers (in remote\n * mode before the backend's own preflight is asked): the transaction must be the quoted one, its gas limit (when it\n * carries one) within the chain's cap, and its target must still be a Settler the registry names now — a fresh read\n * through `resolver` (the device's own RPC), so a Settler paused, replaced or removed since the quote (on the review\n * screen, during an approval) is refused here, with nothing signed or sent.\n */\nexport async function zeroExPreflightDeposit(quote: Quote, tx: UnsignedTx, ctx: {chains: Readonly<Record<number, ZeroExChain>>; resolver: SettlerResolver}): Promise<void> {\n const quoted = quote.txRequest;\n if (\n !quoted?.to || !quoted.data || typeof tx.to !== \"string\" || typeof tx.data !== \"string\" ||\n !same(tx.to, quoted.to) || !same(tx.data, quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\") ||\n tx.permit2Transfer !== quoted.permit2Transfer\n ) {\n throw refusal(\"policy_refused\", \"zeroex: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n const chainId = typeof quote.intentId === \"string\" ? Number(quote.intentId.split(\":\")[1]) : NaN;\n const chain = zeroExChain(ctx.chains, chainId);\n if (!chain) throw refusal(\"policy_refused\", \"zeroex: the quote names no chain this provider serves. Nothing was sent.\");\n checkZeroExGasLimit(tx.gasLimit, chain, chainId);\n const settlers = await ctx.resolver.resolve(chainId, {fresh: true});\n if (!settlers.some((s) => same(s, quoted.to!))) {\n throw refusal(\"vault_mismatch\", \"zeroex: the quoted 0x Settler is no longer in the on-chain registry. Nothing was sent; refresh the quote.\");\n }\n}\n\n/** The liquidity sources of `route.fills`, at most six short names, for display. */\nfunction zeroExSources(route: unknown): string | undefined {\n const fills = plain(route) ? own(route, \"fills\") : undefined;\n if (!Array.isArray(fills)) return undefined;\n const names: string[] = [];\n for (const fill of fills.slice(0, 64)) {\n const source = plain(fill) ? own(fill, \"source\") : undefined;\n if (typeof source !== \"string\" || !/^[A-Za-z0-9_.\\- ]{1,40}$/.test(source)) continue;\n if (!names.includes(source)) names.push(source);\n if (names.length === 6) break;\n }\n return names.length ? names.join(\",\") : undefined;\n}\n","/**\n * Activity recognition for 0x: a `Settler.execute` call to a 0x Settler on a chain the module serves\n * → `swap`, \"Swapped A → B\" from the owner's net transfers.\n *\n * 0x replaces its Settler contracts regularly (the registry names the one in force), so past swaps\n * were sent to addresses no pinned list can hold. Every Settler, past or present, is however an\n * address the registry deploys to (CREATE3, see `zeroExSettlerNonce`), which is computed offline: a\n * transaction is recognized by its target being one, by the method (`execute`, selector `0x1fff991f`)\n * and, when its calldata is there, by that calldata reading as a Settler call. A contract that only\n * copies the selector is not labelled a 0x swap. This only labels history; nothing is signed on it.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {callSelector, chainLabel, describeSwapLike} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {ZEROEX_CHAINS, ZEROEX_SETTLER_NONCE_MARGIN, zeroExChain, zeroExChainId, type ZeroExChain} from \"./chains.js\";\nimport {SETTLER_EXECUTE_SELECTOR, decodeSettlerExecute, zeroExSettlerNonce} from \"./settler.js\";\n\nexport const ZEROEX_MODULE = \"@anywalletkit/protocol-swap2-0x\";\n\n/**\n * The activity item for a 0x swap, or `null`. `chains` is the chain table to read (default: the module's own); the\n * providers pass the table they were built with, so a chain added or re-pinned through `chains` is labelled too.\n */\nexport function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext, chains: Readonly<Record<number, ZeroExChain>> = ZEROEX_CHAINS): ActivityItem | null {\n const chainId = zeroExChainId(tx.chain);\n const chain = zeroExChain(chains, chainId);\n if (!chain) return null;\n if (callSelector(tx) !== SETTLER_EXECUTE_SELECTOR) return null;\n const target = tx.call?.to ?? tx.to;\n // Any deployment up to the newest one the chain accepts (past swaps went to older Settlers too); bounded by the pin,\n // an address that is no Settler costs a few dozen derivations.\n if (typeof target !== \"string\" || zeroExSettlerNonce(chainId, target, chain.registry, chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN) === null) return null;\n const data = tx.call?.data;\n if (typeof data === \"string\" && data.length > 10) {\n try {\n decodeSettlerExecute(data);\n } catch {\n return null;\n }\n }\n return describeSwapLike(tx, ctx, {protocol: ZEROEX_MODULE, subtitle: `0x · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * The app's side of 0x when the API key stays on a server.\n *\n * `zeroExRemoteProvider({baseUrl, rpcUrls})` forwards quotes and builds to your backend (which runs\n * `zeroExProvider` with the key) and checks, on the device, everything that comes back before the\n * engine signs: the Settler from the on-chain registry read through the app's own RPC, the\n * transaction and the Permit2 payload held to the request the app itself sent\n * ({@link zeroExVerifyQuote} on the quote, {@link zeroExVerifyBuild} on the build), and, right\n * before the broadcast, the registry read once more ({@link zeroExPreflightDeposit}) ahead of the\n * backend's own preflight. The backend is what these checks guard against; it never names its own\n * Settler, spender, recipient or minimum.\n *\n * Every text the verifiers return is classified (`zeroExPins.reasonOf`, CS-13), so a remote stub's\n * refusal carries its `Swap2RefusalReason`; the app's own malformed request stays unclassified.\n */\nimport {getAddress} from \"viem\";\nimport {refusalNotes, refusalOf, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {remoteProvider, type RemoteProviderOptions} from \"@anywalletkit/protocol-swap2-core/remote\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {slippageFloor} from \"@anywalletkit/protocol-swap2-core/validate\";\nimport type {CrossChainProvider, Quote, QuoteParams, RemotePins, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {describeZeroExActivity} from \"./activity.js\";\nimport {ZEROEX_NATIVE, ZEROEX_PERMIT2, zeroExChain, zeroExChainId, zeroExChains, type ZeroExChain} from \"./chains.js\";\nimport {ZEROEX_PROVIDER, zeroExPreflightDeposit} from \"./provider.js\";\nimport type {RpcUrls} from \"./rpc.js\";\nimport {ZEROEX_MAX_NATIVE_QUOTE_SECONDS, checkZeroExTransaction, createSettlerResolver, isZeroExNative, type SettlerResolver} from \"./settler.js\";\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst same = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null);\nconst message = (e: unknown, fallback: string): string => (e instanceof Error ? e.message.replace(/^zeroex: /, \"\") : fallback);\n\n/** The reason behind each text {@link zeroExVerifyQuote} / {@link zeroExVerifyBuild} return (`zeroExPins.reasonOf`). */\nconst notes = refusalNotes();\n/** A verifier's answer: the text, its reason remembered (none: the app's own malformed request). */\nconst note = (text: string, reason?: Swap2RefusalReason): string =>\n // Noted without a valid reason, a text is unclassified (and forgets any earlier classification of the same text).\n notes.note(text, reason ?? ({} as Swap2RefusalReason));\n/** A refusal raised by the checks: its text without the prefix, and the reason it carries. */\nconst noteError = (e: unknown, fallback: string): string => note(message(e, fallback), refusalOf(e)?.reason ?? \"policy_refused\");\n\n/** The reason a text from {@link zeroExVerifyQuote} or {@link zeroExVerifyBuild} carries; undefined for any other text. */\nexport const zeroExRefusalReason = (text: string) => notes.reasonOf(text);\n\nexport interface ZeroExVerifyContext {\n /** The chain table in force. */\n chains: Readonly<Record<number, ZeroExChain>>;\n /** Settlers the app resolved from the registry for a chain (never the backend's word). */\n settlers(chainId: number): readonly string[];\n /** The most slippage accepted when the request named none, bps. Default 50 — the provider's own default. */\n defaultSlippageBps?: number | undefined;\n /** Clock (tests). */\n nowMs?: number | undefined;\n}\n\n/**\n * A remote 0x quote, held to the request the app sent. Null when it passes, the reason otherwise.\n *\n * An indicative quote (`dry`) carries no transaction and only its amounts are checked. A live quote must carry one,\n * and it goes through {@link checkZeroExTransaction} with an expectation built only from `params`: the sell token and\n * amount, the buy token, the app's recipient, the quote's minimum (itself held to the requested slippage and floor),\n * the chain's pins and the Settlers the app resolved. It may stay valid no longer than its Permit2 deadline (a token\n * sale) or {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS} from now (a native-coin sale).\n */\nexport function zeroExVerifyQuote(params: QuoteParams, quote: Quote, ctx: ZeroExVerifyContext): string | null {\n if (quote.provider !== ZEROEX_PROVIDER) return note(\"the quote is not a 0x quote\", \"policy_refused\");\n if (params.sourceChain !== params.destChain) return note(\"0x swaps stay on one chain\", \"unsupported_pair\");\n const chainId = zeroExChainId(params.sourceChain);\n const chain = zeroExChain(ctx.chains, chainId);\n if (!chain) return note(\"the chain is not in the 0x chain table\", \"unsupported_pair\");\n if (quote.intentId.replace(/~[0-9a-f]{32}$/, \"\").split(\":\").slice(0, 2).join(\":\") !== `zeroex:${chainId}`) return note(\"the intent id does not name this chain\", \"policy_refused\");\n const src = sourceAssetOf(params);\n if (!src) return note(\"unknown source token\");\n if (src.contract && !ADDRESS.test(src.contract)) return note(\"the source token is not an EVM address\");\n if (typeof params.destToken !== \"string\" || !ADDRESS.test(params.destToken)) return note(\"the destination token is not an EVM address\");\n const sellToken = src.contract ? getAddress(src.contract) : ZEROEX_NATIVE;\n const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : getAddress(params.destToken);\n\n const amountIn = uint(params.amountIn);\n const quotedIn = uint(quote.sourceAmount);\n const dest = uint(quote.destAmount);\n const min = uint(quote.minDestAmount);\n if (amountIn === null || quotedIn === null || dest === null || min === null) return note(\"the quote's amounts are not integers\", amountIn === null ? undefined : \"upstream_unavailable\");\n if (quotedIn !== amountIn) return note(`the quote spends ${quotedIn}, not the ${amountIn} input`, \"policy_refused\");\n if (min <= 0n || min > dest) return note(\"the quoted minimum is not between zero and the quoted output\", \"price_check_failed\");\n const bps = params.slippageBps ?? ctx.defaultSlippageBps ?? 50;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return note(\"invalid slippage\");\n if (min < slippageFloor(dest, bps)) return note(`the quoted minimum ${min} is below ${bps} bps of the quoted output`, \"price_check_failed\");\n if (params.minAmountOut !== undefined) {\n const floor = uint(params.minAmountOut);\n if (floor === null || min < floor) return note(`the quoted minimum ${min} is below the caller's floor`, floor === null ? undefined : \"price_check_failed\");\n }\n\n const tx = quote.txRequest;\n const dry = params.dry !== false;\n if (!tx) return dry ? null : note(\"a live quote carries no transaction\", \"upstream_unavailable\");\n if (dry) return note(\"an indicative quote carries a transaction\", \"policy_refused\");\n if (tx.serializedTx !== undefined || tx.nativeFee !== undefined) return note(\"the quote carries more than a Settler call\", \"policy_refused\");\n if (typeof params.destAddress !== \"string\" || !ADDRESS.test(params.destAddress)) return note(\"a live quote needs the recipient\", \"recipient_mismatch\");\n try {\n const checked = checkZeroExTransaction(tx, {\n chainId,\n chain,\n settlers: ctx.settlers(chainId),\n sellToken,\n buyToken,\n sellAmount: amountIn,\n recipient: params.destAddress,\n minBuyAmount: min,\n ...(ctx.nowMs !== undefined ? {nowMs: ctx.nowMs} : {}),\n });\n // The quote must lapse before the signature it asks for does; a native sale, which signs nothing, within a short window.\n if (checked.permit2 && !(Number.isFinite(quote.validUntilMs) && BigInt(Math.ceil(quote.validUntilMs)) <= checked.permit2.deadline * 1000n)) return note(\"the quote outlives its Permit2 deadline\", \"policy_refused\");\n if (!checked.permit2 && !(Number.isFinite(quote.validUntilMs) && quote.validUntilMs <= (ctx.nowMs ?? Date.now()) + ZEROEX_MAX_NATIVE_QUOTE_SECONDS * 1000)) {\n return note(`the native-coin sale's quote is valid for more than ${ZEROEX_MAX_NATIVE_QUOTE_SECONDS} s`, \"policy_refused\");\n }\n } catch (e) {\n return noteError(e, \"the transaction is refused\");\n }\n return null;\n}\n\n/**\n * A remote 0x build, held to its quote and to the request: the built transaction must be the quote's own (target,\n * data, value, chain, allowance target, Permit2 payload), and that quote must pass {@link zeroExVerifyQuote} again\n * against Settlers read from the registry just now. Without the request (`params`) nothing can be checked: refused.\n */\nexport async function zeroExVerifyBuild(quote: Quote, tx: UnsignedTx, params: QuoteParams | undefined, ctx: ZeroExVerifyContext & {resolver: SettlerResolver}): Promise<string | null> {\n if (!params) return note(\"the request this quote answered is not known to the app\", \"policy_refused\");\n const quoted = quote.txRequest;\n if (!quoted?.to || !quoted.data) return note(\"the quote carries no transaction\", \"policy_refused\");\n if (\n typeof tx.to !== \"string\" || typeof tx.data !== \"string\" || !same(tx.to, quoted.to) || !same(tx.data, quoted.data) ||\n uint(tx.value || \"0\") === null || uint(tx.value || \"0\") !== uint(quoted.value ?? \"0\") ||\n (tx.chainId !== undefined && tx.chainId !== quoted.chainId) ||\n tx.approvalAddress !== quoted.approvalAddress || tx.permit2Transfer !== quoted.permit2Transfer || tx.gasLimit !== quoted.gasLimit ||\n tx.serializedTx !== undefined || tx.typedData !== undefined || tx.memo !== undefined\n ) {\n return note(\"the built transaction is not the quoted swap\", \"policy_refused\");\n }\n let settlers: readonly string[];\n try {\n settlers = await ctx.resolver.resolve(zeroExChainId(params.sourceChain), {fresh: true});\n } catch (e) {\n return noteError(e, \"the 0x Settler cannot be resolved\");\n }\n return zeroExVerifyQuote({...params, dry: false}, quote, {...ctx, settlers: () => settlers});\n}\n\nexport interface ZeroExPinsConfig {\n chains?: Readonly<Record<number, ZeroExChain | null>> | undefined;\n /** JSON-RPC endpoints per EVM chain id — the app's own, for the Settler registry read. */\n rpcUrls?: RpcUrls | undefined;\n settlerMaxAgeMs?: number | undefined;\n settlerResolver?: SettlerResolver | undefined;\n /** The most slippage accepted when a request names none, bps. Default 50; keep it in step with the backend's default. */\n defaultSlippageBps?: number | undefined;\n}\n\n/**\n * The app's pins for a remote 0x provider. Unlike a provider with one fixed router, the call target is whatever the\n * registry names now, so the pins hold a resolver: `callTargets` answers from its last fresh read (empty until one is\n * made — use {@link zeroExRemoteProvider}, which reads before every live quote and build), `spenders` is canonical\n * Permit2 and nothing else. `reasonOf` classifies every text the verifiers return.\n *\n * For a signing policy's known Permit2 spenders (wallet-evm `describeTypedData({knownSpenders})`, a kit allowlist)\n * use {@link zeroExKnownSpenders} with the provider the app swaps through: the Settler rotates, so no static table can\n * hold it, and a fresh `zeroExPins()` has a resolver of its own that has read nothing yet.\n */\nexport function zeroExPins(config: ZeroExPinsConfig = {}): RemotePins & {resolver: SettlerResolver; chains: Readonly<Record<number, ZeroExChain>>} {\n const chains = zeroExChains(config.chains);\n const resolver = config.settlerResolver ?? createSettlerResolver({chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs});\n const ctx: ZeroExVerifyContext = {chains, settlers: (chainId) => resolver.known(chainId), defaultSlippageBps: config.defaultSlippageBps};\n return Object.freeze({\n resolver,\n chains,\n callTargets: (chain: string): readonly string[] => (zeroExChain(chains, zeroExChainId(chain)) ? resolver.known(zeroExChainId(chain)) : []),\n spenders: (chain: string): readonly string[] => (zeroExChain(chains, zeroExChainId(chain)) ? [ZEROEX_PERMIT2] : []),\n verifyQuote: (params: QuoteParams, quote: Quote) => zeroExVerifyQuote(params, quote, ctx),\n verifyBuild: (quote: Quote, tx: UnsignedTx, params?: QuoteParams) => zeroExVerifyBuild(quote, tx, params, {...ctx, resolver}),\n reasonOf: zeroExRefusalReason,\n });\n}\n\nexport interface ZeroExRemoteOptions extends ZeroExPinsConfig, Pick<RemoteProviderOptions, \"baseUrl\" | \"enabled\" | \"fetchImpl\" | \"headers\" | \"timeoutMs\" | \"allowInsecureBaseUrl\"> {}\n\n/** What {@link zeroExRemoteProvider} returns: a remote swap2 provider, plus the Settler resolver it reads through. */\nexport type ZeroExRemoteProvider = CrossChainProvider & {readonly ownGasEstimate: true; readonly settlerResolver: SettlerResolver};\n\n/** How long a live quote's Settler set stays a call target after the quote, at most (its own `validUntilMs` first). */\nconst QUOTED_SET_MAX_MS = 120_000;\n\n/**\n * 0x through your backend: `remoteProvider` with {@link zeroExPins}, plus the registry reads the pins need — the\n * Settler is resolved through the app's RPC before a live quote is asked for (and once more, fresh, if the backend\n * quotes a Settler the app has not seen yet), and the quote is held to exactly that set, however long the backend\n * takes to answer; right before the broadcast `preflightDeposit` reads the registry again on the device and refuses a\n * Settler no longer in it ({@link zeroExPreflightDeposit}), then asks the backend's preflight. Indicative quotes need\n * no RPC. `settlerResolver` is the resolver it reads through (signing policies: {@link zeroExKnownSpenders}).\n */\nexport function zeroExRemoteProvider(options: ZeroExRemoteOptions): ZeroExRemoteProvider {\n const pins = zeroExPins(options);\n const served = (caip2: string): boolean => !!zeroExChain(pins.chains, zeroExChainId(caip2));\n // The Settlers each live quote request was resolved against, by request: the verifier holds the backend's answer to\n // that set, not to whatever the resolver's cache holds once the backend answered (its max age may pass meanwhile).\n const checkedAgainst = new WeakMap<QuoteParams, readonly string[]>();\n // …and, per chain, while that quote may still be used: the router's pin check (callTargets) runs after the answer too.\n const quoted = new Map<number, {settlers: readonly string[]; untilMs: number}>();\n const callTargets = (chain: string): readonly string[] => {\n const chainId = zeroExChainId(chain);\n const known = pins.callTargets(chain);\n const held = quoted.get(chainId);\n if (!held || held.untilMs < Date.now() || !zeroExChain(pins.chains, chainId)) return known;\n return [...known, ...held.settlers.filter((s) => !known.some((k) => same(k, s)))];\n };\n const verifyCtx: ZeroExVerifyContext = {chains: pins.chains, settlers: (chainId) => pins.resolver.known(chainId), defaultSlippageBps: options.defaultSlippageBps};\n const inner = remoteProvider({\n name: ZEROEX_PROVIDER,\n baseUrl: options.baseUrl,\n supportsSameChain: true,\n supportsChain: served,\n supportsChainPair: (from, to) => from === to && served(from),\n supportsRoute: (from, to) => from.chain === to.chain && served(from.chain),\n callTargets,\n spenders: pins.spenders,\n verifyQuote: (params, quote) => {\n const set = checkedAgainst.get(params);\n return zeroExVerifyQuote(params, quote, set ? {...verifyCtx, settlers: () => set} : verifyCtx);\n },\n verifyBuild: pins.verifyBuild!,\n reasonOf: pins.reasonOf!,\n ...(options.enabled ? {enabled: options.enabled} : {}),\n ...(options.fetchImpl ? {fetchImpl: options.fetchImpl} : {}),\n ...(options.headers ? {headers: options.headers} : {}),\n ...(options.timeoutMs !== undefined ? {timeoutMs: options.timeoutMs} : {}),\n ...(options.allowInsecureBaseUrl !== undefined ? {allowInsecureBaseUrl: options.allowInsecureBaseUrl} : {}),\n });\n return {\n ...inner,\n describeActivity: (tx, ctx) => describeZeroExActivity(tx, ctx, pins.chains),\n // The quoted gas limit is the backend's word: every call goes out with the account's own estimate.\n ownGasEstimate: true,\n settlerResolver: pins.resolver,\n // The backend's preflight is its own word: the device reads the registry first (a Settler paused, replaced or\n // removed while the user was on the review screen is refused here, nothing sent), then asks the backend.\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n await zeroExPreflightDeposit(quote, tx, {chains: pins.chains, resolver: pins.resolver});\n await inner.preflightDeposit!(quote, tx);\n },\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n if (params.dry !== false) return inner.getQuote(params, signal);\n const chainId = zeroExChainId(params.sourceChain);\n const ask = async (settlers: readonly string[]): Promise<Quote | null> => {\n checkedAgainst.set(params, settlers);\n const q = await inner.getQuote(params, signal);\n if (q) quoted.set(chainId, {settlers, untilMs: Math.min(Number.isFinite(q.validUntilMs) ? q.validUntilMs : 0, Date.now() + QUOTED_SET_MAX_MS)});\n return q;\n };\n const before = await pins.resolver.resolve(chainId);\n try {\n return await ask(before);\n } catch (e) {\n // A Settler the app has not seen: read the registry again and, only if it changed, ask once more.\n if (!(e instanceof Error) || !/is not a 0x Settler from the on-chain registry/.test(e.message)) throw e;\n const after = await pins.resolver.resolve(chainId, {fresh: true});\n if (after.length === before.length && after.every((s, i) => same(s, before[i]!))) throw e;\n return ask(after);\n }\n },\n };\n}\n\n/**\n * The 0x Settlers a signing policy should know as Permit2 spenders on `chainId`, labelled — the `knownSpenders` of\n * wallet-evm's `describeTypedData`, and the addresses a kit allowlist needs next to Permit2 and the token. Pass the\n * provider the app swaps through (`zeroExRemoteProvider` / `zeroExProvider`, or its `settlerResolver`): the set is the\n * one that resolver read from the registry, cached for its max age and read again after it. Empty when the registry\n * cannot be read: the permit is then described as a grant to an unknown spender, never silently trusted.\n *\n * ```ts\n * const zeroex = zeroExRemoteProvider({baseUrl, rpcUrls});\n * describeTypedData(typed, {chainId: 8453, account, knownSpenders: await zeroExKnownSpenders(zeroex, 8453)});\n * ```\n */\nexport async function zeroExKnownSpenders(source: SettlerResolver | {readonly settlerResolver: SettlerResolver}, chainId: number, label = \"0x Settler\"): Promise<Record<string, string>> {\n const resolver = \"settlerResolver\" in source ? source.settlerResolver : source;\n try {\n return Object.fromEntries((await resolver.resolve(chainId)).map((settler) => [settler, label]));\n } catch {\n return {};\n }\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {zeroExProvider, type ZeroExProviderConfig} from \"./provider.js\";\n\nexport interface ZeroExSwap2Config extends Swap2EngineConfig, ZeroExProviderConfig {}\n\n/** 0x as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class ZeroExSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n constructor(account: Swap2Account | undefined, config: ZeroExSwap2Config) {\n super(account, config);\n this.provider = zeroExProvider(config);\n }\n protected override chainSupported(caip2: string): boolean {\n return this.provider.supportsChain?.(caip2) === true;\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,kBAA8B;AAGvB,IAAM,iBAAiB;AAKvB,IAAM,0BAA0B;AAEhC,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB;AAEtB,IAAM,0BAA0B;AAoChC,IAAM,yBAAyB;AAE/B,IAAM,iBAAiB,CAAC,MAA4B,OAAO,MAAM,YAAY,KAAK,MAAM,KAAK;AAS7F,IAAM,8BAA8B;AAEpC,IAAM,2BAA2B;AAExC,IAAM,QAAQ,CAAC,MAAc,eAAuB,iBAAyB,mBAA2B,gBACtG,OAAO,OAAO,EAAC,MAAM,UAAU,yBAAyB,iBAAiB,mBAAmB,eAAe,GAAI,gBAAgB,SAAY,EAAC,YAAW,IAAI,CAAC,EAAE,CAAC;AAY1J,IAAM,gBAAuD,OAAO,OAAO;AAAA,EAChF,GAAG,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EACzE,IAAI,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EAC1E,IAAI,MAAM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AAM,QAAQ,MAAM,KAAK,SAAS,QAAQ,SAAS,EAAC,OAAO,KAAI,CAAC;AAChE,YAAI,MAAM,WAAW,OAAO,UAAU,MAAM,MAAM,CAAC,GAAG,MAAMA,MAAK,GAAG,OAAO,CAAC,CAAE,CAAC,EAAG,OAAM;AACxF,eAAO,IAAI,KAAK;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AACF;AAcA,eAAsB,oBAAoB,QAAuE,SAAiB,QAAQ,cAA+C;AACvL,QAAM,WAAW,qBAAqB,SAAS,OAAO,kBAAkB;AACxE,MAAI;AACF,WAAO,OAAO,aAAa,MAAM,SAAS,QAAQ,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,SAAS,KAAK,CAAC,CAAC;AAAA,EAChG,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;;;ACnSA,oBAAkC;AAO3B,IAAM,sBAAN,cAAkC,kCAAoB;AAAA,EACxC;AAAA,EACnB,YAAY,SAAmC,QAA2B;AACxE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,eAAe,MAAM;AAAA,EACvC;AAAA,EACmB,eAAe,OAAwB;AACxD,WAAO,KAAK,SAAS,gBAAgB,KAAK,MAAM;AAAA,EAClD;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,cAAc,WAAW,KAAK,eAAe,SAAS;AAAA,EAC/D;AACF;","names":["import_util","import_util","ADDRESS","ZERO_ADDRESS","chain","import_viem","import_errors","import_util","chain","ADDRESS","same","refuse","chain","import_viem","import_errors","import_util","import_validate","ADDRESS","same","uint","chain"]}
|