@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.
Files changed (56) hide show
  1. package/README.md +31 -6
  2. package/dist/activity.cjs +4 -3
  3. package/dist/activity.cjs.map +1 -1
  4. package/dist/activity.d.cts +6 -1
  5. package/dist/activity.d.ts +6 -1
  6. package/dist/activity.js +3 -3
  7. package/dist/chains.cjs +16 -2
  8. package/dist/chains.cjs.map +1 -1
  9. package/dist/chains.d.cts +26 -6
  10. package/dist/chains.d.ts +26 -6
  11. package/dist/chains.js +5 -1
  12. package/dist/{chunk-ALMGGQS4.js → chunk-ABT2WYBK.js} +6 -6
  13. package/dist/{chunk-ALMGGQS4.js.map → chunk-ABT2WYBK.js.map} +1 -1
  14. package/dist/{chunk-CWZCAJBY.js → chunk-AMZ5DXN2.js} +17 -3
  15. package/dist/chunk-AMZ5DXN2.js.map +1 -0
  16. package/dist/{chunk-AX4RNHWE.js → chunk-KYVRMBZG.js} +2 -2
  17. package/dist/{chunk-RLNXMQJH.js → chunk-S2RUUV3X.js} +16 -6
  18. package/dist/chunk-S2RUUV3X.js.map +1 -0
  19. package/dist/{chunk-QFOKBJXP.js → chunk-V4HUFBY2.js} +5 -5
  20. package/dist/chunk-V4HUFBY2.js.map +1 -0
  21. package/dist/{chunk-NK3PQGI4.js → chunk-YHRPT6BS.js} +20 -5
  22. package/dist/chunk-YHRPT6BS.js.map +1 -0
  23. package/dist/index.cjs +46 -10
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +3 -3
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +16 -6
  28. package/dist/protocol.cjs +40 -9
  29. package/dist/protocol.cjs.map +1 -1
  30. package/dist/protocol.d.cts +1 -1
  31. package/dist/protocol.d.ts +1 -1
  32. package/dist/protocol.js +5 -5
  33. package/dist/provider.cjs +41 -9
  34. package/dist/provider.cjs.map +1 -1
  35. package/dist/provider.d.cts +13 -6
  36. package/dist/provider.d.ts +13 -6
  37. package/dist/provider.js +6 -4
  38. package/dist/remote.cjs +34 -9
  39. package/dist/remote.cjs.map +1 -1
  40. package/dist/remote.d.cts +1 -1
  41. package/dist/remote.d.ts +1 -1
  42. package/dist/remote.js +5 -5
  43. package/dist/{settler-KDFcfsKv.d.cts → settler-CeJFLW5t.d.cts} +21 -4
  44. package/dist/{settler-BpRGkBVV.d.ts → settler-DBLrnepW.d.ts} +21 -4
  45. package/dist/settler.cjs +20 -4
  46. package/dist/settler.cjs.map +1 -1
  47. package/dist/settler.d.cts +1 -1
  48. package/dist/settler.d.ts +1 -1
  49. package/dist/settler.js +6 -2
  50. package/module.json +1 -0
  51. package/package.json +6 -6
  52. package/dist/chunk-CWZCAJBY.js.map +0 -1
  53. package/dist/chunk-NK3PQGI4.js.map +0 -1
  54. package/dist/chunk-QFOKBJXP.js.map +0 -1
  55. package/dist/chunk-RLNXMQJH.js.map +0 -1
  56. /package/dist/{chunk-AX4RNHWE.js.map → chunk-KYVRMBZG.js.map} +0 -0
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@anywalletkit/protocol-swap2-0x?label=npm)](https://www.npmjs.com/package/@anywalletkit/protocol-swap2-0x)
4
4
 
5
- [0x Swap API v2](https://docs.0x.org/docs/api/swap-permit2) as a same-chain swap2 provider for Any Wallet Kit, through the Permit2 flow. Exact-input swaps on Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche and BNB Smart Chain. Written from the 0x API and the Settler contracts; it uses no 0x package.
5
+ [0x Swap API v2](https://docs.0x.org/docs/api/swap-permit2) as a same-chain swap2 provider for Any Wallet Kit, through the Permit2 flow. Exact-input swaps on eight chains: Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche, BNB Smart Chain and Monad (since 0.2.0). Written from the 0x API and the Settler contracts; it uses no 0x package.
6
6
 
7
7
  ## Install
8
8
 
@@ -33,13 +33,15 @@ The SDK reads no environment. By convention apps and backends name the switch an
33
33
 
34
34
  Selling the native coin needs no approval and no signature: the call carries the amount as value. It too is dry-run from the account right before the broadcast and sent with the account's own gas estimate, never the quoted limit (the provider declares `ownGasEstimate`). A dry run that reverts refuses the swap (`simulation_failed`); one the account's RPC does not answer is asked once more and then refused as `upstream_unavailable`.
35
35
 
36
+ **Monad charges the gas limit, not the gas used** (limit × price). That is one more reason every 0x call goes out with the account's own estimate rather than the quoted limit: the quoted limit is never sent, so the gas cap only decides which quotes are refused. A quote's gas limit, as the module pads it (0x's `transaction.gas` × 1.2 + 20,000, room for the appended signature), may come to at most the chain's cap: 6,000,000 on Ethereum, Base, Arbitrum, Optimism, Polygon, Avalanche and BNB Smart Chain (`ZEROEX_MAX_GAS_LIMIT`; in 0x's own terms, a quote asking for at most 4,983,334 gas), and 15,000,000 on Monad, whose table entry carries a cap of its own (`maxGasLimit`, since 0.2.0; 0x asking for at most 12,483,334). Monad needs it because its gas grows with the size of the sale, 0x splitting a large one across many pools. In the recordings of 2026-11-26 a $1–25 swap took about 1.6 times Base's gas (25 USDC → MON 435,460 against 269,610 for 25 USDC → ETH on Base; 100 MON → AUSD 453,247), but 62,000 MON → AUSD (about $660, 10 fills) took 3,970,462 and 1,000,000 MON → AUSD (about $10,700, 11 fills) 6,140,730. Under one 6,000,000 cap for every chain, live 0x sales of MON were refused from about $10,000 (2026-11-26: for 1,000,000 MON → AUSD 0x asked for 5.0–6.1 million, a padded 6.05–7.39 million — the recording `monad-mon-ausd-1m.2026-11-25` is one of them). `eth_estimateGas` of that recorded call, from the taker with its balance overridden for the call (nothing sent), came to 5,995,993 at first and to 6,107,627–6,423,555 when read again later that day (the call's deadline moved forward, Monad's RPC taking no block override), and those later reads ran out of gas at 6,000,000: the swap alone can need more than the old cap. Sales of 150,000–700,000 MON (about $1,600–7,600) sat at 82–93 % of that cap — refused or not depending on the route 0x picked, its gas moving about 20 % from one quote to the next. Under 15,000,000 those sales pass with room; a quote whose stated gas, padded, is past it is still refused (`policy_refused`, naming the chain and its cap). The cap reads 0x's `transaction.gas` as a decimal string: a quote that states none that way (absent, zero, or in another notation) carries no gas limit, so there is nothing for the cap to hold, and nothing the engine would have sent either, as it sends its own estimate. A `chains` entry may set its own `maxGasLimit`, a bigint from 1 to 30,000,000 (Monad's per-transaction gas limit), so config can raise a chain's cap but not remove the bound; an entry replaces the default whole, so a Monad entry of your own without `maxGasLimit` has the 6,000,000 cap. An EIP-7702-delegated account on Monad cannot go below 10 MON (Monad's reserve balance), so selling all of its MON does not go through; how a plain account fares on "sell all MON" has not been verified.
37
+
36
38
  ## What is checked before anything is signed
37
39
 
38
40
  **The Settler comes from the chain, not from the API.** 0x replaces its Settler contracts regularly. The module reads the Settler in force (`ownerOf(2)`) and the one it replaced (`prev(2)`) from 0x's on-chain registry `0x00000000000004533Fe15556B1E086BB1A72cEae` through your RPC, and accepts a transaction only when its target is one of the two. The answer is held to bounds the RPC cannot move:
39
41
  - it must be an address the registry deploys Settlers to — `CREATE3(registry, feature 2, this chain, nonce)`, computed on the device (`zeroExSettlerNonce`) — so an RPC cannot name an arbitrary contract or account;
40
- - that deployment must sit inside the window the chain table pins: no older than the previous Settler live when the table was pinned (`previousLiveNonce`; an older, replaced Settler is refused) and no newer than the one in force then (`newestLiveNonce`; Base: 23 and 22 since 2026-11-25, after 0x's 2026-11-24 release) plus, for a token sale, a margin of two (`ZEROEX_SETTLER_NONCE_MARGIN`);
42
+ - that deployment must sit inside the window the chain table pins: no older than the previous Settler live when the table was pinned (`previousLiveNonce`; an older, replaced Settler is refused) and no newer than the one in force then (`newestLiveNonce`; Base: 23 and 22 since 2026-11-25, after 0x's 2026-11-24 release; Monad: 12 and 11) plus, for a token sale, a margin of two (`ZEROEX_SETTLER_NONCE_MARGIN`);
41
43
  - a **native-coin sale goes only to the pinned current or previous Settler**, never into the margin: its value is sent to the address as it is, and whether a deployment inside the margin exists is only the RPC's word. A token sale may use the margin, since its permit can be spent only with the account itself as the caller;
42
- - a newer deployment is refused with what to do (update the package, or raise the pins once the deployment is checked) — native sales from the day 0x deploys it, token sales once it is past the margin. The watch job reports every new deployment (`ownerOf(2)` per chain in `watch.json`) and `verify:live` fails as long as the registry names anything but the pinned pair, so the pins are raised promptly;
44
+ - a newer deployment is refused with what to do (update the package, or raise the pins once the deployment is checked) — native sales from the day 0x deploys it, token sales once it is past the margin. The watch job reports every new deployment (`ownerOf(2)` and `prev(2)` per chain in `watch.json`; a new Settler in force is a severity-high change) and `verify:live` fails as long as the registry names anything but the pinned pair, so the pins are raised promptly;
43
45
  - there must be a contract at that address (`eth_getCode`, through the same RPC): a deployment that does not exist yet would strand what is sent to it.
44
46
 
45
47
  A live quote therefore needs `rpcUrls` for its chain. The read is cached for five minutes (`settlerMaxAgeMs`) and repeated right before the broadcast — in remote mode on the device, before the backend's own preflight is asked — so a Settler paused, replaced or removed while the review screen is open is refused with nothing sent. A live quote in remote mode is held to exactly the set its own request read, however long the backend takes, and a native sale's quote stays valid for at most two minutes (`ZEROEX_MAX_NATIVE_QUOTE_SECONDS`; a token sale's is bounded by its permit).
@@ -57,7 +59,7 @@ A live quote therefore needs `rpcUrls` for its chain. The read is cached for fiv
57
59
  - for a token sale, the first action is one of the Settler's Permit2 payments, it pulls the sold token for the input amount with the same nonce and deadline as the signed payload, and the place for the signature is the very end of the calldata;
58
60
  - for a native sale, the first action is `NATIVE_CHECK`. The Settler spends a Permit2 signature only in its first action and pulls from the caller, so this keeps an earlier, unspent permit of the account (one whose swap reverted) from being spent inside what looks like a plain native sale;
59
61
  - 0x names canonical Permit2 as `allowanceTarget` on every answer, native sales included; anything else is refused, and a native sale's transaction carries no allowance target at all;
60
- - the gas limit is bounded, and the allowance target is the canonical Permit2.
62
+ - the gas limit is held to the chain's cap (6,000,000; Monad 15,000,000), and the allowance target is the canonical Permit2.
61
63
 
62
64
  Anything else is refused, with the reason, before an approval or a signature.
63
65
 
@@ -97,6 +99,20 @@ It is empty when the registry cannot be read, so the permit is then described as
97
99
 
98
100
  0x also keeps positive slippage (the part of a fill above the quoted amount): it is not a line in the answer's fees but the calldata's `POSITIVE_SLIPPAGE` action, which sends the surplus above the quoted amount to 0x. The quoted amount and the minimum are what the checks hold the swap to.
99
101
 
102
+ ## Gas: `gasEstimate`
103
+
104
+ Every quote whose answer states gas carries `gasEstimate` with `gasEstimateSource: "venue"`: 0x's `transaction.gas` on a live quote, its `gas` on an indicative price, read as decimal digits exactly as the gas limit and the network fee read them (absent, zero or another notation: no estimate). It is for comparing routes (see protocol-swap2-core, "Gas: `gasEstimate` vs `gasLimit`"). Nothing else changes: a live quote's `txRequest.gasLimit` is still that figure × 1.2 + 20,000 and still held to the chain's cap (6,000,000; Monad 15,000,000), the estimate is never above it, and every call still goes out with the account's own estimate (`ownGasEstimate`). It counts the swap call only: a token sale's Permit2 approval, when one is sent, is priced separately by the router.
105
+
106
+ **How it compares with the gas used.** 0x documents this figure as the gas limit to send with, and it runs high. Measured 2026-11-28: 13 live quotes for a throwaway taker on Ethereum, Base, Arbitrum, Optimism, Polygon and BNB Smart Chain, each transaction run with `eth_simulateV1` right after the quote, at the chain's gas price with the module's gas limit (nothing signed or sent). A native sale was given its value by a balance override; a token sale its balance and Permit2 allowance by storage overrides, the engine's signature suffix with a dummy 65-byte signature, and an ERC-1271 stand-in on the taker so Permit2 accepts it (about 3,000 gas cheaper than the `ecrecover` an ordinary account's signature costs). Two reverted (a Metric v2 route on Arbitrum, a token sale on BNB Smart Chain); of the other 11:
107
+
108
+ | | Gas used ÷ 0x's `gas` | Gas used − 0x's `gas` |
109
+ |---|---|---|
110
+ | 11 quotes | 0.41–0.95, median 0.74 | −457,917 … −44,428, median −115,378 |
111
+ | 6 native sales | 0.69–0.88, median 0.72 | median −100,139 |
112
+ | 5 token sales | 0.41–0.95, median 0.74 | median −168,196 |
113
+
114
+ 0x's figure was above the gas used every time (the call used about three quarters of it at the median); the padded limit was never more than 78 % used. The module passes the figure on as 0x states it rather than scaling it by these numbers. The taker held none of the output, so writing its first balance is in the figures; on Arbitrum they are L2 execution gas without the L1 data component, which the router leaves out too. On Monad what is charged is the limit the account sends (its own estimate), not the gas used.
115
+
100
116
  ## Configure
101
117
 
102
118
  ```ts
@@ -125,7 +141,7 @@ const zeroex = zeroExRemoteProvider({
125
141
  | `apiKey` | none | The 0x key (local mode, servers only — refused under React Native): a getter (preferred) or a string. Without one the provider serves no route. |
126
142
  | `baseUrl` | `https://api.0x.org` | API origin (local mode), or your swap2 backend (remote mode). `https` only. |
127
143
  | `rpcUrls` | none | `{ chainId: [url…] }` — registry reads and receipts. Required for live quotes. |
128
- | `chains` | the seven chains above | Chain table: `{ chainId: { name, registry, newestLiveNonce, previousLiveNonce, wrappedNative } }` merged over the defaults; `null` removes a chain. `newestLiveNonce` and `previousLiveNonce` (required) are the Settler deployments the registry names as current and previous when you pin the entry (`pnpm verify:live` prints both): native sales go only to these two, token sales also to the next two deployments once they hold code, nothing older than the previous one. |
144
+ | `chains` | the eight chains above | Chain table: `{ chainId: { name, registry, newestLiveNonce, previousLiveNonce, wrappedNative, maxGasLimit } }` merged over the defaults; `null` removes a chain. `newestLiveNonce` and `previousLiveNonce` (required) are the Settler deployments the registry names as current and previous when you pin the entry (`pnpm verify:live` prints both): native sales go only to these two, token sales also to the next two deployments once they hold code, nothing older than the previous one. `maxGasLimit` (optional) is the chain's gas cap on the padded limit, a bigint from 1 to 30,000,000; without it, 6,000,000 (the default table sets 15,000,000 on Monad only). An entry replaces the default whole. |
129
145
  | `defaultSlippageBps` | `50` | Used when the caller passes none. Keep it the same on the backend and in the app. |
130
146
  | `quoteTtlMs` | `120000` | How long a quote is offered; never past the Permit2 deadline − 20 s, and a native sale's never past 90 s. A quote that lapses while an approval mines is re-quoted by the engine (the permit is signed once, after the approval). |
131
147
  | `timeoutMs` | `10000` | Per API request. |
@@ -165,9 +181,18 @@ Every refusal reads `zeroex: <what was found>` and reaches `onRefusal(text, info
165
181
  ```sh
166
182
  pnpm test # unit, probes, and every recorded real 0x answer (fixtures/quotes)
167
183
  ZEROEX_LIVE=1 ZEROEX_API_KEY=… pnpm test # also live quotes from api.0x.org (read-only)
168
- pnpm verify:live # registry, Settlers (code, the pinned current / previous pair), Permit2 on all seven chains; with ZEROEX_API_KEY also live corridors
184
+ pnpm verify:live # registry, Settlers (code, the pinned current / previous pair), Permit2 on all eight chains; with ZEROEX_API_KEY also live corridors
169
185
  ```
170
186
 
187
+ The recordings in `fixtures/quotes` are real 0x answers, one set per pin era (`fixtures/pin-eras.json`): 2026-11-15 on the first seven chains, 2026-11-25 on all eight (recorded 2026-11-26, when 0x still quoted the previous Settler everywhere). Each replays with its own era's chain table and registry answer (exactly the era's current and previous Settler), every era must be recorded on every one of its chains — a native-coin sale, a token sale and an indicative price — and each era's recordings are pinned by name. No era or chain may be listed as unrecorded, not even the era in force, so a pin raise lands with its recordings, which need a 0x API key and must be made while 0x still quotes the new era's Settlers.
188
+
189
+ `verify:live` reads public RPCs (`RPC_<chainId>=url[,url]` overrides one: the first URL, then the retry). A chain no RPC answers fails the run: its pins are unchecked. A read the RPC did not answer (a JSON-RPC error that is not a revert, an answer for another chain, an RPC with no state) moves to the next URL; a registry that names no Settler is read again (up to three tries) until a second answer names none too; what `ownerOf(2)` named is kept when a later read gets no answer, so a new deployment is reported as NEW even then; `ownerOf(2)` reads that disagree print a `note chain …` line. A failed run ends with `FAILED (n)` and a `Reason:` line that names every chain that is not ok, by verdict (`Reason: NEW on 1, 8453; unreachable on 143`), preceded by `Severity: high` when a sale through the Settler in force is refused today (a new deployment on a pinned chain refuses native-coin sales from the day it lands). Without `ZEROEX_API_KEY` the live corridors (including Monad MON → AUSD and USDC → MON) are skipped with a neutral line.
190
+
191
+
192
+ ## `blockNumber`
193
+
194
+ `QuoteParams.blockNumber` (one block for a comparison round) is not supported: the price comes from the 0x Swap API, so the quote names no block (`Quote.blockNumber` absent).
195
+
171
196
  ## License
172
197
 
173
198
  Apache-2.0
package/dist/activity.cjs CHANGED
@@ -32,12 +32,13 @@ var ZEROEX_SETTLER_REGISTRY = "0x00000000000004533Fe15556B1E086BB1A72cEae";
32
32
  var ZEROEX_TAKER_FEATURE = 2;
33
33
  var ZEROEX_SETTLER_NONCE_MARGIN = 2;
34
34
  var ZEROEX_SETTLER_MAX_NONCE = 1024;
35
- var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative });
35
+ var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce, maxGasLimit) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative, ...maxGasLimit !== void 0 ? { maxGasLimit } : {} });
36
36
  var ZEROEX_CHAINS = Object.freeze({
37
37
  1: chain("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 22, 21),
38
38
  10: chain("Optimism", "0x4200000000000000000000000000000000000006", 22, 21),
39
39
  56: chain("BNB Smart Chain", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 24, 23),
40
40
  137: chain("Polygon", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 21, 20),
41
+ 143: chain("Monad", "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A", 12, 11, 15000000n),
41
42
  8453: chain("Base", "0x4200000000000000000000000000000000000006", 23, 22),
42
43
  42161: chain("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 21, 20),
43
44
  43114: chain("Avalanche", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 21, 20)
@@ -148,9 +149,9 @@ function decodeSettlerExecute(data) {
148
149
 
149
150
  // src/activity.ts
150
151
  var ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
151
- function describeZeroExActivity(tx, ctx) {
152
+ function describeZeroExActivity(tx, ctx, chains = ZEROEX_CHAINS) {
152
153
  const chainId = zeroExChainId(tx.chain);
153
- const chain2 = zeroExChain(ZEROEX_CHAINS, chainId);
154
+ const chain2 = zeroExChain(chains, chainId);
154
155
  if (!chain2) return null;
155
156
  if ((0, import_activity.callSelector)(tx) !== SETTLER_EXECUTE_SELECTOR) return null;
156
157
  const target = tx.call?.to ?? tx.to;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/activity.ts","../src/chains.ts","../src/settler.ts"],"sourcesContent":["/**\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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,sBAAyD;;;ACLzD,kBAA8B;AAQvB,IAAM,0BAA0B;AAEhC,IAAM,uBAAuB;AAqC7B,IAAM,8BAA8B;AAEpC,IAAM,2BAA2B;AAExC,IAAM,QAAQ,CAAC,MAAc,eAAuB,iBAAyB,sBAC3E,OAAO,OAAO,EAAC,MAAM,UAAU,yBAAyB,iBAAiB,mBAAmB,cAAa,CAAC;AAOrG,IAAM,gBAAuD,OAAO,OAAO;AAAA,EAChF,GAAG,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EACzE,IAAI,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA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,KAAK,KAAK,iBAAiB,WAAY,OAAM,OAAO,UAAU,CAAC,2CAA2C,gBAAgB;AACvI,YAAQ,KAAK,OAAO,OAAO,EAAC,UAAU,KAAK,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,MAAM,CAAC,CAAC,IAAI,WAAW,KAAK,IAAI,eAAc,CAAC,CAAC;AAAA,EAC7H;AACA,SAAO,OAAO,OAAO,EAAC,WAAW,UAAU,cAAc,iBAAiB,SAAS,OAAO,OAAO,OAAO,GAAG,YAAY,KAAI,CAAC;AAC9H;;;AFrVO,IAAM,gBAAgB;AAEtB,SAAS,uBAAuB,IAAa,KAAmD;AACrG,QAAM,UAAU,cAAc,GAAG,KAAK;AACtC,QAAMC,SAAQ,YAAY,eAAe,OAAO;AAChD,MAAI,CAACA,OAAO,QAAO;AACnB,UAAI,8BAAa,EAAE,MAAM,yBAA0B,QAAO;AAC1D,QAAM,SAAS,GAAG,MAAM,MAAM,GAAG;AAGjC,MAAI,OAAO,WAAW,YAAY,mBAAmB,SAAS,QAAQA,OAAM,UAAUA,OAAM,kBAAkB,2BAA2B,MAAM,KAAM,QAAO;AAC5J,QAAM,OAAO,GAAG,MAAM;AACtB,MAAI,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI;AAChD,QAAI;AACF,2BAAqB,IAAI;AAAA,IAC3B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,eAAe,UAAU,eAAQ,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AACpH;","names":["import_util","chain","chain"]}
1
+ {"version":3,"sources":["../src/activity.ts","../src/chains.ts","../src/settler.ts"],"sourcesContent":["/**\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 * 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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,sBAAyD;;;ACLzD,kBAA8B;AAQvB,IAAM,0BAA0B;AAEhC,IAAM,uBAAuB;AAmD7B,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,mBAAmB,8CAA8C,IAAI,EAAE;AAAA,EACjF,KAAK,MAAM,WAAW,8CAA8C,IAAI,EAAE;AAAA,EAC1E,KAAK,MAAM,SAAS,8CAA8C,IAAI,IAAI,SAAW;AAAA,EACrF,MAAM,MAAM,QAAQ,8CAA8C,IAAI,EAAE;AAAA,EACxE,OAAO,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EAC7E,OAAO,MAAM,aAAa,8CAA8C,IAAI,EAAE;AAChF,CAAC;AA8CM,SAAS,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B,SAAS,OAAO,OAAO,OAAO,GAAG,YAAY,KAAI,CAAC;AAC9H;;;AFrVO,IAAM,gBAAgB;AAMtB,SAAS,uBAAuB,IAAa,KAA8B,SAAgD,eAAoC;AACpK,QAAM,UAAU,cAAc,GAAG,KAAK;AACtC,QAAMC,SAAQ,YAAY,QAAQ,OAAO;AACzC,MAAI,CAACA,OAAO,QAAO;AACnB,UAAI,8BAAa,EAAE,MAAM,yBAA0B,QAAO;AAC1D,QAAM,SAAS,GAAG,MAAM,MAAM,GAAG;AAGjC,MAAI,OAAO,WAAW,YAAY,mBAAmB,SAAS,QAAQA,OAAM,UAAUA,OAAM,kBAAkB,2BAA2B,MAAM,KAAM,QAAO;AAC5J,QAAM,OAAO,GAAG,MAAM;AACtB,MAAI,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI;AAChD,QAAI;AACF,2BAAqB,IAAI;AAAA,IAC3B,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACA,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,eAAe,UAAU,eAAQ,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AACpH;","names":["import_util","chain","chain"]}
@@ -1,4 +1,5 @@
1
1
  import { ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
2
+ import { ZeroExChain } from './chains.cjs';
2
3
 
3
4
  /**
4
5
  * Activity recognition for 0x: a `Settler.execute` call to a 0x Settler on a chain the module serves
@@ -13,6 +14,10 @@ import { ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/co
13
14
  */
14
15
 
15
16
  declare const ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
16
- declare function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null;
17
+ /**
18
+ * The activity item for a 0x swap, or `null`. `chains` is the chain table to read (default: the module's own); the
19
+ * providers pass the table they were built with, so a chain added or re-pinned through `chains` is labelled too.
20
+ */
21
+ declare function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext, chains?: Readonly<Record<number, ZeroExChain>>): ActivityItem | null;
17
22
 
18
23
  export { ZEROEX_MODULE, describeZeroExActivity };
@@ -1,4 +1,5 @@
1
1
  import { ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/core';
2
+ import { ZeroExChain } from './chains.js';
2
3
 
3
4
  /**
4
5
  * Activity recognition for 0x: a `Settler.execute` call to a 0x Settler on a chain the module serves
@@ -13,6 +14,10 @@ import { ChainTx, DescribeActivityContext, ActivityItem } from '@anywalletkit/co
13
14
  */
14
15
 
15
16
  declare const ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
16
- declare function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null;
17
+ /**
18
+ * The activity item for a 0x swap, or `null`. `chains` is the chain table to read (default: the module's own); the
19
+ * providers pass the table they were built with, so a chain added or re-pinned through `chains` is labelled too.
20
+ */
21
+ declare function describeZeroExActivity(tx: ChainTx, ctx: DescribeActivityContext, chains?: Readonly<Record<number, ZeroExChain>>): ActivityItem | null;
17
22
 
18
23
  export { ZEROEX_MODULE, describeZeroExActivity };
package/dist/activity.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  ZEROEX_MODULE,
3
3
  describeZeroExActivity
4
- } from "./chunk-QFOKBJXP.js";
5
- import "./chunk-NK3PQGI4.js";
6
- import "./chunk-CWZCAJBY.js";
4
+ } from "./chunk-V4HUFBY2.js";
5
+ import "./chunk-YHRPT6BS.js";
6
+ import "./chunk-AMZ5DXN2.js";
7
7
  export {
8
8
  ZEROEX_MODULE,
9
9
  describeZeroExActivity
package/dist/chains.cjs CHANGED
@@ -22,12 +22,14 @@ var chains_exports = {};
22
22
  __export(chains_exports, {
23
23
  ZEROEX_ALLOWANCE_HOLDER: () => ZEROEX_ALLOWANCE_HOLDER,
24
24
  ZEROEX_CHAINS: () => ZEROEX_CHAINS,
25
+ ZEROEX_GAS_CAP_CEILING: () => ZEROEX_GAS_CAP_CEILING,
25
26
  ZEROEX_NATIVE: () => ZEROEX_NATIVE,
26
27
  ZEROEX_PERMIT2: () => ZEROEX_PERMIT2,
27
28
  ZEROEX_SETTLER_MAX_NONCE: () => ZEROEX_SETTLER_MAX_NONCE,
28
29
  ZEROEX_SETTLER_NONCE_MARGIN: () => ZEROEX_SETTLER_NONCE_MARGIN,
29
30
  ZEROEX_SETTLER_REGISTRY: () => ZEROEX_SETTLER_REGISTRY,
30
31
  ZEROEX_TAKER_FEATURE: () => ZEROEX_TAKER_FEATURE,
32
+ isZeroExGasCap: () => isZeroExGasCap,
31
33
  zeroExChain: () => zeroExChain,
32
34
  zeroExChainId: () => zeroExChainId,
33
35
  zeroExChains: () => zeroExChains
@@ -39,14 +41,17 @@ var ZEROEX_SETTLER_REGISTRY = "0x00000000000004533Fe15556B1E086BB1A72cEae";
39
41
  var ZEROEX_TAKER_FEATURE = 2;
40
42
  var ZEROEX_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
41
43
  var ZEROEX_ALLOWANCE_HOLDER = "0x0000000000001fF3684f28c67538d4D072C22734";
44
+ var ZEROEX_GAS_CAP_CEILING = 30000000n;
45
+ var isZeroExGasCap = (v) => typeof v === "bigint" && v >= 1n && v <= ZEROEX_GAS_CAP_CEILING;
42
46
  var ZEROEX_SETTLER_NONCE_MARGIN = 2;
43
47
  var ZEROEX_SETTLER_MAX_NONCE = 1024;
44
- var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative });
48
+ var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce, maxGasLimit) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative, ...maxGasLimit !== void 0 ? { maxGasLimit } : {} });
45
49
  var ZEROEX_CHAINS = Object.freeze({
46
50
  1: chain("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 22, 21),
47
51
  10: chain("Optimism", "0x4200000000000000000000000000000000000006", 22, 21),
48
52
  56: chain("BNB Smart Chain", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 24, 23),
49
53
  137: chain("Polygon", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 21, 20),
54
+ 143: chain("Monad", "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A", 12, 11, 15000000n),
50
55
  8453: chain("Base", "0x4200000000000000000000000000000000000006", 23, 22),
51
56
  42161: chain("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 21, 20),
52
57
  43114: chain("Avalanche", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 21, 20)
@@ -75,7 +80,16 @@ function zeroExChains(overrides) {
75
80
  if (!Number.isSafeInteger(previous) || previous < 1 || previous > newest) {
76
81
  throw new Error(`zeroex: chain ${id} pins no previous live Settler deployment (previousLiveNonce, 1 to its newestLiveNonce)`);
77
82
  }
78
- out[id] = Object.freeze({ name: entry.name, registry: entry.registry, newestLiveNonce: newest, previousLiveNonce: previous, ...entry.wrappedNative ? { wrappedNative: entry.wrappedNative } : {} });
83
+ const gasCap = entry.maxGasLimit;
84
+ if (gasCap !== void 0 && !isZeroExGasCap(gasCap)) throw new Error(`zeroex: chain ${id} gas cap (maxGasLimit) is not a bigint from 1 to ${ZEROEX_GAS_CAP_CEILING}`);
85
+ out[id] = Object.freeze({
86
+ name: entry.name,
87
+ registry: entry.registry,
88
+ newestLiveNonce: newest,
89
+ previousLiveNonce: previous,
90
+ ...entry.wrappedNative ? { wrappedNative: entry.wrappedNative } : {},
91
+ ...gasCap !== void 0 ? { maxGasLimit: gasCap } : {}
92
+ });
79
93
  }
80
94
  return Object.freeze(out);
81
95
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chains.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,kBAA8B;AAGvB,IAAM,iBAAiB;AAKvB,IAAM,0BAA0B;AAEhC,IAAM,uBAAuB;AAE7B,IAAM,gBAAgB;AAEtB,IAAM,0BAA0B;AAiChC,IAAM,8BAA8B;AAEpC,IAAM,2BAA2B;AAExC,IAAM,QAAQ,CAAC,MAAc,eAAuB,iBAAyB,sBAC3E,OAAO,OAAO,EAAC,MAAM,UAAU,yBAAyB,iBAAiB,mBAAmB,cAAa,CAAC;AAOrG,IAAM,gBAAuD,OAAO,OAAO;AAAA,EAChF,GAAG,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EACzE,IAAI,MAAM,YAAY,8CAA8C,IAAI,EAAE;AAAA,EAC1E,IAAI,MAAM,mBAAmB,8CAA8C,IAAI,EAAE;AAAA,EACjF,KAAK,MAAM,WAAW,8CAA8C,IAAI,EAAE;AAAA,EAC1E,MAAM,MAAM,QAAQ,8CAA8C,IAAI,EAAE;AAAA,EACxE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,QAAI,EAAE,IAAI,OAAO,OAAO,EAAC,MAAM,MAAM,MAAM,UAAU,MAAM,UAAU,iBAAiB,QAAQ,mBAAmB,UAAU,GAAI,MAAM,gBAAgB,EAAC,eAAe,MAAM,cAAa,IAAI,CAAC,EAAE,CAAC;AAAA,EAClM;AACA,SAAO,OAAO,OAAO,GAAG;AAC1B;AAGO,SAAS,cAAc,OAAuB;AACnD,SAAO,OAAO,UAAU,YAAY,4BAA4B,KAAK,KAAK,IAAI,OAAO,MAAM,MAAM,CAAC,CAAC,IAAI;AACzG;AAGO,SAAS,YAAY,QAA+C,SAA0C;AACnH,SAAO,OAAO,cAAc,OAAO,KAAK,OAAO,UAAU,eAAe,KAAK,QAAQ,OAAO,IAAI,OAAO,OAAO,IAAI;AACpH;","names":[]}
1
+ {"version":3,"sources":["../src/chains.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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