@anywalletkit/protocol-swap2-0x 0.0.0-stage → 0.1.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 (60) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +172 -2
  3. package/dist/activity.cjs +168 -0
  4. package/dist/activity.cjs.map +1 -0
  5. package/dist/activity.d.cts +18 -0
  6. package/dist/activity.d.ts +18 -0
  7. package/dist/activity.js +11 -0
  8. package/dist/activity.js.map +1 -0
  9. package/dist/chains.cjs +88 -0
  10. package/dist/chains.cjs.map +1 -0
  11. package/dist/chains.d.cts +64 -0
  12. package/dist/chains.d.ts +64 -0
  13. package/dist/chains.js +27 -0
  14. package/dist/chains.js.map +1 -0
  15. package/dist/chunk-AOJSV3QG.js +498 -0
  16. package/dist/chunk-AOJSV3QG.js.map +1 -0
  17. package/dist/chunk-F6QOUZC7.js +24 -0
  18. package/dist/chunk-F6QOUZC7.js.map +1 -0
  19. package/dist/chunk-HDMLWKPW.js +38 -0
  20. package/dist/chunk-HDMLWKPW.js.map +1 -0
  21. package/dist/chunk-MBQ2WFQW.js +207 -0
  22. package/dist/chunk-MBQ2WFQW.js.map +1 -0
  23. package/dist/chunk-MMOBCJEO.js +68 -0
  24. package/dist/chunk-MMOBCJEO.js.map +1 -0
  25. package/dist/chunk-VSYAAW22.js +323 -0
  26. package/dist/chunk-VSYAAW22.js.map +1 -0
  27. package/dist/index.cjs +1098 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +13 -0
  30. package/dist/index.d.ts +13 -0
  31. package/dist/index.js +102 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/protocol.cjs +879 -0
  34. package/dist/protocol.cjs.map +1 -0
  35. package/dist/protocol.d.cts +20 -0
  36. package/dist/protocol.d.ts +20 -0
  37. package/dist/protocol.js +11 -0
  38. package/dist/protocol.js.map +1 -0
  39. package/dist/provider.cjs +865 -0
  40. package/dist/provider.cjs.map +1 -0
  41. package/dist/provider.d.cts +84 -0
  42. package/dist/provider.d.ts +84 -0
  43. package/dist/provider.js +18 -0
  44. package/dist/provider.js.map +1 -0
  45. package/dist/remote.cjs +609 -0
  46. package/dist/remote.cjs.map +1 -0
  47. package/dist/remote.d.cts +93 -0
  48. package/dist/remote.d.ts +93 -0
  49. package/dist/remote.js +21 -0
  50. package/dist/remote.js.map +1 -0
  51. package/dist/settler-BpRGkBVV.d.ts +196 -0
  52. package/dist/settler-KDFcfsKv.d.cts +196 -0
  53. package/dist/settler.cjs +352 -0
  54. package/dist/settler.cjs.map +1 -0
  55. package/dist/settler.d.cts +4 -0
  56. package/dist/settler.d.ts +4 -0
  57. package/dist/settler.js +42 -0
  58. package/dist/settler.js.map +1 -0
  59. package/module.json +22 -0
  60. package/package.json +98 -3
@@ -0,0 +1,323 @@
1
+ import {
2
+ ZEROEX_CHAINS,
3
+ ZEROEX_NATIVE,
4
+ ZEROEX_PERMIT2,
5
+ ZEROEX_SETTLER_MAX_NONCE,
6
+ ZEROEX_SETTLER_NONCE_MARGIN,
7
+ ZEROEX_SETTLER_REGISTRY,
8
+ ZEROEX_TAKER_FEATURE,
9
+ zeroExChain
10
+ } from "./chunk-MMOBCJEO.js";
11
+
12
+ // src/settler.ts
13
+ import { getAddress, getContractAddress, numberToHex, pad } from "viem";
14
+ import { refusalOf, withReason } from "@anywalletkit/protocol-swap2-core/errors";
15
+ import { readPermit2Transfer } from "@anywalletkit/protocol-swap2-core/util";
16
+
17
+ // src/rpc.ts
18
+ import { timeoutSignal } from "@anywalletkit/protocol-swap2-core/util";
19
+ var RPC_TIMEOUT_MS = 12e3;
20
+ function rpcUrlsFor(rpcUrls, chainId) {
21
+ if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];
22
+ const urls = rpcUrls[chainId];
23
+ return Array.isArray(urls) ? urls.filter((u) => typeof u === "string" && u.length > 0) : [];
24
+ }
25
+ async function rpcRequest(rpcUrls, chainId, method, params) {
26
+ for (const url of rpcUrlsFor(rpcUrls, chainId)) {
27
+ try {
28
+ const res = await fetch(url, {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json" },
31
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
32
+ signal: timeoutSignal(RPC_TIMEOUT_MS)
33
+ });
34
+ if (!res.ok) continue;
35
+ const body = await res.json();
36
+ if (!body || typeof body !== "object") continue;
37
+ if (body.error) return { error: { code: body.error.code, message: typeof body.error.message === "string" ? body.error.message : "rpc error" } };
38
+ if ("result" in body) return { result: body.result ?? null };
39
+ } catch {
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+ function isRevert(error) {
45
+ return error.code === 3 || /revert/i.test(error.message);
46
+ }
47
+
48
+ // src/settler.ts
49
+ var SETTLER_EXECUTE_SELECTOR = "0x1fff991f";
50
+ var REGISTRY_OWNER_OF_SELECTOR = "0x6352211e";
51
+ var REGISTRY_PREV_SELECTOR = "0xe2603dc2";
52
+ var SETTLER_NATIVE_CHECK_SELECTOR = "0xbd01c226";
53
+ var ZEROEX_MAX_PERMIT_SECONDS = 600;
54
+ var ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;
55
+ var ZEROEX_NATIVE_QUOTE_SKEW_SECONDS = 30;
56
+ var PERMIT = "((address,uint256),uint256,uint256)";
57
+ var SETTLER_PERMIT_ACTIONS = Object.freeze({
58
+ "0xc1fb425e": Object.freeze({ name: "TRANSFER_FROM", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5 }),
59
+ "0x3036d6a6": Object.freeze({ name: "UNISWAPV3_VIP", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6 }),
60
+ "0x6a92dacb": Object.freeze({ name: "UNISWAPV4_VIP", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
61
+ "0x441d2492": Object.freeze({ name: "PANCAKE_INFINITY_VIP", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
62
+ "0x4150c86c": Object.freeze({ name: "BALANCERV3_VIP", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
63
+ "0x10cd6343": Object.freeze({ name: "EKUBOV3_VIP", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
64
+ "0x0bcce50f": Object.freeze({ name: "CURVE_TRICRYPTO_VIP", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6 })
65
+ });
66
+ var ZeroExTransactionError = class extends Error {
67
+ constructor(why, reason) {
68
+ super(`zeroex: ${why}`);
69
+ this.name = "ZeroExTransactionError";
70
+ if (reason) withReason(this, reason);
71
+ }
72
+ };
73
+ var refuse = (why, reason) => new ZeroExTransactionError(why, reason);
74
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
75
+ var ZERO_ADDRESS = /^0x0{40}$/;
76
+ var same = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
77
+ var isZeroExNative = (token) => ZERO_ADDRESS.test(token) || same(token, ZEROEX_NATIVE);
78
+ var ZEROEX_SETTLER_SHIM_INIT_HASH = "0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f";
79
+ var ZEROEX_SETTLER_LOOKAHEAD = 16;
80
+ var tokenCeiling = (chain) => chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;
81
+ function zeroExSettlerAddress(chainId, nonce, registry = ZEROEX_SETTLER_REGISTRY) {
82
+ 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");
83
+ const salt = pad(numberToHex(BigInt(ZEROEX_TAKER_FEATURE) << 128n | BigInt(chainId) << 64n | BigInt(nonce)), { size: 32 });
84
+ const shim = getContractAddress({ opcode: "CREATE2", from: registry, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH });
85
+ return getContractAddress({ opcode: "CREATE", from: shim, nonce: 1n });
86
+ }
87
+ var derived = /* @__PURE__ */ new Map();
88
+ function zeroExSettlerNonce(chainId, address, registry = ZEROEX_SETTLER_REGISTRY, maxNonce) {
89
+ if (typeof address !== "string" || !ADDRESS.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS.test(registry)) return null;
90
+ const pinned = zeroExChain(ZEROEX_CHAINS, chainId);
91
+ const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);
92
+ if (!Number.isSafeInteger(bound) || bound < 1) return null;
93
+ const key = `${registry.toLowerCase()}:${chainId}`;
94
+ let list = derived.get(key);
95
+ if (!list) derived.set(key, list = []);
96
+ const want = address.toLowerCase();
97
+ const hit = list.indexOf(want);
98
+ if (hit >= 0) return hit < bound ? hit + 1 : null;
99
+ while (list.length < bound) {
100
+ const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();
101
+ list.push(next);
102
+ if (next === want) return list.length;
103
+ }
104
+ return null;
105
+ }
106
+ var DEFAULT_SETTLER_MAX_AGE_MS = 5 * 6e4;
107
+ function addressWord(result) {
108
+ if (typeof result !== "string" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;
109
+ const address = `0x${result.slice(26)}`;
110
+ return ZERO_ADDRESS.test(address) ? null : getAddress(address);
111
+ }
112
+ function createSettlerResolver(config) {
113
+ const maxAge = config.maxAgeMs !== void 0 && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;
114
+ const now = config.now ?? Date.now;
115
+ const cache = /* @__PURE__ */ new Map();
116
+ const flights = /* @__PURE__ */ new Map();
117
+ async function call(chainId, to, data) {
118
+ if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "policy_refused");
119
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_call", [{ to, data }, "latest"]);
120
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "upstream_unavailable");
121
+ if ("error" in answer) {
122
+ if (isRevert(answer.error)) return { reverted: true };
123
+ throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
124
+ }
125
+ if (typeof answer.result !== "string") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
126
+ return { result: answer.result };
127
+ }
128
+ const withCode = /* @__PURE__ */ new Set();
129
+ async function hasCode(chainId, address) {
130
+ const key = `${chainId}:${address.toLowerCase()}`;
131
+ if (withCode.has(key)) return true;
132
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_getCode", [address, "latest"]);
133
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler's code cannot be read`, "upstream_unavailable");
134
+ 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");
135
+ if (answer.result.length <= 2) return false;
136
+ withCode.add(key);
137
+ return true;
138
+ }
139
+ async function read(chainId) {
140
+ const entry = zeroExChain(config.chains, chainId);
141
+ if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, "unsupported_pair");
142
+ const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, "0");
143
+ const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);
144
+ if ("reverted" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, "chain_halted");
145
+ const settler = addressWord(current.result);
146
+ if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, "vault_mismatch");
147
+ const oldest = entry.previousLiveNonce;
148
+ const ceiling = tokenCeiling(entry);
149
+ const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);
150
+ if (nonce === null) {
151
+ const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);
152
+ if (newer !== null) {
153
+ throw refuse(`the 0x registry on chain ${chainId} names Settler deployment ${newer} (${settler}), newer than the newest this module accepts there (${ceiling}) \u2014 update @anywalletkit/protocol-swap2-0x, or raise the chain's newestLiveNonce and previousLiveNonce once that deployment is checked`, "vault_mismatch");
154
+ }
155
+ 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");
156
+ }
157
+ 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}) \u2014 a replaced Settler is not called`, "vault_mismatch");
158
+ 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");
159
+ const settlers = [settler];
160
+ try {
161
+ const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);
162
+ const prev = "result" in previous ? addressWord(previous.result) : null;
163
+ const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;
164
+ if (prev && prevNonce !== null && prevNonce >= oldest && await hasCode(chainId, prev)) settlers.push(prev);
165
+ } catch {
166
+ }
167
+ return Object.freeze(settlers);
168
+ }
169
+ return {
170
+ async resolve(chainId, options) {
171
+ const hit = cache.get(chainId);
172
+ if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;
173
+ const running = flights.get(chainId);
174
+ if (running) return running;
175
+ const flight = read(chainId).then((settlers) => {
176
+ cache.set(chainId, { at: now(), settlers });
177
+ return settlers;
178
+ }).finally(() => {
179
+ flights.delete(chainId);
180
+ });
181
+ flights.set(chainId, flight);
182
+ return flight;
183
+ },
184
+ known(chainId) {
185
+ const hit = cache.get(chainId);
186
+ return hit && now() - hit.at <= maxAge ? hit.settlers : [];
187
+ }
188
+ };
189
+ }
190
+ var MAX_CALLDATA_BYTES = 65536;
191
+ var MAX_ACTIONS = 256;
192
+ var ACTIONS_OFFSET = 160;
193
+ function decodeSettlerExecute(data) {
194
+ if (typeof data !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse("the transaction data is not hex bytes", "policy_refused");
195
+ if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse("the transaction data is larger than any 0x swap", "policy_refused");
196
+ if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse("the transaction does not call Settler.execute", "policy_refused");
197
+ const body = data.slice(10).toLowerCase();
198
+ const bodyLength = body.length / 2;
199
+ const word = (offset) => {
200
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse("the Settler call is cut short", "policy_refused");
201
+ return body.slice(offset * 2, offset * 2 + 64);
202
+ };
203
+ const address = (offset, what) => {
204
+ const w = word(offset);
205
+ if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, "policy_refused");
206
+ return getAddress(`0x${w.slice(24)}`);
207
+ };
208
+ const small = (offset, what) => {
209
+ const w = word(offset);
210
+ if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, "policy_refused");
211
+ return parseInt(w.slice(56), 16);
212
+ };
213
+ const recipient = address(0, "recipient");
214
+ const buyToken = address(32, "buy token");
215
+ const minAmountOut = BigInt(`0x${word(64)}`);
216
+ if (small(96, "action array offset") !== ACTIONS_OFFSET) throw refuse("the Settler call does not place its actions where the ABI does", "policy_refused");
217
+ const zidAndAffiliate = `0x${word(128)}`;
218
+ const count = small(ACTIONS_OFFSET, "action count");
219
+ if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, "policy_refused");
220
+ const table = ACTIONS_OFFSET + 32;
221
+ const actions = [];
222
+ for (let i = 0; i < count; i++) {
223
+ const offset = small(table + 32 * i, "action offset");
224
+ const at = table + offset;
225
+ if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, "policy_refused");
226
+ const declaredLength = small(at, "action length");
227
+ if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, "policy_refused");
228
+ if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, "policy_refused");
229
+ actions.push(Object.freeze({ selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength }));
230
+ }
231
+ return Object.freeze({ recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word });
232
+ }
233
+ var ZEROEX_MAX_GAS_LIMIT = 6000000n;
234
+ function checkZeroExTransaction(tx, expected) {
235
+ if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse("the swap names no EVM chain");
236
+ if (!ADDRESS.test(expected.recipient) || ZERO_ADDRESS.test(expected.recipient)) throw refuse("the swap names no recipient");
237
+ if (!ADDRESS.test(expected.sellToken) || !ADDRESS.test(expected.buyToken)) throw refuse("the swap names no sell or buy token");
238
+ if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse("the swap has no input or no minimum output");
239
+ const nativeSell = isZeroExNative(expected.sellToken);
240
+ const nativeBuy = isZeroExNative(expected.buyToken);
241
+ if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse("the swap sells and buys the same token");
242
+ if (typeof tx.to !== "string" || !ADDRESS.test(tx.to)) throw refuse("the transaction has no target", "policy_refused");
243
+ const to = tx.to;
244
+ if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, "upstream_unavailable");
245
+ 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");
246
+ if (tx.chainId !== void 0 && tx.chainId !== expected.chainId) throw refuse(`the transaction is for chain ${String(tx.chainId).slice(0, 20)}, not ${expected.chainId}`, "vault_mismatch");
247
+ const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);
248
+ if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, "unsupported_pair");
249
+ const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));
250
+ 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");
251
+ if (typeof tx.value !== "string" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse("the transaction value is not a decimal amount", "policy_refused");
252
+ const value = BigInt(tx.value);
253
+ 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");
254
+ if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {
255
+ throw refuse(deployment > pin.newestLiveNonce ? `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}) \u2014 a native-coin sale goes only to a pinned Settler: update @anywalletkit/protocol-swap2-0x` : `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) \u2014 a native-coin sale goes only to a pinned Settler`, "vault_mismatch");
256
+ }
257
+ if (tx.gasLimit !== void 0 && (typeof tx.gasLimit !== "string" || !/^[0-9]{1,12}$/.test(tx.gasLimit) || BigInt(tx.gasLimit) === 0n || BigInt(tx.gasLimit) > ZEROEX_MAX_GAS_LIMIT)) {
258
+ throw refuse("the transaction asks for more gas than any 0x swap needs", "policy_refused");
259
+ }
260
+ if (typeof tx.data !== "string") throw refuse("the transaction has no data", "policy_refused");
261
+ const execute = decodeSettlerExecute(tx.data);
262
+ if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, "recipient_mismatch");
263
+ 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");
264
+ if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, "price_check_failed");
265
+ const first = execute.actions[0];
266
+ if (nativeSell) {
267
+ if (tx.approvalAddress !== void 0) throw refuse("a native-coin sale asks for a token allowance", "policy_refused");
268
+ if (tx.permit2Transfer !== void 0) throw refuse("a native-coin sale carries a Permit2 signature request", "policy_refused");
269
+ 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");
270
+ return { execute };
271
+ }
272
+ if (typeof tx.approvalAddress !== "string" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse("the allowance target is not canonical Permit2", "vault_mismatch");
273
+ if (typeof tx.permit2Transfer !== "string") throw refuse("a token sale carries no Permit2 payload to sign", "policy_refused");
274
+ const nowMs = expected.nowMs ?? Date.now();
275
+ let permit2;
276
+ try {
277
+ permit2 = readPermit2Transfer(tx.permit2Transfer, {
278
+ chainId: expected.chainId,
279
+ token: expected.sellToken,
280
+ amount: expected.sellAmount,
281
+ spender: to,
282
+ nowMs
283
+ });
284
+ } catch (err) {
285
+ throw refuse((err instanceof Error ? err.message : "the Permit2 payload is refused").replace(/^swap2: /, ""), refusalOf(err)?.reason ?? "policy_refused");
286
+ }
287
+ if (permit2.deadline > BigInt(Math.floor(nowMs / 1e3) + ZEROEX_MAX_PERMIT_SECONDS)) throw refuse(`the Permit2 deadline is more than ${ZEROEX_MAX_PERMIT_SECONDS} s away`, "policy_refused");
288
+ const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : void 0;
289
+ if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, "policy_refused");
290
+ const arg = (index) => execute.word(first.argsStart + 32 * index);
291
+ 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");
292
+ if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, "policy_refused");
293
+ 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");
294
+ const sigOffset = arg(action.sigWord);
295
+ if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {
296
+ throw refuse(`${action.name} does not read its signature from the end of the data`, "policy_refused");
297
+ }
298
+ return { execute, permit2, permitAction: action.name };
299
+ }
300
+
301
+ export {
302
+ rpcUrlsFor,
303
+ rpcRequest,
304
+ SETTLER_EXECUTE_SELECTOR,
305
+ REGISTRY_OWNER_OF_SELECTOR,
306
+ REGISTRY_PREV_SELECTOR,
307
+ SETTLER_NATIVE_CHECK_SELECTOR,
308
+ ZEROEX_MAX_PERMIT_SECONDS,
309
+ ZEROEX_MAX_NATIVE_QUOTE_SECONDS,
310
+ ZEROEX_NATIVE_QUOTE_SKEW_SECONDS,
311
+ SETTLER_PERMIT_ACTIONS,
312
+ ZeroExTransactionError,
313
+ isZeroExNative,
314
+ ZEROEX_SETTLER_SHIM_INIT_HASH,
315
+ ZEROEX_SETTLER_LOOKAHEAD,
316
+ zeroExSettlerAddress,
317
+ zeroExSettlerNonce,
318
+ createSettlerResolver,
319
+ decodeSettlerExecute,
320
+ ZEROEX_MAX_GAS_LIMIT,
321
+ checkZeroExTransaction
322
+ };
323
+ //# sourceMappingURL=chunk-VSYAAW22.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/settler.ts","../src/rpc.ts"],"sourcesContent":["/**\n * The device-side checks of a 0x Permit2 swap. Nothing here trusts the API.\n *\n * - {@link createSettlerResolver}: the Settler in force is read from the pinned on-chain registry\n * (`ownerOf(2)`, and `prev(2)` for 0x's dwell time after a new deployment) — never taken from a\n * quote — and held to a CREATE3 deployment of that registry between the chain's pinned previous\n * deployment and its newest plus the margin, with code. A paused or removed feature reverts there\n * and the swap is refused.\n * - {@link decodeSettlerExecute}: a word-level reader of `Settler.execute(slippage, actions, zid)`.\n * - {@link checkZeroExTransaction}: the transaction a quote carries, held to the request — target\n * (and, for a native-coin sale, a Settler live when the chain table was pinned), value, chain,\n * method, the recipient / buy token / minimum of Settler's own slippage check, and, for a token\n * sale, the Permit2 payload (rebuilt locally by the core reader) and the first action that\n * spends it.\n *\n * Why the slippage tuple is the anchor: `execute` ends in Settler's `_checkSlippageAndTransfer`,\n * which sends the Settler's whole balance of `buyToken` to `recipient` and reverts below\n * `minAmountOut`. With the target a registry Settler, that tuple and the signed amount fixed, the\n * worst a hostile route can do is revert: the account pays at most the signed input and receives at\n * least the minimum. What the actions between do (which pools, in what order) is not checked.\n *\n * Why the first action is always checked: Settler runs a Permit2-spending action (`TRANSFER_FROM`,\n * every `*_VIP`) only at index 0, and Permit2 pulls from the caller. A token sale's action 0 must\n * therefore spend exactly the permit about to be signed, and a native-coin sale's action 0 must be\n * `NATIVE_CHECK` — otherwise an earlier, unspent permit of this account (one whose swap reverted)\n * could be spent inside a swap that looks like a plain native sale.\n *\n * Every refusal carries a `Swap2RefusalReason` (CS-13); a request this side cannot hold a\n * transaction to (no chain, recipient, tokens or amounts) is the caller's error and stays unclassified.\n */\nimport {getAddress, getContractAddress, numberToHex, pad} from \"viem\";\nimport {refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {readPermit2Transfer, type Permit2Transfer} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {ZEROEX_CHAINS, ZEROEX_NATIVE, ZEROEX_PERMIT2, ZEROEX_SETTLER_MAX_NONCE, ZEROEX_SETTLER_NONCE_MARGIN, ZEROEX_SETTLER_REGISTRY, ZEROEX_TAKER_FEATURE, zeroExChain, type ZeroExChain} from \"./chains.js\";\nimport {isRevert, rpcRequest, rpcUrlsFor, type RpcUrls} from \"./rpc.js\";\n\n/** `execute((address recipient, address buyToken, uint256 minAmountOut), bytes[] actions, bytes32 zidAndAffiliate)`. */\nexport const SETTLER_EXECUTE_SELECTOR = \"0x1fff991f\";\n/** `ownerOf(uint256)` on the registry: the Settler in force for a feature. */\nexport const REGISTRY_OWNER_OF_SELECTOR = \"0x6352211e\";\n/** `prev(uint128)` on the registry: the instance the current one replaced. */\nexport const REGISTRY_PREV_SELECTOR = \"0xe2603dc2\";\n/** `NATIVE_CHECK(uint256 deadline, uint256 msgValue)`: the action every native-coin sale opens with (no Permit2 involved). */\nexport const SETTLER_NATIVE_CHECK_SELECTOR = \"0xbd01c226\";\n/**\n * The longest a 0x permit may stay valid from now. 0x signs five minutes ahead; the core reader allows an hour for any\n * provider. A shorter window leaves less time for a permit that was published but not spent (its swap reverted).\n */\nexport const ZEROEX_MAX_PERMIT_SECONDS = 600;\n/**\n * The longest a native-coin sale's quote may stay valid from now. A token sale's quote is bounded by its permit's\n * deadline; a native sale signs nothing, so its quote is bounded here instead: the transaction goes out within this\n * window of the registry read it was checked against, or not at all.\n */\nexport const ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;\n\n/** How far inside {@link ZEROEX_MAX_NATIVE_QUOTE_SECONDS} a backend ends a native sale's quote, so an app whose clock runs behind the backend's still accepts it. */\nexport const ZEROEX_NATIVE_QUOTE_SKEW_SECONDS = 30;\n\nconst PERMIT = \"((address,uint256),uint256,uint256)\";\n/**\n * Settler actions through which a taker-submitted swap spends a Permit2 signature (`ISettlerActions.sol`), by\n * selector. Every one starts `(address recipient, PermitTransferFrom permit, …)`, so the permit sits in argument\n * words 1–4 (token, amount, nonce, deadline); `sigWord` is the head word holding the offset of `bytes sig`.\n * `RFQ_VIP` (a maker-signed order) is left out on purpose: a quote that opens with it is refused.\n */\nexport const SETTLER_PERMIT_ACTIONS: Readonly<Record<string, {name: string; signature: string; sigWord: number}>> = Object.freeze({\n \"0xc1fb425e\": Object.freeze({name: \"TRANSFER_FROM\", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5}),\n \"0x3036d6a6\": Object.freeze({name: \"UNISWAPV3_VIP\", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6}),\n \"0x6a92dacb\": Object.freeze({name: \"UNISWAPV4_VIP\", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x441d2492\": Object.freeze({name: \"PANCAKE_INFINITY_VIP\", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10}),\n \"0x4150c86c\": Object.freeze({name: \"BALANCERV3_VIP\", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x10cd6343\": Object.freeze({name: \"EKUBOV3_VIP\", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9}),\n \"0x0bcce50f\": Object.freeze({name: \"CURVE_TRICRYPTO_VIP\", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6}),\n});\n\n/** A refusal from one of the checks in this file. The message is safe to show and starts `zeroex: `; `reason` classifies it (CS-13). */\nexport class ZeroExTransactionError extends Error {\n declare readonly reason?: Swap2RefusalReason;\n constructor(why: string, reason?: Swap2RefusalReason) {\n super(`zeroex: ${why}`);\n this.name = \"ZeroExTransactionError\";\n if (reason) withReason(this, reason);\n }\n}\nconst refuse = (why: string, reason?: Swap2RefusalReason) => new ZeroExTransactionError(why, reason);\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ZERO_ADDRESS = /^0x0{40}$/;\nconst same = (a: string, b: string) => a.length === b.length && a.toLowerCase() === b.toLowerCase();\n/** The native coin, as the engine (zero address) or 0x (the `0xEeee…` sentinel) names it. */\nexport const isZeroExNative = (token: string): boolean => ZERO_ADDRESS.test(token) || same(token, ZEROEX_NATIVE);\n\n// ── which addresses are 0x Settlers at all ──────────────────────────────────\n\n/**\n * keccak256 of the CREATE3 shim (PUSH0 variant) through which the registry deploys every Settler: the registry\n * CREATE2s the shim with salt `feature << 128 | chainId << 64 | nonce`, and the shim CREATEs the Settler (nonce 1).\n */\nexport const ZEROEX_SETTLER_SHIM_INIT_HASH = \"0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f\";\n/**\n * How far past the newest deployment a chain accepts ({@link ZeroExChain.newestLiveNonce} plus the margin) the resolver\n * still derives, only to tell \"0x deployed a newer Settler than this module accepts\" (refused until the pin is raised)\n * from \"not a 0x Settler at all\".\n */\nexport const ZEROEX_SETTLER_LOOKAHEAD = 16;\n\n/** The newest deployment a token sale may use on a chain: the newest one live when pinned, plus the margin. */\nconst tokenCeiling = (chain: ZeroExChain): number => chain.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;\n\n/** The address the registry deploys taker-feature Settler number `nonce` to on `chainId` — computed, no network. */\nexport function zeroExSettlerAddress(chainId: number, nonce: number, registry: string = ZEROEX_SETTLER_REGISTRY): string {\n if (!Number.isSafeInteger(chainId) || chainId <= 0 || !Number.isSafeInteger(nonce) || nonce <= 0) throw new Error(\"zeroex: a Settler address needs a positive chain id and nonce\");\n const salt = pad(numberToHex((BigInt(ZEROEX_TAKER_FEATURE) << 128n) | (BigInt(chainId) << 64n) | BigInt(nonce)), {size: 32});\n const shim = getContractAddress({opcode: \"CREATE2\", from: registry as `0x${string}`, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH});\n return getContractAddress({opcode: \"CREATE\", from: shim, nonce: 1n});\n}\n\nconst derived = new Map<string, string[]>();\n/**\n * Which deployment of the registry's taker feature `address` is on `chainId` (its nonce), or null when it is none of\n * deployments 1…`maxNonce` — by default the newest one the default table accepts on the chain\n * ({@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}; a chain outside the table has none:\n * null). An RPC (or an API) can therefore only ever name a contract 0x's own registry deployed as a Settler — never an\n * arbitrary contract or account. Bounded by the pin, an address that is no Settler costs a few dozen derivations, not\n * a thousand. Memoized per chain.\n */\nexport function zeroExSettlerNonce(chainId: number, address: string, registry: string = ZEROEX_SETTLER_REGISTRY, maxNonce?: number): number | null {\n if (typeof address !== \"string\" || !ADDRESS.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS.test(registry)) return null;\n const pinned = zeroExChain(ZEROEX_CHAINS, chainId);\n const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);\n if (!Number.isSafeInteger(bound) || bound < 1) return null;\n const key = `${registry.toLowerCase()}:${chainId}`;\n let list = derived.get(key);\n if (!list) derived.set(key, (list = []));\n const want = address.toLowerCase();\n const hit = list.indexOf(want);\n if (hit >= 0) return hit < bound ? hit + 1 : null;\n while (list.length < bound) {\n const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();\n list.push(next);\n if (next === want) return list.length;\n }\n return null;\n}\n\n// ── the Settler in force ────────────────────────────────────────────────────\n\nexport interface SettlerResolverConfig {\n /** The chain table (registry per chain). */\n chains: Readonly<Record<number, ZeroExChain>>;\n /** JSON-RPC endpoints per EVM chain id. Without one for a chain, its Settler cannot be resolved and live quotes are refused. */\n rpcUrls?: RpcUrls | undefined;\n /** How long a registry read is reused, ms. Default 5 minutes; a miss always triggers a fresh read. */\n maxAgeMs?: number | undefined;\n /** Clock (tests). */\n now?: (() => number) | undefined;\n}\n\nexport interface SettlerResolver {\n /** The Settlers a swap on `chainId` may call: the one in force, then the one it replaced (if any). Throws when the registry cannot be read or the feature is paused. */\n resolve(chainId: number, options?: {fresh?: boolean}): Promise<readonly string[]>;\n /** The last resolved set while it is still fresh; empty otherwise. Never touches the network. */\n known(chainId: number): readonly string[];\n}\n\nconst DEFAULT_SETTLER_MAX_AGE_MS = 5 * 60_000;\n\n/** One 32-byte word that is an address (upper 12 bytes zero), as a checksummed address; null for anything else, the zero address included. */\nfunction addressWord(result: unknown): string | null {\n if (typeof result !== \"string\" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;\n const address = `0x${result.slice(26)}`;\n return ZERO_ADDRESS.test(address) ? null : getAddress(address);\n}\n\n/**\n * Reads the Settler in force from the registry and caches it per chain. The registry address comes from the chain\n * table; the answer comes from the integrator's own RPC — that RPC is what this module trusts for \"which contract\n * is 0x's Settler right now\", within hard bounds it cannot move: the answer must be a CREATE3 deployment of that\n * registry, no older than the chain's pinned {@link ZeroExChain.previousLiveNonce} and no newer than its\n * {@link ZeroExChain.newestLiveNonce} plus {@link ZEROEX_SETTLER_NONCE_MARGIN}, with code at the address (read through\n * the same RPC). Which of these a native-coin sale may use is narrower still ({@link checkZeroExTransaction}).\n */\nexport function createSettlerResolver(config: SettlerResolverConfig): SettlerResolver {\n const maxAge = config.maxAgeMs !== undefined && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;\n const now = config.now ?? Date.now;\n const cache = new Map<number, {at: number; settlers: readonly string[]}>();\n const flights = new Map<number, Promise<readonly string[]>>();\n\n /** eth_call on the registry. `{reverted: true}` when the node says the call reverted; throws when nothing answered. */\n async function call(chainId: number, to: string, data: string): Promise<{result: string} | {reverted: true}> {\n if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} — the 0x Settler cannot be resolved`, \"policy_refused\");\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_call\", [{to, data}, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler cannot be resolved`, \"upstream_unavailable\");\n // An execution revert is an answer (the feature is paused / has no instance); any other error is the endpoint failing.\n if (\"error\" in answer) {\n if (isRevert(answer.error)) return {reverted: true};\n throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n }\n if (typeof answer.result !== \"string\") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, \"upstream_unavailable\");\n return {result: answer.result};\n }\n\n /** Addresses already seen holding code (per chain): a deployed Settler's code does not go away, so it is read once. */\n const withCode = new Set<string>();\n /** Whether `address` holds contract code, read over the same RPC as the registry. Throws when nothing answered. */\n async function hasCode(chainId: number, address: string): Promise<boolean> {\n const key = `${chainId}:${address.toLowerCase()}`;\n if (withCode.has(key)) return true;\n const answer = await rpcRequest(config.rpcUrls, chainId, \"eth_getCode\", [address, \"latest\"]);\n if (!answer) throw refuse(`no RPC answered on chain ${chainId} — the 0x Settler's code cannot be read`, \"upstream_unavailable\");\n if (\"error\" in answer || typeof answer.result !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(answer.result)) throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler's code`, \"upstream_unavailable\");\n if (answer.result.length <= 2) return false;\n withCode.add(key);\n return true;\n }\n\n async function read(chainId: number): Promise<readonly string[]> {\n const entry = zeroExChain(config.chains, chainId);\n if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, \"0\");\n const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);\n if (\"reverted\" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, \"chain_halted\");\n const settler = addressWord(current.result);\n if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, \"vault_mismatch\");\n // The answer comes from one RPC: it must be a deployment the registry itself made, inside the window this module\n // pins for the chain, and a contract. A newer deployment is 0x moving on: refused, with what to do, until the pin\n // is raised (the watch job reports it the day it happens). An older one is a replaced Settler: refused.\n const oldest = entry.previousLiveNonce;\n const ceiling = tokenCeiling(entry);\n const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);\n if (nonce === null) {\n const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);\n if (newer !== null) {\n throw refuse(`the 0x registry on chain ${chainId} names Settler deployment ${newer} (${settler}), newer than the newest this module accepts there (${ceiling}) — update @anywalletkit/protocol-swap2-0x, or raise the chain's newestLiveNonce and previousLiveNonce once that deployment is checked`, \"vault_mismatch\");\n }\n throw refuse(`the RPC on chain ${chainId} names ${settler} as the 0x Settler, which is not an address the 0x registry deploys Settlers to`, \"vault_mismatch\");\n }\n if (nonce < oldest) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, older than the oldest this module accepts there (${oldest}) — a replaced Settler is not called`, \"vault_mismatch\");\n // A deployment that does not exist yet (inside the margin past the newest live one) has no code: value or tokens\n // sent there would be stranded until 0x deploys it.\n if (!(await hasCode(chainId, settler))) throw refuse(`the RPC on chain ${chainId} names ${settler} (Settler deployment ${nonce}) as the 0x Settler, but no contract is deployed there`, \"vault_mismatch\");\n const settlers = [settler];\n // The instance it replaced: 0x keeps quoting it for a while after a new deployment. No previous instance reverts;\n // one outside the pinned window, or without code, is left out.\n try {\n const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);\n const prev = \"result\" in previous ? addressWord(previous.result) : null;\n const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;\n if (prev && prevNonce !== null && prevNonce >= oldest && (await hasCode(chainId, prev))) settlers.push(prev);\n } catch {\n // The current Settler alone is a valid (stricter) answer.\n }\n return Object.freeze(settlers);\n }\n\n return {\n async resolve(chainId, options) {\n const hit = cache.get(chainId);\n if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;\n const running = flights.get(chainId);\n if (running) return running;\n const flight = read(chainId).then((settlers) => {\n cache.set(chainId, {at: now(), settlers});\n return settlers;\n }).finally(() => {\n flights.delete(chainId);\n });\n flights.set(chainId, flight);\n return flight;\n },\n known(chainId) {\n const hit = cache.get(chainId);\n return hit && now() - hit.at <= maxAge ? hit.settlers : [];\n },\n };\n}\n\n// ── Settler.execute calldata ────────────────────────────────────────────────\n\nexport interface SettlerAction {\n /** 4-byte action selector, lowercase. */\n selector: string;\n /** Byte offset, inside the `execute` arguments, of the action's first argument word. */\n argsStart: number;\n /** The action's declared byte length (selector included). The first action of a Permit2 quote declares more than is there: its signature is appended later. */\n declaredLength: number;\n}\n\nexport interface SettlerExecute {\n /** Who Settler's slippage check pays. */\n recipient: string;\n /** The token that check measures (`0xEeee…` for the native coin). */\n buyToken: string;\n /** The least `recipient` receives, or the call reverts. */\n minAmountOut: bigint;\n /** 0x's trade id and affiliate tag (not checked). */\n zidAndAffiliate: string;\n actions: readonly SettlerAction[];\n /** Bytes of arguments after the 4-byte method selector. */\n bodyLength: number;\n /** The argument word at byte `offset`, as 64 hex characters; throws when it is out of range. */\n word(offset: number): string;\n}\n\nconst MAX_CALLDATA_BYTES = 65_536;\nconst MAX_ACTIONS = 256;\nconst ACTIONS_OFFSET = 0xa0;\n\n/**\n * Read `Settler.execute(slippage, actions, zidAndAffiliate)` calldata. Strict where it matters (method, the static\n * slippage tuple, the canonical position of the action array, every action inside the data) and tolerant where\n * Settler is: the data need not be a multiple of 32 bytes, and the first action may declare a length that runs past\n * the end (0x leaves room for the Permit2 signature there).\n */\nexport function decodeSettlerExecute(data: string): SettlerExecute {\n if (typeof data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse(\"the transaction data is not hex bytes\", \"policy_refused\");\n if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse(\"the transaction data is larger than any 0x swap\", \"policy_refused\");\n if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse(\"the transaction does not call Settler.execute\", \"policy_refused\");\n const body = data.slice(10).toLowerCase();\n const bodyLength = body.length / 2;\n const word = (offset: number): string => {\n if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse(\"the Settler call is cut short\", \"policy_refused\");\n return body.slice(offset * 2, offset * 2 + 64);\n };\n const address = (offset: number, what: string): string => {\n const w = word(offset);\n if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, \"policy_refused\");\n return getAddress(`0x${w.slice(24)}`);\n };\n /** A word that must be a small non-negative integer (an offset, a length, a count). */\n const small = (offset: number, what: string): number => {\n const w = word(offset);\n if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, \"policy_refused\");\n return parseInt(w.slice(56), 16);\n };\n\n const recipient = address(0x00, \"recipient\");\n const buyToken = address(0x20, \"buy token\");\n const minAmountOut = BigInt(`0x${word(0x40)}`);\n if (small(0x60, \"action array offset\") !== ACTIONS_OFFSET) throw refuse(\"the Settler call does not place its actions where the ABI does\", \"policy_refused\");\n const zidAndAffiliate = `0x${word(0x80)}`;\n const count = small(ACTIONS_OFFSET, \"action count\");\n if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, \"policy_refused\");\n const table = ACTIONS_OFFSET + 32;\n const actions: SettlerAction[] = [];\n for (let i = 0; i < count; i++) {\n const offset = small(table + 32 * i, \"action offset\");\n const at = table + offset;\n // Past the offset table, with room for the length word and a selector.\n if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, \"policy_refused\");\n const declaredLength = small(at, \"action length\");\n if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, \"policy_refused\");\n if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, \"policy_refused\");\n actions.push(Object.freeze({selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength}));\n }\n return Object.freeze({recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word});\n}\n\n// ── the transaction, held to the request ────────────────────────────────────\n\n/** What the user asked for — the only source of truth for the checks. */\nexport interface ZeroExExpectation {\n /** EVM chain id of the swap. */\n chainId: number;\n /**\n * The chain's entry in the table in force: its pins bound the target (a token sale: `previousLiveNonce` up to\n * `newestLiveNonce` plus the margin; a native-coin sale: exactly `newestLiveNonce` or `previousLiveNonce`). Default:\n * the default table's entry for `chainId`.\n */\n chain?: ZeroExChain | undefined;\n /** Settlers resolved from the registry for that chain ({@link SettlerResolver.resolve}). */\n settlers: readonly string[];\n /** The token sold: an ERC-20 address, or the zero address / `0xEeee…` for the native coin. */\n sellToken: string;\n /** The token bought, same convention. */\n buyToken: string;\n /** Exactly the input, base units. */\n sellAmount: bigint;\n /** Who must receive the output (the user's own address unless they named another). */\n recipient: string;\n /** The least the recipient must receive — the quote's minimum, already held to the requested slippage by the caller. */\n minBuyAmount: bigint;\n /** Clock for the Permit2 deadline (tests). */\n nowMs?: number;\n}\n\n/** The transaction fields the checks read (a quote's `txRequest` or a built `UnsignedTx`). */\nexport interface ZeroExTransaction {\n to?: string | undefined;\n data?: string | undefined;\n value?: string | undefined;\n chainId?: number | undefined;\n approvalAddress?: string | undefined;\n permit2Transfer?: string | undefined;\n gasLimit?: string | undefined;\n}\n\n/**\n * The most gas a 0x swap may be given. Unused gas is refunded, but a reverting route burns up to the limit, so a\n * quote that asks for a block's worth is refused. Real Settler swaps sit well under 2 million.\n */\nexport const ZEROEX_MAX_GAS_LIMIT = 6_000_000n;\n\nexport interface ZeroExCheckedTransaction {\n execute: SettlerExecute;\n /** The locally rebuilt Permit2 payload of a token sale; absent for a native-coin sale. */\n permit2?: Permit2Transfer;\n /** Name of the Settler action that spends the Permit2 signature (token sales). */\n permitAction?: string;\n}\n\n/**\n * Hold a 0x transaction to the request, or throw {@link ZeroExTransactionError}. Checked:\n *\n * 1. `to` is one of the registry's Settlers, and a deployment inside the chain's pinned window\n * (`previousLiveNonce` … `newestLiveNonce` + {@link ZEROEX_SETTLER_NONCE_MARGIN}); `chainId`, when present, is the\n * swap's chain.\n * 2. `value` is the input for a native-coin sale and zero for a token sale; a sale that sends value goes only to the\n * chain's `newestLiveNonce` or `previousLiveNonce` deployment — Settlers that were live when the table was pinned —\n * never into the margin; a gas limit, when given, is at most {@link ZEROEX_MAX_GAS_LIMIT}.\n * 3. The method is `execute`, and its slippage tuple names the expected recipient, the requested buy token and\n * exactly the expected minimum (never zero).\n * 4. Token sale: the allowance target is canonical Permit2; the Permit2 payload passes the core reader (Permit2\n * domain on this chain, the sell token, exactly the input, this very Settler as spender) and is rebuilt locally,\n * with a deadline at most {@link ZEROEX_MAX_PERMIT_SECONDS} away; the first action is a known Permit2-spending\n * action carrying that same token, amount, nonce and deadline, and its signature slot points at the end of the\n * data, where the signature is appended.\n * 5. Native-coin sale: no allowance target, no Permit2 payload, and the first action is `NATIVE_CHECK` — the only\n * place Settler would spend a Permit2 signature holds none.\n *\n * Not checked: the actions after the first (the route), the first action's own `recipient` (where Permit2 sends the\n * input: the Settler or a pool) and `zidAndAffiliate`. Settler's slippage check bounds what they can do.\n */\nexport function checkZeroExTransaction(tx: ZeroExTransaction, expected: ZeroExExpectation): ZeroExCheckedTransaction {\n if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse(\"the swap names no EVM chain\");\n if (!ADDRESS.test(expected.recipient) || ZERO_ADDRESS.test(expected.recipient)) throw refuse(\"the swap names no recipient\");\n if (!ADDRESS.test(expected.sellToken) || !ADDRESS.test(expected.buyToken)) throw refuse(\"the swap names no sell or buy token\");\n if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse(\"the swap has no input or no minimum output\");\n const nativeSell = isZeroExNative(expected.sellToken);\n const nativeBuy = isZeroExNative(expected.buyToken);\n if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse(\"the swap sells and buys the same token\");\n\n if (typeof tx.to !== \"string\" || !ADDRESS.test(tx.to)) throw refuse(\"the transaction has no target\", \"policy_refused\");\n const to = tx.to;\n if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, \"upstream_unavailable\");\n if (!expected.settlers.some((s) => same(s, to))) throw refuse(`the transaction target ${to} is not a 0x Settler from the on-chain registry`, \"vault_mismatch\");\n if (tx.chainId !== undefined && tx.chainId !== expected.chainId) throw refuse(`the transaction is for chain ${String(tx.chainId).slice(0, 20)}, not ${expected.chainId}`, \"vault_mismatch\");\n // Whatever settler list the caller hands in, the target is held to the chain's pins: a deployment of the registry\n // between the previous one live at pin time and the newest one a token sale may use.\n const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);\n if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, \"unsupported_pair\");\n const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));\n if (deployment === null || deployment < pin.previousLiveNonce) throw refuse(`the transaction target ${to} is not a 0x Settler deployment this module accepts on chain ${expected.chainId}`, \"vault_mismatch\");\n if (typeof tx.value !== \"string\" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse(\"the transaction value is not a decimal amount\", \"policy_refused\");\n const value = BigInt(tx.value);\n if (value !== (nativeSell ? expected.sellAmount : 0n)) throw refuse(nativeSell ? \"the transaction value is not the amount being sold\" : \"the transaction sends native coin with a token sale\", \"price_check_failed\");\n // Value goes straight to the target: only to a Settler that was live when the table was pinned. A deployment inside\n // the margin may not exist yet (its code is the RPC's word) — what is sent there would be stranded, or swept by\n // whatever 0x deploys there later. Refused until the package (its pins) is updated.\n if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {\n throw refuse(deployment > pin.newestLiveNonce\n ? `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, newer than the newest one live when this module's chain table was pinned (${pin.newestLiveNonce}) — a native-coin sale goes only to a pinned Settler: update @anywalletkit/protocol-swap2-0x`\n : `the swap sends native coin to Settler deployment ${deployment} (${to}) on chain ${expected.chainId}, which was not live when this module's chain table was pinned (${pin.newestLiveNonce} and ${pin.previousLiveNonce} were) — a native-coin sale goes only to a pinned Settler`, \"vault_mismatch\");\n }\n if (tx.gasLimit !== undefined && (typeof tx.gasLimit !== \"string\" || !/^[0-9]{1,12}$/.test(tx.gasLimit) || BigInt(tx.gasLimit) === 0n || BigInt(tx.gasLimit) > ZEROEX_MAX_GAS_LIMIT)) {\n throw refuse(\"the transaction asks for more gas than any 0x swap needs\", \"policy_refused\");\n }\n if (typeof tx.data !== \"string\") throw refuse(\"the transaction has no data\", \"policy_refused\");\n\n const execute = decodeSettlerExecute(tx.data);\n if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, \"recipient_mismatch\");\n if (nativeBuy ? !same(execute.buyToken, ZEROEX_NATIVE) : !same(execute.buyToken, expected.buyToken)) throw refuse(`the swap delivers ${execute.buyToken}, not the token asked for`, \"price_check_failed\");\n if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, \"price_check_failed\");\n const first = execute.actions[0]!;\n\n if (nativeSell) {\n if (tx.approvalAddress !== undefined) throw refuse(\"a native-coin sale asks for a token allowance\", \"policy_refused\");\n if (tx.permit2Transfer !== undefined) throw refuse(\"a native-coin sale carries a Permit2 signature request\", \"policy_refused\");\n // Action 0 is where Settler would spend a Permit2 signature (any earlier, unspent permit of this account): a native\n // sale opens with NATIVE_CHECK and nothing else.\n if (first.selector !== SETTLER_NATIVE_CHECK_SELECTOR) throw refuse(`the swap's first action ${first.selector} is not the native-value check a native-coin sale opens with`, \"policy_refused\");\n return {execute};\n }\n\n if (typeof tx.approvalAddress !== \"string\" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse(\"the allowance target is not canonical Permit2\", \"vault_mismatch\");\n if (typeof tx.permit2Transfer !== \"string\") throw refuse(\"a token sale carries no Permit2 payload to sign\", \"policy_refused\");\n const nowMs = expected.nowMs ?? Date.now();\n let permit2: Permit2Transfer;\n try {\n permit2 = readPermit2Transfer(tx.permit2Transfer, {\n chainId: expected.chainId,\n token: expected.sellToken,\n amount: expected.sellAmount,\n spender: to,\n nowMs,\n });\n } catch (err) {\n throw refuse((err instanceof Error ? err.message : \"the Permit2 payload is refused\").replace(/^swap2: /, \"\"), refusalOf(err)?.reason ?? \"policy_refused\");\n }\n if (permit2.deadline > BigInt(Math.floor(nowMs / 1000) + ZEROEX_MAX_PERMIT_SECONDS)) throw refuse(`the Permit2 deadline is more than ${ZEROEX_MAX_PERMIT_SECONDS} s away`, \"policy_refused\");\n\n const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : undefined;\n if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, \"policy_refused\");\n const arg = (index: number) => execute.word(first.argsStart + 32 * index);\n // (address recipient, ((address token, uint256 amount), uint256 nonce, uint256 deadline), …): words 1–4.\n if (!/^0{24}/.test(arg(1)) || !same(`0x${arg(1).slice(24)}`, expected.sellToken)) throw refuse(`${action.name} pulls a token other than the one being sold`, \"policy_refused\");\n if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, \"policy_refused\");\n if (BigInt(`0x${arg(3)}`) !== permit2.nonce || BigInt(`0x${arg(4)}`) !== permit2.deadline) throw refuse(`${action.name} carries a different permit than the one to be signed`, \"policy_refused\");\n const sigOffset = arg(action.sigWord);\n if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {\n throw refuse(`${action.name} does not read its signature from the end of the data`, \"policy_refused\");\n }\n return {execute, permit2, permitAction: action.name};\n}\n","/**\n * Minimal JSON-RPC over the integrator's own endpoints (Hermes-safe: `timeoutSignal`, no AbortSignal.timeout).\n * The first endpoint that gives a JSON-RPC answer wins; an execution error is an answer, a transport failure is not.\n */\nimport {timeoutSignal} from \"@anywalletkit/protocol-swap2-core/util\";\n\nexport type RpcUrls = Readonly<Record<number, readonly string[]>>;\nexport type RpcAnswer = {result: unknown} | {error: {code: unknown; message: string}};\n\nconst RPC_TIMEOUT_MS = 12_000;\n\n/** The endpoints configured for `chainId` (own property only). */\nexport function rpcUrlsFor(rpcUrls: RpcUrls | undefined, chainId: number): readonly string[] {\n if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];\n const urls = rpcUrls[chainId];\n return Array.isArray(urls) ? urls.filter((u): u is string => typeof u === \"string\" && u.length > 0) : [];\n}\n\n/** One request; null when no endpoint is configured or none answered. */\nexport async function rpcRequest(rpcUrls: RpcUrls | undefined, chainId: number, method: string, params: unknown[]): Promise<RpcAnswer | null> {\n for (const url of rpcUrlsFor(rpcUrls, chainId)) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}),\n signal: timeoutSignal(RPC_TIMEOUT_MS),\n });\n if (!res.ok) continue;\n const body = (await res.json()) as {result?: unknown; error?: {code?: unknown; message?: unknown} | null} | null;\n if (!body || typeof body !== \"object\") continue;\n if (body.error) return {error: {code: body.error.code, message: typeof body.error.message === \"string\" ? body.error.message : \"rpc error\"}};\n if (\"result\" in body) return {result: body.result ?? null};\n } catch {\n // next endpoint\n }\n }\n return null;\n}\n\n/** Whether a JSON-RPC error says the call itself reverted (as opposed to the endpoint failing). */\nexport function isRevert(error: {code: unknown; message: string}): boolean {\n return error.code === 3 || /revert/i.test(error.message);\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,SAAQ,YAAY,oBAAoB,aAAa,WAAU;AAC/D,SAAQ,WAAW,kBAA0C;AAC7D,SAAQ,2BAAgD;;;AC5BxD,SAAQ,qBAAoB;AAK5B,IAAM,iBAAiB;AAGhB,SAAS,WAAW,SAA8B,SAAoC;AAC3F,MAAI,CAAC,WAAW,CAAC,OAAO,UAAU,eAAe,KAAK,SAAS,OAAO,EAAG,QAAO,CAAC;AACjF,QAAM,OAAO,QAAQ,OAAO;AAC5B,SAAO,MAAM,QAAQ,IAAI,IAAI,KAAK,OAAO,CAAC,MAAmB,OAAO,MAAM,YAAY,EAAE,SAAS,CAAC,IAAI,CAAC;AACzG;AAGA,eAAsB,WAAW,SAA8B,SAAiB,QAAgB,QAA8C;AAC5I,aAAW,OAAO,WAAW,SAAS,OAAO,GAAG;AAC9C,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,KAAK;AAAA,QAC3B,QAAQ;AAAA,QACR,SAAS,EAAC,gBAAgB,mBAAkB;AAAA,QAC5C,MAAM,KAAK,UAAU,EAAC,SAAS,OAAO,IAAI,GAAG,QAAQ,OAAM,CAAC;AAAA,QAC5D,QAAQ,cAAc,cAAc;AAAA,MACtC,CAAC;AACD,UAAI,CAAC,IAAI,GAAI;AACb,YAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,UAAI,CAAC,QAAQ,OAAO,SAAS,SAAU;AACvC,UAAI,KAAK,MAAO,QAAO,EAAC,OAAO,EAAC,MAAM,KAAK,MAAM,MAAM,SAAS,OAAO,KAAK,MAAM,YAAY,WAAW,KAAK,MAAM,UAAU,YAAW,EAAC;AAC1I,UAAI,YAAY,KAAM,QAAO,EAAC,QAAQ,KAAK,UAAU,KAAI;AAAA,IAC3D,QAAQ;AAAA,IAER;AAAA,E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