@anywalletkit/protocol-swap2-0x 0.0.0-stage → 0.1.1

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,609 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/remote.ts
21
+ var remote_exports = {};
22
+ __export(remote_exports, {
23
+ zeroExKnownSpenders: () => zeroExKnownSpenders,
24
+ zeroExPins: () => zeroExPins,
25
+ zeroExRefusalReason: () => zeroExRefusalReason,
26
+ zeroExRemoteProvider: () => zeroExRemoteProvider,
27
+ zeroExVerifyBuild: () => zeroExVerifyBuild,
28
+ zeroExVerifyQuote: () => zeroExVerifyQuote
29
+ });
30
+ module.exports = __toCommonJS(remote_exports);
31
+ var import_viem3 = require("viem");
32
+ var import_errors3 = require("@anywalletkit/protocol-swap2-core/errors");
33
+ var import_remote = require("@anywalletkit/protocol-swap2-core/remote");
34
+ var import_util5 = require("@anywalletkit/protocol-swap2-core/util");
35
+ var import_validate2 = require("@anywalletkit/protocol-swap2-core/validate");
36
+
37
+ // src/activity.ts
38
+ var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
39
+
40
+ // src/chains.ts
41
+ var import_util = require("@anywalletkit/protocol-swap2-core/util");
42
+ var ZEROEX_PERMIT2 = import_util.PERMIT2_ADDRESS;
43
+ var ZEROEX_SETTLER_REGISTRY = "0x00000000000004533Fe15556B1E086BB1A72cEae";
44
+ var ZEROEX_TAKER_FEATURE = 2;
45
+ var ZEROEX_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
46
+ var ZEROEX_SETTLER_NONCE_MARGIN = 2;
47
+ var ZEROEX_SETTLER_MAX_NONCE = 1024;
48
+ var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative });
49
+ var ZEROEX_CHAINS = Object.freeze({
50
+ 1: chain("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 21, 20),
51
+ 10: chain("Optimism", "0x4200000000000000000000000000000000000006", 21, 20),
52
+ 56: chain("BNB Smart Chain", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 23, 22),
53
+ 137: chain("Polygon", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 20, 19),
54
+ 8453: chain("Base", "0x4200000000000000000000000000000000000006", 22, 21),
55
+ 42161: chain("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 20, 19),
56
+ 43114: chain("Avalanche", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 20, 19)
57
+ });
58
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
59
+ var ZERO_ADDRESS = /^0x0{40}$/;
60
+ function zeroExChains(overrides) {
61
+ if (!overrides) return ZEROEX_CHAINS;
62
+ const out = { ...ZEROEX_CHAINS };
63
+ for (const key of Object.keys(overrides)) {
64
+ const id = Number(key);
65
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error(`zeroex: chain id ${key.slice(0, 20)} is not a positive integer`);
66
+ const entry = overrides[id];
67
+ if (entry === null || entry === void 0) {
68
+ delete out[id];
69
+ continue;
70
+ }
71
+ if (typeof entry.name !== "string" || !entry.name) throw new Error(`zeroex: chain ${id} has no name`);
72
+ 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`);
73
+ if (entry.wrappedNative !== void 0 && (typeof entry.wrappedNative !== "string" || !ADDRESS.test(entry.wrappedNative))) throw new Error(`zeroex: chain ${id} wrapped native is not an address`);
74
+ const newest = entry.newestLiveNonce;
75
+ const previous = entry.previousLiveNonce;
76
+ if (!Number.isSafeInteger(newest) || newest < 1 || newest > ZEROEX_SETTLER_MAX_NONCE) {
77
+ throw new Error(`zeroex: chain ${id} pins no newest live Settler deployment (newestLiveNonce, 1 to ${ZEROEX_SETTLER_MAX_NONCE})`);
78
+ }
79
+ if (!Number.isSafeInteger(previous) || previous < 1 || previous > newest) {
80
+ throw new Error(`zeroex: chain ${id} pins no previous live Settler deployment (previousLiveNonce, 1 to its newestLiveNonce)`);
81
+ }
82
+ out[id] = Object.freeze({ name: entry.name, registry: entry.registry, newestLiveNonce: newest, previousLiveNonce: previous, ...entry.wrappedNative ? { wrappedNative: entry.wrappedNative } : {} });
83
+ }
84
+ return Object.freeze(out);
85
+ }
86
+ function zeroExChainId(caip2) {
87
+ return typeof caip2 === "string" && /^eip155:[1-9][0-9]{0,15}$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
88
+ }
89
+ function zeroExChain(chains, chainId) {
90
+ return Number.isSafeInteger(chainId) && Object.prototype.hasOwnProperty.call(chains, chainId) ? chains[chainId] : void 0;
91
+ }
92
+
93
+ // src/settler.ts
94
+ var import_viem = require("viem");
95
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
96
+ var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
97
+
98
+ // src/rpc.ts
99
+ var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
100
+ var RPC_TIMEOUT_MS = 12e3;
101
+ function rpcUrlsFor(rpcUrls, chainId) {
102
+ if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];
103
+ const urls = rpcUrls[chainId];
104
+ return Array.isArray(urls) ? urls.filter((u) => typeof u === "string" && u.length > 0) : [];
105
+ }
106
+ async function rpcRequest(rpcUrls, chainId, method, params) {
107
+ for (const url of rpcUrlsFor(rpcUrls, chainId)) {
108
+ try {
109
+ const res = await fetch(url, {
110
+ method: "POST",
111
+ headers: { "content-type": "application/json" },
112
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
113
+ signal: (0, import_util2.timeoutSignal)(RPC_TIMEOUT_MS)
114
+ });
115
+ if (!res.ok) continue;
116
+ const body = await res.json();
117
+ if (!body || typeof body !== "object") continue;
118
+ if (body.error) return { error: { code: body.error.code, message: typeof body.error.message === "string" ? body.error.message : "rpc error" } };
119
+ if ("result" in body) return { result: body.result ?? null };
120
+ } catch {
121
+ }
122
+ }
123
+ return null;
124
+ }
125
+ function isRevert(error) {
126
+ return error.code === 3 || /revert/i.test(error.message);
127
+ }
128
+
129
+ // src/settler.ts
130
+ var SETTLER_EXECUTE_SELECTOR = "0x1fff991f";
131
+ var REGISTRY_OWNER_OF_SELECTOR = "0x6352211e";
132
+ var REGISTRY_PREV_SELECTOR = "0xe2603dc2";
133
+ var SETTLER_NATIVE_CHECK_SELECTOR = "0xbd01c226";
134
+ var ZEROEX_MAX_PERMIT_SECONDS = 600;
135
+ var ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;
136
+ var PERMIT = "((address,uint256),uint256,uint256)";
137
+ var SETTLER_PERMIT_ACTIONS = Object.freeze({
138
+ "0xc1fb425e": Object.freeze({ name: "TRANSFER_FROM", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5 }),
139
+ "0x3036d6a6": Object.freeze({ name: "UNISWAPV3_VIP", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6 }),
140
+ "0x6a92dacb": Object.freeze({ name: "UNISWAPV4_VIP", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
141
+ "0x441d2492": Object.freeze({ name: "PANCAKE_INFINITY_VIP", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
142
+ "0x4150c86c": Object.freeze({ name: "BALANCERV3_VIP", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
143
+ "0x10cd6343": Object.freeze({ name: "EKUBOV3_VIP", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
144
+ "0x0bcce50f": Object.freeze({ name: "CURVE_TRICRYPTO_VIP", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6 })
145
+ });
146
+ var ZeroExTransactionError = class extends Error {
147
+ constructor(why, reason) {
148
+ super(`zeroex: ${why}`);
149
+ this.name = "ZeroExTransactionError";
150
+ if (reason) (0, import_errors.withReason)(this, reason);
151
+ }
152
+ };
153
+ var refuse = (why, reason) => new ZeroExTransactionError(why, reason);
154
+ var ADDRESS2 = /^0x[0-9a-fA-F]{40}$/;
155
+ var ZERO_ADDRESS2 = /^0x0{40}$/;
156
+ var same = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
157
+ var isZeroExNative = (token) => ZERO_ADDRESS2.test(token) || same(token, ZEROEX_NATIVE);
158
+ var ZEROEX_SETTLER_SHIM_INIT_HASH = "0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f";
159
+ var ZEROEX_SETTLER_LOOKAHEAD = 16;
160
+ var tokenCeiling = (chain2) => chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;
161
+ function zeroExSettlerAddress(chainId, nonce, registry = ZEROEX_SETTLER_REGISTRY) {
162
+ 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");
163
+ const salt = (0, import_viem.pad)((0, import_viem.numberToHex)(BigInt(ZEROEX_TAKER_FEATURE) << 128n | BigInt(chainId) << 64n | BigInt(nonce)), { size: 32 });
164
+ const shim = (0, import_viem.getContractAddress)({ opcode: "CREATE2", from: registry, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH });
165
+ return (0, import_viem.getContractAddress)({ opcode: "CREATE", from: shim, nonce: 1n });
166
+ }
167
+ var derived = /* @__PURE__ */ new Map();
168
+ function zeroExSettlerNonce(chainId, address, registry = ZEROEX_SETTLER_REGISTRY, maxNonce) {
169
+ if (typeof address !== "string" || !ADDRESS2.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS2.test(registry)) return null;
170
+ const pinned = zeroExChain(ZEROEX_CHAINS, chainId);
171
+ const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);
172
+ if (!Number.isSafeInteger(bound) || bound < 1) return null;
173
+ const key = `${registry.toLowerCase()}:${chainId}`;
174
+ let list = derived.get(key);
175
+ if (!list) derived.set(key, list = []);
176
+ const want = address.toLowerCase();
177
+ const hit = list.indexOf(want);
178
+ if (hit >= 0) return hit < bound ? hit + 1 : null;
179
+ while (list.length < bound) {
180
+ const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();
181
+ list.push(next);
182
+ if (next === want) return list.length;
183
+ }
184
+ return null;
185
+ }
186
+ var DEFAULT_SETTLER_MAX_AGE_MS = 5 * 6e4;
187
+ function addressWord(result) {
188
+ if (typeof result !== "string" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;
189
+ const address = `0x${result.slice(26)}`;
190
+ return ZERO_ADDRESS2.test(address) ? null : (0, import_viem.getAddress)(address);
191
+ }
192
+ function createSettlerResolver(config) {
193
+ const maxAge = config.maxAgeMs !== void 0 && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;
194
+ const now = config.now ?? Date.now;
195
+ const cache = /* @__PURE__ */ new Map();
196
+ const flights = /* @__PURE__ */ new Map();
197
+ async function call(chainId, to, data) {
198
+ if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "policy_refused");
199
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_call", [{ to, data }, "latest"]);
200
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "upstream_unavailable");
201
+ if ("error" in answer) {
202
+ if (isRevert(answer.error)) return { reverted: true };
203
+ throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
204
+ }
205
+ if (typeof answer.result !== "string") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
206
+ return { result: answer.result };
207
+ }
208
+ const withCode = /* @__PURE__ */ new Set();
209
+ async function hasCode(chainId, address) {
210
+ const key = `${chainId}:${address.toLowerCase()}`;
211
+ if (withCode.has(key)) return true;
212
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_getCode", [address, "latest"]);
213
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler's code cannot be read`, "upstream_unavailable");
214
+ 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");
215
+ if (answer.result.length <= 2) return false;
216
+ withCode.add(key);
217
+ return true;
218
+ }
219
+ async function read(chainId) {
220
+ const entry = zeroExChain(config.chains, chainId);
221
+ if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, "unsupported_pair");
222
+ const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, "0");
223
+ const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);
224
+ if ("reverted" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, "chain_halted");
225
+ const settler = addressWord(current.result);
226
+ if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, "vault_mismatch");
227
+ const oldest = entry.previousLiveNonce;
228
+ const ceiling = tokenCeiling(entry);
229
+ const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);
230
+ if (nonce === null) {
231
+ const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);
232
+ if (newer !== null) {
233
+ 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");
234
+ }
235
+ 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");
236
+ }
237
+ 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");
238
+ 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");
239
+ const settlers = [settler];
240
+ try {
241
+ const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);
242
+ const prev = "result" in previous ? addressWord(previous.result) : null;
243
+ const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;
244
+ if (prev && prevNonce !== null && prevNonce >= oldest && await hasCode(chainId, prev)) settlers.push(prev);
245
+ } catch {
246
+ }
247
+ return Object.freeze(settlers);
248
+ }
249
+ return {
250
+ async resolve(chainId, options) {
251
+ const hit = cache.get(chainId);
252
+ if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;
253
+ const running = flights.get(chainId);
254
+ if (running) return running;
255
+ const flight = read(chainId).then((settlers) => {
256
+ cache.set(chainId, { at: now(), settlers });
257
+ return settlers;
258
+ }).finally(() => {
259
+ flights.delete(chainId);
260
+ });
261
+ flights.set(chainId, flight);
262
+ return flight;
263
+ },
264
+ known(chainId) {
265
+ const hit = cache.get(chainId);
266
+ return hit && now() - hit.at <= maxAge ? hit.settlers : [];
267
+ }
268
+ };
269
+ }
270
+ var MAX_CALLDATA_BYTES = 65536;
271
+ var MAX_ACTIONS = 256;
272
+ var ACTIONS_OFFSET = 160;
273
+ function decodeSettlerExecute(data) {
274
+ if (typeof data !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse("the transaction data is not hex bytes", "policy_refused");
275
+ if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse("the transaction data is larger than any 0x swap", "policy_refused");
276
+ if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse("the transaction does not call Settler.execute", "policy_refused");
277
+ const body = data.slice(10).toLowerCase();
278
+ const bodyLength = body.length / 2;
279
+ const word = (offset) => {
280
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse("the Settler call is cut short", "policy_refused");
281
+ return body.slice(offset * 2, offset * 2 + 64);
282
+ };
283
+ const address = (offset, what) => {
284
+ const w = word(offset);
285
+ if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, "policy_refused");
286
+ return (0, import_viem.getAddress)(`0x${w.slice(24)}`);
287
+ };
288
+ const small = (offset, what) => {
289
+ const w = word(offset);
290
+ if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, "policy_refused");
291
+ return parseInt(w.slice(56), 16);
292
+ };
293
+ const recipient = address(0, "recipient");
294
+ const buyToken = address(32, "buy token");
295
+ const minAmountOut = BigInt(`0x${word(64)}`);
296
+ if (small(96, "action array offset") !== ACTIONS_OFFSET) throw refuse("the Settler call does not place its actions where the ABI does", "policy_refused");
297
+ const zidAndAffiliate = `0x${word(128)}`;
298
+ const count = small(ACTIONS_OFFSET, "action count");
299
+ if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, "policy_refused");
300
+ const table = ACTIONS_OFFSET + 32;
301
+ const actions = [];
302
+ for (let i = 0; i < count; i++) {
303
+ const offset = small(table + 32 * i, "action offset");
304
+ const at = table + offset;
305
+ if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, "policy_refused");
306
+ const declaredLength = small(at, "action length");
307
+ if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, "policy_refused");
308
+ if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, "policy_refused");
309
+ actions.push(Object.freeze({ selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength }));
310
+ }
311
+ return Object.freeze({ recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word });
312
+ }
313
+ var ZEROEX_MAX_GAS_LIMIT = 6000000n;
314
+ function checkZeroExTransaction(tx, expected) {
315
+ if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse("the swap names no EVM chain");
316
+ if (!ADDRESS2.test(expected.recipient) || ZERO_ADDRESS2.test(expected.recipient)) throw refuse("the swap names no recipient");
317
+ if (!ADDRESS2.test(expected.sellToken) || !ADDRESS2.test(expected.buyToken)) throw refuse("the swap names no sell or buy token");
318
+ if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse("the swap has no input or no minimum output");
319
+ const nativeSell = isZeroExNative(expected.sellToken);
320
+ const nativeBuy = isZeroExNative(expected.buyToken);
321
+ if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse("the swap sells and buys the same token");
322
+ if (typeof tx.to !== "string" || !ADDRESS2.test(tx.to)) throw refuse("the transaction has no target", "policy_refused");
323
+ const to = tx.to;
324
+ if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, "upstream_unavailable");
325
+ 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");
326
+ 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");
327
+ const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);
328
+ if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, "unsupported_pair");
329
+ const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));
330
+ 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");
331
+ if (typeof tx.value !== "string" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse("the transaction value is not a decimal amount", "policy_refused");
332
+ const value = BigInt(tx.value);
333
+ 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");
334
+ if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {
335
+ 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");
336
+ }
337
+ 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)) {
338
+ throw refuse("the transaction asks for more gas than any 0x swap needs", "policy_refused");
339
+ }
340
+ if (typeof tx.data !== "string") throw refuse("the transaction has no data", "policy_refused");
341
+ const execute = decodeSettlerExecute(tx.data);
342
+ if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, "recipient_mismatch");
343
+ 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");
344
+ if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, "price_check_failed");
345
+ const first = execute.actions[0];
346
+ if (nativeSell) {
347
+ if (tx.approvalAddress !== void 0) throw refuse("a native-coin sale asks for a token allowance", "policy_refused");
348
+ if (tx.permit2Transfer !== void 0) throw refuse("a native-coin sale carries a Permit2 signature request", "policy_refused");
349
+ 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");
350
+ return { execute };
351
+ }
352
+ if (typeof tx.approvalAddress !== "string" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse("the allowance target is not canonical Permit2", "vault_mismatch");
353
+ if (typeof tx.permit2Transfer !== "string") throw refuse("a token sale carries no Permit2 payload to sign", "policy_refused");
354
+ const nowMs = expected.nowMs ?? Date.now();
355
+ let permit2;
356
+ try {
357
+ permit2 = (0, import_util3.readPermit2Transfer)(tx.permit2Transfer, {
358
+ chainId: expected.chainId,
359
+ token: expected.sellToken,
360
+ amount: expected.sellAmount,
361
+ spender: to,
362
+ nowMs
363
+ });
364
+ } catch (err) {
365
+ throw refuse((err instanceof Error ? err.message : "the Permit2 payload is refused").replace(/^swap2: /, ""), (0, import_errors.refusalOf)(err)?.reason ?? "policy_refused");
366
+ }
367
+ 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");
368
+ const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : void 0;
369
+ if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, "policy_refused");
370
+ const arg = (index) => execute.word(first.argsStart + 32 * index);
371
+ 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");
372
+ if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, "policy_refused");
373
+ 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");
374
+ const sigOffset = arg(action.sigWord);
375
+ if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {
376
+ throw refuse(`${action.name} does not read its signature from the end of the data`, "policy_refused");
377
+ }
378
+ return { execute, permit2, permitAction: action.name };
379
+ }
380
+
381
+ // src/activity.ts
382
+ var ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
383
+ function describeZeroExActivity(tx, ctx) {
384
+ const chainId = zeroExChainId(tx.chain);
385
+ const chain2 = zeroExChain(ZEROEX_CHAINS, chainId);
386
+ if (!chain2) return null;
387
+ if ((0, import_activity.callSelector)(tx) !== SETTLER_EXECUTE_SELECTOR) return null;
388
+ const target = tx.call?.to ?? tx.to;
389
+ if (typeof target !== "string" || zeroExSettlerNonce(chainId, target, chain2.registry, chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN) === null) return null;
390
+ const data = tx.call?.data;
391
+ if (typeof data === "string" && data.length > 10) {
392
+ try {
393
+ decodeSettlerExecute(data);
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+ return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: ZEROEX_MODULE, subtitle: `0x \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
399
+ }
400
+
401
+ // src/provider.ts
402
+ var import_viem2 = require("viem");
403
+ var import_core = require("@anywalletkit/core");
404
+ var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
405
+ var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
406
+ var import_validate = require("@anywalletkit/protocol-swap2-core/validate");
407
+ var ZEROEX_PROVIDER = "zeroex";
408
+ var API_ERRORS = Object.freeze({
409
+ INPUT_INVALID: ["0x rejected the request as invalid", "no_route"],
410
+ SWAP_VALIDATION_FAILED: ["0x could not validate this swap", "no_route"],
411
+ TOKEN_NOT_SUPPORTED: ["0x does not support one of these tokens", "unsupported_pair"],
412
+ RECIPIENT_NOT_SUPPORTED: ["0x does not support a separate recipient for this swap", "unsupported_pair"],
413
+ USER_NOT_AUTHORIZED: ["0x does not serve this account", "unsupported_pair"],
414
+ TAKER_NOT_AUTHORIZED_FOR_TRADE: ["0x does not serve this account", "unsupported_pair"],
415
+ RECIPIENT_NOT_AUTHORIZED_FOR_TRADE: ["0x does not serve this recipient", "unsupported_pair"],
416
+ BUY_TOKEN_NOT_AUTHORIZED_FOR_TRADE: ["0x does not serve the token being bought", "unsupported_pair"],
417
+ SELL_TOKEN_NOT_AUTHORIZED_FOR_TRADE: ["0x does not serve the token being sold", "unsupported_pair"],
418
+ XSTOCKS_NOT_AUTHORIZED: ["0x does not serve this token for this account", "unsupported_pair"],
419
+ INSUFFICIENT_ASSET_LIQUIDITY: ["0x has too little liquidity for this pair and amount", "insufficient_liquidity"],
420
+ INTERNAL_SERVER_ERROR: ["0x had an internal error", "upstream_unavailable"],
421
+ UNCATEGORIZED: ["0x could not quote this swap", "no_route"]
422
+ });
423
+ var same2 = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
424
+ var sameAmount = (a, b) => /^[0-9]{1,78}$/.test(a) && /^[0-9]{1,78}$/.test(b) && BigInt(a) === BigInt(b);
425
+ async function zeroExPreflightDeposit(quote, tx, ctx) {
426
+ const quoted = quote.txRequest;
427
+ if (!quoted?.to || !quoted.data || typeof tx.to !== "string" || typeof tx.data !== "string" || !same2(tx.to, quoted.to) || !same2(tx.data, quoted.data) || !sameAmount(tx.value || "0", quoted.value ?? "0") || tx.permit2Transfer !== quoted.permit2Transfer) {
428
+ throw (0, import_errors2.refusal)("policy_refused", "zeroex: the transaction is not the quoted swap. Nothing was sent; refresh the quote.");
429
+ }
430
+ const chainId = typeof quote.intentId === "string" ? Number(quote.intentId.split(":")[1]) : NaN;
431
+ if (!zeroExChain(ctx.chains, chainId)) throw (0, import_errors2.refusal)("policy_refused", "zeroex: the quote names no chain this provider serves. Nothing was sent.");
432
+ const settlers = await ctx.resolver.resolve(chainId, { fresh: true });
433
+ if (!settlers.some((s) => same2(s, quoted.to))) {
434
+ throw (0, import_errors2.refusal)("vault_mismatch", "zeroex: the quoted 0x Settler is no longer in the on-chain registry. Nothing was sent; refresh the quote.");
435
+ }
436
+ }
437
+
438
+ // src/remote.ts
439
+ var ADDRESS3 = /^0x[0-9a-fA-F]{40}$/;
440
+ var same3 = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
441
+ var uint = (v) => typeof v === "string" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null;
442
+ var message = (e, fallback) => e instanceof Error ? e.message.replace(/^zeroex: /, "") : fallback;
443
+ var notes = (0, import_errors3.refusalNotes)();
444
+ var note = (text, reason) => (
445
+ // Noted without a valid reason, a text is unclassified (and forgets any earlier classification of the same text).
446
+ notes.note(text, reason ?? {})
447
+ );
448
+ var noteError = (e, fallback) => note(message(e, fallback), (0, import_errors3.refusalOf)(e)?.reason ?? "policy_refused");
449
+ var zeroExRefusalReason = (text) => notes.reasonOf(text);
450
+ function zeroExVerifyQuote(params, quote, ctx) {
451
+ if (quote.provider !== ZEROEX_PROVIDER) return note("the quote is not a 0x quote", "policy_refused");
452
+ if (params.sourceChain !== params.destChain) return note("0x swaps stay on one chain", "unsupported_pair");
453
+ const chainId = zeroExChainId(params.sourceChain);
454
+ const chain2 = zeroExChain(ctx.chains, chainId);
455
+ if (!chain2) return note("the chain is not in the 0x chain table", "unsupported_pair");
456
+ if (quote.intentId.replace(/~[0-9a-f]{32}$/, "").split(":").slice(0, 2).join(":") !== `zeroex:${chainId}`) return note("the intent id does not name this chain", "policy_refused");
457
+ const src = (0, import_util5.sourceAssetOf)(params);
458
+ if (!src) return note("unknown source token");
459
+ if (src.contract && !ADDRESS3.test(src.contract)) return note("the source token is not an EVM address");
460
+ if (typeof params.destToken !== "string" || !ADDRESS3.test(params.destToken)) return note("the destination token is not an EVM address");
461
+ const sellToken = src.contract ? (0, import_viem3.getAddress)(src.contract) : ZEROEX_NATIVE;
462
+ const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : (0, import_viem3.getAddress)(params.destToken);
463
+ const amountIn = uint(params.amountIn);
464
+ const quotedIn = uint(quote.sourceAmount);
465
+ const dest = uint(quote.destAmount);
466
+ const min = uint(quote.minDestAmount);
467
+ if (amountIn === null || quotedIn === null || dest === null || min === null) return note("the quote's amounts are not integers", amountIn === null ? void 0 : "upstream_unavailable");
468
+ if (quotedIn !== amountIn) return note(`the quote spends ${quotedIn}, not the ${amountIn} input`, "policy_refused");
469
+ if (min <= 0n || min > dest) return note("the quoted minimum is not between zero and the quoted output", "price_check_failed");
470
+ const bps = params.slippageBps ?? ctx.defaultSlippageBps ?? 50;
471
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return note("invalid slippage");
472
+ if (min < (0, import_validate2.slippageFloor)(dest, bps)) return note(`the quoted minimum ${min} is below ${bps} bps of the quoted output`, "price_check_failed");
473
+ if (params.minAmountOut !== void 0) {
474
+ const floor = uint(params.minAmountOut);
475
+ if (floor === null || min < floor) return note(`the quoted minimum ${min} is below the caller's floor`, floor === null ? void 0 : "price_check_failed");
476
+ }
477
+ const tx = quote.txRequest;
478
+ const dry = params.dry !== false;
479
+ if (!tx) return dry ? null : note("a live quote carries no transaction", "upstream_unavailable");
480
+ if (dry) return note("an indicative quote carries a transaction", "policy_refused");
481
+ if (tx.serializedTx !== void 0 || tx.nativeFee !== void 0) return note("the quote carries more than a Settler call", "policy_refused");
482
+ if (typeof params.destAddress !== "string" || !ADDRESS3.test(params.destAddress)) return note("a live quote needs the recipient", "recipient_mismatch");
483
+ try {
484
+ const checked = checkZeroExTransaction(tx, {
485
+ chainId,
486
+ chain: chain2,
487
+ settlers: ctx.settlers(chainId),
488
+ sellToken,
489
+ buyToken,
490
+ sellAmount: amountIn,
491
+ recipient: params.destAddress,
492
+ minBuyAmount: min,
493
+ ...ctx.nowMs !== void 0 ? { nowMs: ctx.nowMs } : {}
494
+ });
495
+ if (checked.permit2 && !(Number.isFinite(quote.validUntilMs) && BigInt(Math.ceil(quote.validUntilMs)) <= checked.permit2.deadline * 1000n)) return note("the quote outlives its Permit2 deadline", "policy_refused");
496
+ if (!checked.permit2 && !(Number.isFinite(quote.validUntilMs) && quote.validUntilMs <= (ctx.nowMs ?? Date.now()) + ZEROEX_MAX_NATIVE_QUOTE_SECONDS * 1e3)) {
497
+ return note(`the native-coin sale's quote is valid for more than ${ZEROEX_MAX_NATIVE_QUOTE_SECONDS} s`, "policy_refused");
498
+ }
499
+ } catch (e) {
500
+ return noteError(e, "the transaction is refused");
501
+ }
502
+ return null;
503
+ }
504
+ async function zeroExVerifyBuild(quote, tx, params, ctx) {
505
+ if (!params) return note("the request this quote answered is not known to the app", "policy_refused");
506
+ const quoted = quote.txRequest;
507
+ if (!quoted?.to || !quoted.data) return note("the quote carries no transaction", "policy_refused");
508
+ if (typeof tx.to !== "string" || typeof tx.data !== "string" || !same3(tx.to, quoted.to) || !same3(tx.data, quoted.data) || uint(tx.value || "0") === null || uint(tx.value || "0") !== uint(quoted.value ?? "0") || tx.chainId !== void 0 && tx.chainId !== quoted.chainId || tx.approvalAddress !== quoted.approvalAddress || tx.permit2Transfer !== quoted.permit2Transfer || tx.gasLimit !== quoted.gasLimit || tx.serializedTx !== void 0 || tx.typedData !== void 0 || tx.memo !== void 0) {
509
+ return note("the built transaction is not the quoted swap", "policy_refused");
510
+ }
511
+ let settlers;
512
+ try {
513
+ settlers = await ctx.resolver.resolve(zeroExChainId(params.sourceChain), { fresh: true });
514
+ } catch (e) {
515
+ return noteError(e, "the 0x Settler cannot be resolved");
516
+ }
517
+ return zeroExVerifyQuote({ ...params, dry: false }, quote, { ...ctx, settlers: () => settlers });
518
+ }
519
+ function zeroExPins(config = {}) {
520
+ const chains = zeroExChains(config.chains);
521
+ const resolver = config.settlerResolver ?? createSettlerResolver({ chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs });
522
+ const ctx = { chains, settlers: (chainId) => resolver.known(chainId), defaultSlippageBps: config.defaultSlippageBps };
523
+ return Object.freeze({
524
+ resolver,
525
+ chains,
526
+ callTargets: (chain2) => zeroExChain(chains, zeroExChainId(chain2)) ? resolver.known(zeroExChainId(chain2)) : [],
527
+ spenders: (chain2) => zeroExChain(chains, zeroExChainId(chain2)) ? [ZEROEX_PERMIT2] : [],
528
+ verifyQuote: (params, quote) => zeroExVerifyQuote(params, quote, ctx),
529
+ verifyBuild: (quote, tx, params) => zeroExVerifyBuild(quote, tx, params, { ...ctx, resolver }),
530
+ reasonOf: zeroExRefusalReason
531
+ });
532
+ }
533
+ var QUOTED_SET_MAX_MS = 12e4;
534
+ function zeroExRemoteProvider(options) {
535
+ const pins = zeroExPins(options);
536
+ const served = (caip2) => !!zeroExChain(pins.chains, zeroExChainId(caip2));
537
+ const checkedAgainst = /* @__PURE__ */ new WeakMap();
538
+ const quoted = /* @__PURE__ */ new Map();
539
+ const callTargets = (chain2) => {
540
+ const chainId = zeroExChainId(chain2);
541
+ const known = pins.callTargets(chain2);
542
+ const held = quoted.get(chainId);
543
+ if (!held || held.untilMs < Date.now() || !zeroExChain(pins.chains, chainId)) return known;
544
+ return [...known, ...held.settlers.filter((s) => !known.some((k) => same3(k, s)))];
545
+ };
546
+ const verifyCtx = { chains: pins.chains, settlers: (chainId) => pins.resolver.known(chainId), defaultSlippageBps: options.defaultSlippageBps };
547
+ const inner = (0, import_remote.remoteProvider)({
548
+ name: ZEROEX_PROVIDER,
549
+ baseUrl: options.baseUrl,
550
+ supportsSameChain: true,
551
+ supportsChain: served,
552
+ supportsChainPair: (from, to) => from === to && served(from),
553
+ supportsRoute: (from, to) => from.chain === to.chain && served(from.chain),
554
+ callTargets,
555
+ spenders: pins.spenders,
556
+ verifyQuote: (params, quote) => {
557
+ const set = checkedAgainst.get(params);
558
+ return zeroExVerifyQuote(params, quote, set ? { ...verifyCtx, settlers: () => set } : verifyCtx);
559
+ },
560
+ verifyBuild: pins.verifyBuild,
561
+ reasonOf: pins.reasonOf,
562
+ ...options.enabled ? { enabled: options.enabled } : {},
563
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
564
+ ...options.headers ? { headers: options.headers } : {},
565
+ ...options.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {},
566
+ ...options.allowInsecureBaseUrl !== void 0 ? { allowInsecureBaseUrl: options.allowInsecureBaseUrl } : {}
567
+ });
568
+ return {
569
+ ...inner,
570
+ describeActivity: describeZeroExActivity,
571
+ // The quoted gas limit is the backend's word: every call goes out with the account's own estimate.
572
+ ownGasEstimate: true,
573
+ settlerResolver: pins.resolver,
574
+ // The backend's preflight is its own word: the device reads the registry first (a Settler paused, replaced or
575
+ // removed while the user was on the review screen is refused here, nothing sent), then asks the backend.
576
+ async preflightDeposit(quote, tx) {
577
+ await zeroExPreflightDeposit(quote, tx, { chains: pins.chains, resolver: pins.resolver });
578
+ await inner.preflightDeposit(quote, tx);
579
+ },
580
+ async getQuote(params, signal) {
581
+ if (params.dry !== false) return inner.getQuote(params, signal);
582
+ const chainId = zeroExChainId(params.sourceChain);
583
+ const ask = async (settlers) => {
584
+ checkedAgainst.set(params, settlers);
585
+ const q = await inner.getQuote(params, signal);
586
+ if (q) quoted.set(chainId, { settlers, untilMs: Math.min(Number.isFinite(q.validUntilMs) ? q.validUntilMs : 0, Date.now() + QUOTED_SET_MAX_MS) });
587
+ return q;
588
+ };
589
+ const before = await pins.resolver.resolve(chainId);
590
+ try {
591
+ return await ask(before);
592
+ } catch (e) {
593
+ if (!(e instanceof Error) || !/is not a 0x Settler from the on-chain registry/.test(e.message)) throw e;
594
+ const after = await pins.resolver.resolve(chainId, { fresh: true });
595
+ if (after.length === before.length && after.every((s, i) => same3(s, before[i]))) throw e;
596
+ return ask(after);
597
+ }
598
+ }
599
+ };
600
+ }
601
+ async function zeroExKnownSpenders(source, chainId, label = "0x Settler") {
602
+ const resolver = "settlerResolver" in source ? source.settlerResolver : source;
603
+ try {
604
+ return Object.fromEntries((await resolver.resolve(chainId)).map((settler) => [settler, label]));
605
+ } catch {
606
+ return {};
607
+ }
608
+ }
609
+ //# sourceMappingURL=remote.cjs.map