@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,879 @@
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/protocol.ts
21
+ var protocol_exports = {};
22
+ __export(protocol_exports, {
23
+ ZeroExSwap2Protocol: () => ZeroExSwap2Protocol
24
+ });
25
+ module.exports = __toCommonJS(protocol_exports);
26
+ var import_single = require("@anywalletkit/protocol-swap2-core/swap2/single");
27
+
28
+ // src/provider.ts
29
+ var import_viem2 = require("viem");
30
+ var import_core = require("@anywalletkit/core");
31
+ var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
32
+ var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
33
+ var import_validate = require("@anywalletkit/protocol-swap2-core/validate");
34
+
35
+ // src/activity.ts
36
+ var import_activity = require("@anywalletkit/protocol-swap2-core/activity");
37
+
38
+ // src/chains.ts
39
+ var import_util = require("@anywalletkit/protocol-swap2-core/util");
40
+ var ZEROEX_PERMIT2 = import_util.PERMIT2_ADDRESS;
41
+ var ZEROEX_SETTLER_REGISTRY = "0x00000000000004533Fe15556B1E086BB1A72cEae";
42
+ var ZEROEX_TAKER_FEATURE = 2;
43
+ var ZEROEX_NATIVE = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
44
+ var ZEROEX_SETTLER_NONCE_MARGIN = 2;
45
+ var ZEROEX_SETTLER_MAX_NONCE = 1024;
46
+ var chain = (name, wrappedNative, newestLiveNonce, previousLiveNonce) => Object.freeze({ name, registry: ZEROEX_SETTLER_REGISTRY, newestLiveNonce, previousLiveNonce, wrappedNative });
47
+ var ZEROEX_CHAINS = Object.freeze({
48
+ 1: chain("Ethereum", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", 21, 20),
49
+ 10: chain("Optimism", "0x4200000000000000000000000000000000000006", 21, 20),
50
+ 56: chain("BNB Smart Chain", "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", 23, 22),
51
+ 137: chain("Polygon", "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", 20, 19),
52
+ 8453: chain("Base", "0x4200000000000000000000000000000000000006", 22, 21),
53
+ 42161: chain("Arbitrum", "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1", 20, 19),
54
+ 43114: chain("Avalanche", "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", 20, 19)
55
+ });
56
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
57
+ var ZERO_ADDRESS = /^0x0{40}$/;
58
+ function zeroExChains(overrides) {
59
+ if (!overrides) return ZEROEX_CHAINS;
60
+ const out = { ...ZEROEX_CHAINS };
61
+ for (const key of Object.keys(overrides)) {
62
+ const id = Number(key);
63
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error(`zeroex: chain id ${key.slice(0, 20)} is not a positive integer`);
64
+ const entry = overrides[id];
65
+ if (entry === null || entry === void 0) {
66
+ delete out[id];
67
+ continue;
68
+ }
69
+ if (typeof entry.name !== "string" || !entry.name) throw new Error(`zeroex: chain ${id} has no name`);
70
+ 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`);
71
+ 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`);
72
+ const newest = entry.newestLiveNonce;
73
+ const previous = entry.previousLiveNonce;
74
+ if (!Number.isSafeInteger(newest) || newest < 1 || newest > ZEROEX_SETTLER_MAX_NONCE) {
75
+ throw new Error(`zeroex: chain ${id} pins no newest live Settler deployment (newestLiveNonce, 1 to ${ZEROEX_SETTLER_MAX_NONCE})`);
76
+ }
77
+ if (!Number.isSafeInteger(previous) || previous < 1 || previous > newest) {
78
+ throw new Error(`zeroex: chain ${id} pins no previous live Settler deployment (previousLiveNonce, 1 to its newestLiveNonce)`);
79
+ }
80
+ out[id] = Object.freeze({ name: entry.name, registry: entry.registry, newestLiveNonce: newest, previousLiveNonce: previous, ...entry.wrappedNative ? { wrappedNative: entry.wrappedNative } : {} });
81
+ }
82
+ return Object.freeze(out);
83
+ }
84
+ function zeroExChainId(caip2) {
85
+ return typeof caip2 === "string" && /^eip155:[1-9][0-9]{0,15}$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
86
+ }
87
+ function zeroExChain(chains, chainId) {
88
+ return Number.isSafeInteger(chainId) && Object.prototype.hasOwnProperty.call(chains, chainId) ? chains[chainId] : void 0;
89
+ }
90
+
91
+ // src/settler.ts
92
+ var import_viem = require("viem");
93
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
94
+ var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
95
+
96
+ // src/rpc.ts
97
+ var import_util2 = require("@anywalletkit/protocol-swap2-core/util");
98
+ var RPC_TIMEOUT_MS = 12e3;
99
+ function rpcUrlsFor(rpcUrls, chainId) {
100
+ if (!rpcUrls || !Object.prototype.hasOwnProperty.call(rpcUrls, chainId)) return [];
101
+ const urls = rpcUrls[chainId];
102
+ return Array.isArray(urls) ? urls.filter((u) => typeof u === "string" && u.length > 0) : [];
103
+ }
104
+ async function rpcRequest(rpcUrls, chainId, method, params) {
105
+ for (const url of rpcUrlsFor(rpcUrls, chainId)) {
106
+ try {
107
+ const res = await fetch(url, {
108
+ method: "POST",
109
+ headers: { "content-type": "application/json" },
110
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
111
+ signal: (0, import_util2.timeoutSignal)(RPC_TIMEOUT_MS)
112
+ });
113
+ if (!res.ok) continue;
114
+ const body = await res.json();
115
+ if (!body || typeof body !== "object") continue;
116
+ if (body.error) return { error: { code: body.error.code, message: typeof body.error.message === "string" ? body.error.message : "rpc error" } };
117
+ if ("result" in body) return { result: body.result ?? null };
118
+ } catch {
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ function isRevert(error) {
124
+ return error.code === 3 || /revert/i.test(error.message);
125
+ }
126
+
127
+ // src/settler.ts
128
+ var SETTLER_EXECUTE_SELECTOR = "0x1fff991f";
129
+ var REGISTRY_OWNER_OF_SELECTOR = "0x6352211e";
130
+ var REGISTRY_PREV_SELECTOR = "0xe2603dc2";
131
+ var SETTLER_NATIVE_CHECK_SELECTOR = "0xbd01c226";
132
+ var ZEROEX_MAX_PERMIT_SECONDS = 600;
133
+ var ZEROEX_MAX_NATIVE_QUOTE_SECONDS = 120;
134
+ var ZEROEX_NATIVE_QUOTE_SKEW_SECONDS = 30;
135
+ var PERMIT = "((address,uint256),uint256,uint256)";
136
+ var SETTLER_PERMIT_ACTIONS = Object.freeze({
137
+ "0xc1fb425e": Object.freeze({ name: "TRANSFER_FROM", signature: `TRANSFER_FROM(address,${PERMIT},bytes)`, sigWord: 5 }),
138
+ "0x3036d6a6": Object.freeze({ name: "UNISWAPV3_VIP", signature: `UNISWAPV3_VIP(address,${PERMIT},bytes,bytes,uint256)`, sigWord: 6 }),
139
+ "0x6a92dacb": Object.freeze({ name: "UNISWAPV4_VIP", signature: `UNISWAPV4_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
140
+ "0x441d2492": Object.freeze({ name: "PANCAKE_INFINITY_VIP", signature: `PANCAKE_INFINITY_VIP(address,${PERMIT},uint8,bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 10 }),
141
+ "0x4150c86c": Object.freeze({ name: "BALANCERV3_VIP", signature: `BALANCERV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
142
+ "0x10cd6343": Object.freeze({ name: "EKUBOV3_VIP", signature: `EKUBOV3_VIP(address,${PERMIT},bool,uint256,uint256,bytes,bytes,uint256)`, sigWord: 9 }),
143
+ "0x0bcce50f": Object.freeze({ name: "CURVE_TRICRYPTO_VIP", signature: `CURVE_TRICRYPTO_VIP(address,${PERMIT},uint80,bytes,uint256)`, sigWord: 6 })
144
+ });
145
+ var ZeroExTransactionError = class extends Error {
146
+ constructor(why, reason) {
147
+ super(`zeroex: ${why}`);
148
+ this.name = "ZeroExTransactionError";
149
+ if (reason) (0, import_errors.withReason)(this, reason);
150
+ }
151
+ };
152
+ var refuse = (why, reason) => new ZeroExTransactionError(why, reason);
153
+ var ADDRESS2 = /^0x[0-9a-fA-F]{40}$/;
154
+ var ZERO_ADDRESS2 = /^0x0{40}$/;
155
+ var same = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
156
+ var isZeroExNative = (token) => ZERO_ADDRESS2.test(token) || same(token, ZEROEX_NATIVE);
157
+ var ZEROEX_SETTLER_SHIM_INIT_HASH = "0x3bf3f97f0be1e2c00023033eefeb4fc062ac552ff36778b17060d90b6764902f";
158
+ var ZEROEX_SETTLER_LOOKAHEAD = 16;
159
+ var tokenCeiling = (chain2) => chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN;
160
+ function zeroExSettlerAddress(chainId, nonce, registry = ZEROEX_SETTLER_REGISTRY) {
161
+ 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");
162
+ const salt = (0, import_viem.pad)((0, import_viem.numberToHex)(BigInt(ZEROEX_TAKER_FEATURE) << 128n | BigInt(chainId) << 64n | BigInt(nonce)), { size: 32 });
163
+ const shim = (0, import_viem.getContractAddress)({ opcode: "CREATE2", from: registry, salt, bytecodeHash: ZEROEX_SETTLER_SHIM_INIT_HASH });
164
+ return (0, import_viem.getContractAddress)({ opcode: "CREATE", from: shim, nonce: 1n });
165
+ }
166
+ var derived = /* @__PURE__ */ new Map();
167
+ function zeroExSettlerNonce(chainId, address, registry = ZEROEX_SETTLER_REGISTRY, maxNonce) {
168
+ if (typeof address !== "string" || !ADDRESS2.test(address) || !Number.isSafeInteger(chainId) || chainId <= 0 || !ADDRESS2.test(registry)) return null;
169
+ const pinned = zeroExChain(ZEROEX_CHAINS, chainId);
170
+ const bound = Math.min(maxNonce ?? (pinned ? tokenCeiling(pinned) : 0), ZEROEX_SETTLER_MAX_NONCE + ZEROEX_SETTLER_NONCE_MARGIN + ZEROEX_SETTLER_LOOKAHEAD);
171
+ if (!Number.isSafeInteger(bound) || bound < 1) return null;
172
+ const key = `${registry.toLowerCase()}:${chainId}`;
173
+ let list = derived.get(key);
174
+ if (!list) derived.set(key, list = []);
175
+ const want = address.toLowerCase();
176
+ const hit = list.indexOf(want);
177
+ if (hit >= 0) return hit < bound ? hit + 1 : null;
178
+ while (list.length < bound) {
179
+ const next = zeroExSettlerAddress(chainId, list.length + 1, registry).toLowerCase();
180
+ list.push(next);
181
+ if (next === want) return list.length;
182
+ }
183
+ return null;
184
+ }
185
+ var DEFAULT_SETTLER_MAX_AGE_MS = 5 * 6e4;
186
+ function addressWord(result) {
187
+ if (typeof result !== "string" || !/^0x0{24}[0-9a-fA-F]{40}$/.test(result)) return null;
188
+ const address = `0x${result.slice(26)}`;
189
+ return ZERO_ADDRESS2.test(address) ? null : (0, import_viem.getAddress)(address);
190
+ }
191
+ function createSettlerResolver(config) {
192
+ const maxAge = config.maxAgeMs !== void 0 && Number.isFinite(config.maxAgeMs) && config.maxAgeMs >= 0 ? config.maxAgeMs : DEFAULT_SETTLER_MAX_AGE_MS;
193
+ const now = config.now ?? Date.now;
194
+ const cache = /* @__PURE__ */ new Map();
195
+ const flights = /* @__PURE__ */ new Map();
196
+ async function call(chainId, to, data) {
197
+ if (!rpcUrlsFor(config.rpcUrls, chainId).length) throw refuse(`no RPC is configured for chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "policy_refused");
198
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_call", [{ to, data }, "latest"]);
199
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler cannot be resolved`, "upstream_unavailable");
200
+ if ("error" in answer) {
201
+ if (isRevert(answer.error)) return { reverted: true };
202
+ throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
203
+ }
204
+ if (typeof answer.result !== "string") throw refuse(`the RPC on chain ${chainId} could not read the 0x Settler registry`, "upstream_unavailable");
205
+ return { result: answer.result };
206
+ }
207
+ const withCode = /* @__PURE__ */ new Set();
208
+ async function hasCode(chainId, address) {
209
+ const key = `${chainId}:${address.toLowerCase()}`;
210
+ if (withCode.has(key)) return true;
211
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_getCode", [address, "latest"]);
212
+ if (!answer) throw refuse(`no RPC answered on chain ${chainId} \u2014 the 0x Settler's code cannot be read`, "upstream_unavailable");
213
+ 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");
214
+ if (answer.result.length <= 2) return false;
215
+ withCode.add(key);
216
+ return true;
217
+ }
218
+ async function read(chainId) {
219
+ const entry = zeroExChain(config.chains, chainId);
220
+ if (!entry) throw refuse(`chain ${chainId} is not in the 0x chain table`, "unsupported_pair");
221
+ const feature = ZEROEX_TAKER_FEATURE.toString(16).padStart(64, "0");
222
+ const current = await call(chainId, entry.registry, `${REGISTRY_OWNER_OF_SELECTOR}${feature}`);
223
+ if ("reverted" in current) throw refuse(`the 0x Settler registry on chain ${chainId} reports no taker Settler in force (paused or removed)`, "chain_halted");
224
+ const settler = addressWord(current.result);
225
+ if (!settler) throw refuse(`the 0x Settler registry on chain ${chainId} answered something that is not an address`, "vault_mismatch");
226
+ const oldest = entry.previousLiveNonce;
227
+ const ceiling = tokenCeiling(entry);
228
+ const nonce = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling);
229
+ if (nonce === null) {
230
+ const newer = zeroExSettlerNonce(chainId, settler, entry.registry, ceiling + ZEROEX_SETTLER_LOOKAHEAD);
231
+ if (newer !== null) {
232
+ 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");
233
+ }
234
+ 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");
235
+ }
236
+ 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");
237
+ 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");
238
+ const settlers = [settler];
239
+ try {
240
+ const previous = await call(chainId, entry.registry, `${REGISTRY_PREV_SELECTOR}${feature}`);
241
+ const prev = "result" in previous ? addressWord(previous.result) : null;
242
+ const prevNonce = prev && !same(prev, settler) ? zeroExSettlerNonce(chainId, prev, entry.registry, ceiling) : null;
243
+ if (prev && prevNonce !== null && prevNonce >= oldest && await hasCode(chainId, prev)) settlers.push(prev);
244
+ } catch {
245
+ }
246
+ return Object.freeze(settlers);
247
+ }
248
+ return {
249
+ async resolve(chainId, options) {
250
+ const hit = cache.get(chainId);
251
+ if (!options?.fresh && hit && now() - hit.at <= maxAge) return hit.settlers;
252
+ const running = flights.get(chainId);
253
+ if (running) return running;
254
+ const flight = read(chainId).then((settlers) => {
255
+ cache.set(chainId, { at: now(), settlers });
256
+ return settlers;
257
+ }).finally(() => {
258
+ flights.delete(chainId);
259
+ });
260
+ flights.set(chainId, flight);
261
+ return flight;
262
+ },
263
+ known(chainId) {
264
+ const hit = cache.get(chainId);
265
+ return hit && now() - hit.at <= maxAge ? hit.settlers : [];
266
+ }
267
+ };
268
+ }
269
+ var MAX_CALLDATA_BYTES = 65536;
270
+ var MAX_ACTIONS = 256;
271
+ var ACTIONS_OFFSET = 160;
272
+ function decodeSettlerExecute(data) {
273
+ if (typeof data !== "string" || !/^0x(?:[0-9a-fA-F]{2})*$/.test(data)) throw refuse("the transaction data is not hex bytes", "policy_refused");
274
+ if (data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw refuse("the transaction data is larger than any 0x swap", "policy_refused");
275
+ if (data.length < 10 || data.slice(0, 10).toLowerCase() !== SETTLER_EXECUTE_SELECTOR) throw refuse("the transaction does not call Settler.execute", "policy_refused");
276
+ const body = data.slice(10).toLowerCase();
277
+ const bodyLength = body.length / 2;
278
+ const word = (offset) => {
279
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + 32 > bodyLength) throw refuse("the Settler call is cut short", "policy_refused");
280
+ return body.slice(offset * 2, offset * 2 + 64);
281
+ };
282
+ const address = (offset, what) => {
283
+ const w = word(offset);
284
+ if (!/^0{24}/.test(w)) throw refuse(`the Settler call's ${what} is not an address`, "policy_refused");
285
+ return (0, import_viem.getAddress)(`0x${w.slice(24)}`);
286
+ };
287
+ const small = (offset, what) => {
288
+ const w = word(offset);
289
+ if (!/^0{56}/.test(w)) throw refuse(`the Settler call's ${what} is out of range`, "policy_refused");
290
+ return parseInt(w.slice(56), 16);
291
+ };
292
+ const recipient = address(0, "recipient");
293
+ const buyToken = address(32, "buy token");
294
+ const minAmountOut = BigInt(`0x${word(64)}`);
295
+ if (small(96, "action array offset") !== ACTIONS_OFFSET) throw refuse("the Settler call does not place its actions where the ABI does", "policy_refused");
296
+ const zidAndAffiliate = `0x${word(128)}`;
297
+ const count = small(ACTIONS_OFFSET, "action count");
298
+ if (count < 1 || count > MAX_ACTIONS) throw refuse(`the Settler call carries ${count} actions`, "policy_refused");
299
+ const table = ACTIONS_OFFSET + 32;
300
+ const actions = [];
301
+ for (let i = 0; i < count; i++) {
302
+ const offset = small(table + 32 * i, "action offset");
303
+ const at = table + offset;
304
+ if (offset < 32 * count || at + 36 > bodyLength) throw refuse(`action ${i} of the Settler call lies outside the data`, "policy_refused");
305
+ const declaredLength = small(at, "action length");
306
+ if (declaredLength < 4) throw refuse(`action ${i} of the Settler call has no selector`, "policy_refused");
307
+ if (i > 0 && at + 32 + declaredLength > bodyLength) throw refuse(`action ${i} of the Settler call runs past the data`, "policy_refused");
308
+ actions.push(Object.freeze({ selector: `0x${body.slice((at + 32) * 2, (at + 36) * 2)}`, argsStart: at + 36, declaredLength }));
309
+ }
310
+ return Object.freeze({ recipient, buyToken, minAmountOut, zidAndAffiliate, actions: Object.freeze(actions), bodyLength, word });
311
+ }
312
+ var ZEROEX_MAX_GAS_LIMIT = 6000000n;
313
+ function checkZeroExTransaction(tx, expected) {
314
+ if (!Number.isSafeInteger(expected.chainId) || expected.chainId <= 0) throw refuse("the swap names no EVM chain");
315
+ if (!ADDRESS2.test(expected.recipient) || ZERO_ADDRESS2.test(expected.recipient)) throw refuse("the swap names no recipient");
316
+ if (!ADDRESS2.test(expected.sellToken) || !ADDRESS2.test(expected.buyToken)) throw refuse("the swap names no sell or buy token");
317
+ if (expected.sellAmount <= 0n || expected.minBuyAmount <= 0n) throw refuse("the swap has no input or no minimum output");
318
+ const nativeSell = isZeroExNative(expected.sellToken);
319
+ const nativeBuy = isZeroExNative(expected.buyToken);
320
+ if (nativeSell ? nativeBuy : !nativeBuy && same(expected.sellToken, expected.buyToken)) throw refuse("the swap sells and buys the same token");
321
+ if (typeof tx.to !== "string" || !ADDRESS2.test(tx.to)) throw refuse("the transaction has no target", "policy_refused");
322
+ const to = tx.to;
323
+ if (!expected.settlers.length) throw refuse(`the 0x Settler for chain ${expected.chainId} is not resolved`, "upstream_unavailable");
324
+ 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");
325
+ 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");
326
+ const pin = expected.chain ?? zeroExChain(ZEROEX_CHAINS, expected.chainId);
327
+ if (!pin) throw refuse(`chain ${expected.chainId} is not in the 0x chain table`, "unsupported_pair");
328
+ const deployment = zeroExSettlerNonce(expected.chainId, to, pin.registry, tokenCeiling(pin));
329
+ 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");
330
+ if (typeof tx.value !== "string" || !/^[0-9]{1,78}$/.test(tx.value)) throw refuse("the transaction value is not a decimal amount", "policy_refused");
331
+ const value = BigInt(tx.value);
332
+ 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");
333
+ if (value > 0n && deployment !== pin.newestLiveNonce && deployment !== pin.previousLiveNonce) {
334
+ 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");
335
+ }
336
+ 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)) {
337
+ throw refuse("the transaction asks for more gas than any 0x swap needs", "policy_refused");
338
+ }
339
+ if (typeof tx.data !== "string") throw refuse("the transaction has no data", "policy_refused");
340
+ const execute = decodeSettlerExecute(tx.data);
341
+ if (!same(execute.recipient, expected.recipient)) throw refuse(`the swap pays ${execute.recipient}, not the recipient of this swap`, "recipient_mismatch");
342
+ 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");
343
+ if (execute.minAmountOut !== expected.minBuyAmount) throw refuse(`the swap enforces a minimum of ${execute.minAmountOut}, not the quoted ${expected.minBuyAmount}`, "price_check_failed");
344
+ const first = execute.actions[0];
345
+ if (nativeSell) {
346
+ if (tx.approvalAddress !== void 0) throw refuse("a native-coin sale asks for a token allowance", "policy_refused");
347
+ if (tx.permit2Transfer !== void 0) throw refuse("a native-coin sale carries a Permit2 signature request", "policy_refused");
348
+ 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");
349
+ return { execute };
350
+ }
351
+ if (typeof tx.approvalAddress !== "string" || !same(tx.approvalAddress, ZEROEX_PERMIT2)) throw refuse("the allowance target is not canonical Permit2", "vault_mismatch");
352
+ if (typeof tx.permit2Transfer !== "string") throw refuse("a token sale carries no Permit2 payload to sign", "policy_refused");
353
+ const nowMs = expected.nowMs ?? Date.now();
354
+ let permit2;
355
+ try {
356
+ permit2 = (0, import_util3.readPermit2Transfer)(tx.permit2Transfer, {
357
+ chainId: expected.chainId,
358
+ token: expected.sellToken,
359
+ amount: expected.sellAmount,
360
+ spender: to,
361
+ nowMs
362
+ });
363
+ } catch (err) {
364
+ throw refuse((err instanceof Error ? err.message : "the Permit2 payload is refused").replace(/^swap2: /, ""), (0, import_errors.refusalOf)(err)?.reason ?? "policy_refused");
365
+ }
366
+ 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");
367
+ const action = Object.prototype.hasOwnProperty.call(SETTLER_PERMIT_ACTIONS, first.selector) ? SETTLER_PERMIT_ACTIONS[first.selector] : void 0;
368
+ if (!action) throw refuse(`the swap's first action ${first.selector} is not a Permit2 payment this module knows`, "policy_refused");
369
+ const arg = (index) => execute.word(first.argsStart + 32 * index);
370
+ 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");
371
+ if (BigInt(`0x${arg(2)}`) !== expected.sellAmount) throw refuse(`${action.name} pulls an amount other than the input`, "policy_refused");
372
+ 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");
373
+ const sigOffset = arg(action.sigWord);
374
+ if (!/^0{56}/.test(sigOffset) || first.argsStart + parseInt(sigOffset.slice(56), 16) !== execute.bodyLength) {
375
+ throw refuse(`${action.name} does not read its signature from the end of the data`, "policy_refused");
376
+ }
377
+ return { execute, permit2, permitAction: action.name };
378
+ }
379
+
380
+ // src/activity.ts
381
+ var ZEROEX_MODULE = "@anywalletkit/protocol-swap2-0x";
382
+ function describeZeroExActivity(tx, ctx) {
383
+ const chainId = zeroExChainId(tx.chain);
384
+ const chain2 = zeroExChain(ZEROEX_CHAINS, chainId);
385
+ if (!chain2) return null;
386
+ if ((0, import_activity.callSelector)(tx) !== SETTLER_EXECUTE_SELECTOR) return null;
387
+ const target = tx.call?.to ?? tx.to;
388
+ if (typeof target !== "string" || zeroExSettlerNonce(chainId, target, chain2.registry, chain2.newestLiveNonce + ZEROEX_SETTLER_NONCE_MARGIN) === null) return null;
389
+ const data = tx.call?.data;
390
+ if (typeof data === "string" && data.length > 10) {
391
+ try {
392
+ decodeSettlerExecute(data);
393
+ } catch {
394
+ return null;
395
+ }
396
+ }
397
+ return (0, import_activity.describeSwapLike)(tx, ctx, { protocol: ZEROEX_MODULE, subtitle: `0x \xB7 ${(0, import_activity.chainLabel)(tx.chain)}`, kind: "swap" });
398
+ }
399
+
400
+ // src/provider.ts
401
+ var ZEROEX_PROVIDER = "zeroex";
402
+ var ZEROEX_DEFAULT_BASE_URL = "https://api.0x.org";
403
+ var DEFAULT_SLIPPAGE_BPS = 50;
404
+ var DEFAULT_TTL_MS = 45e3;
405
+ var DEFAULT_TIMEOUT_MS = 1e4;
406
+ var DEADLINE_MARGIN_MS = 2e4;
407
+ var MAX_RESPONSE_CHARS = 6e5;
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 ADDRESS3 = /^0x[0-9a-fA-F]{40}$/;
424
+ var plain = (v) => !!v && typeof v === "object" && !Array.isArray(v);
425
+ var own = (o, key) => Object.prototype.hasOwnProperty.call(o, key) ? o[key] : void 0;
426
+ var uint = (v) => typeof v === "string" && /^[0-9]{1,78}$/.test(v) ? BigInt(v) : null;
427
+ var same2 = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
428
+ var sameAmount = (a, b) => /^[0-9]{1,78}$/.test(a) && /^[0-9]{1,78}$/.test(b) && BigInt(a) === BigInt(b);
429
+ var isAddress = (v) => typeof v === "string" && ADDRESS3.test(v);
430
+ var feeToken = (token) => isZeroExNative(token) ? "native" : (0, import_viem2.getAddress)(token);
431
+ function readKey(source) {
432
+ let key = source;
433
+ if (typeof source === "function") {
434
+ try {
435
+ key = source();
436
+ } catch {
437
+ return void 0;
438
+ }
439
+ }
440
+ return typeof key === "string" && /^[\x21-\x7e]{1,200}$/.test(key) ? key : void 0;
441
+ }
442
+ function onReactNative() {
443
+ const g = globalThis;
444
+ return g.HermesInternal !== void 0 || g.navigator?.product === "ReactNative";
445
+ }
446
+ var originOf = (url) => (/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(url)?.[0] ?? "").toLowerCase();
447
+ function apiOrigin(baseUrl) {
448
+ const url = (baseUrl ?? ZEROEX_DEFAULT_BASE_URL).trim().replace(/\/+$/, "");
449
+ if (/^https:\/\/[^\s/?#@]+(?:\/[^\s?#]*)?$/i.test(url)) return url;
450
+ if (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::[0-9]{1,5})?(?:\/[^\s?#]*)?$/i.test(url)) return url;
451
+ throw new Error("zeroex: baseUrl must be an https:// origin (http only for localhost) \u2014 the API key is sent to it");
452
+ }
453
+ var UNASKED_INTEGRATOR_FEE = "the quote carries an integrator fee this wallet did not ask for";
454
+ function zeroExFees(response, gas) {
455
+ const fees = own(response, "fees");
456
+ if (!plain(fees)) return "the quote's fees are missing";
457
+ if (!Object.prototype.hasOwnProperty.call(fees, "zeroExFee")) return "the quote does not say what 0x charges";
458
+ const out = [];
459
+ const amountAndToken = (v) => {
460
+ if (!plain(v)) return null;
461
+ const amount = uint(own(v, "amount"));
462
+ const token = own(v, "token");
463
+ return amount !== null && isAddress(token) ? { amount, token } : null;
464
+ };
465
+ const zeroEx = own(fees, "zeroExFee");
466
+ if (zeroEx !== null) {
467
+ const fee = amountAndToken(zeroEx);
468
+ if (!fee) return "the 0x fee cannot be read";
469
+ if (fee.amount > 0n) out.push({ type: "protocol", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: "0x fee (taken on-chain, already out of the quoted amount)" });
470
+ }
471
+ const integrator = own(fees, "integratorFee");
472
+ if (integrator !== null && integrator !== void 0) {
473
+ const fee = amountAndToken(integrator);
474
+ if (!fee) return "the integrator fee cannot be read";
475
+ if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;
476
+ }
477
+ const integrators = own(fees, "integratorFees");
478
+ if (integrators !== null && integrators !== void 0) {
479
+ if (!Array.isArray(integrators) || integrators.length > 16) return "the integrator fees cannot be read";
480
+ for (const entry of integrators) {
481
+ const fee = amountAndToken(entry);
482
+ if (!fee) return "the integrator fees cannot be read";
483
+ if (fee.amount > 0n) return UNASKED_INTEGRATOR_FEE;
484
+ }
485
+ }
486
+ const gasFee = own(fees, "gasFee");
487
+ if (gasFee !== null && gasFee !== void 0) {
488
+ const fee = amountAndToken(gasFee);
489
+ if (!fee) return "the gas fee cannot be read";
490
+ if (fee.amount > 0n) out.push({ type: "network", amount: fee.amount.toString(), token: feeToken(fee.token), included: true, description: "Gas charged by 0x inside the trade" });
491
+ }
492
+ const total = own(response, "totalNetworkFee");
493
+ let network = null;
494
+ if (total !== null && total !== void 0) {
495
+ network = uint(total);
496
+ if (network === null) return "the network fee cannot be read";
497
+ } else if (gas.gas !== null && gas.gas !== void 0 && gas.gasPrice !== null && gas.gasPrice !== void 0) {
498
+ const units = uint(gas.gas);
499
+ const price = uint(gas.gasPrice);
500
+ if (units === null || price === null) return "the gas estimate cannot be read";
501
+ network = units * price;
502
+ }
503
+ if (network !== null) out.push({ type: "network", amount: network.toString(), token: "native", included: false, description: "Estimated network fee (gas \xD7 gas price, as 0x reports it)" });
504
+ return { fees: out, networkFeeKnown: network !== null };
505
+ }
506
+ function taxBps(v) {
507
+ if (v === null || v === void 0) return null;
508
+ if (typeof v === "number" && Number.isFinite(v) && v >= 0) return v;
509
+ if (typeof v === "string" && /^[0-9]{1,6}$/.test(v)) return Number(v);
510
+ return void 0;
511
+ }
512
+ var sequence = 0;
513
+ function zeroExProvider(config) {
514
+ if (config.apiKey !== void 0 && onReactNative()) {
515
+ throw new Error("zeroex: the 0x API key belongs on a server \u2014 in a React Native app it would ship in the bundle, and React Native's fetch follows redirects with the key attached. Run zeroExProvider({apiKey}) on your backend (createSwap2Handler) and zeroExRemoteProvider({baseUrl, rpcUrls}) in the app.");
516
+ }
517
+ const baseUrl = apiOrigin(config.baseUrl);
518
+ const apiOriginOnly = originOf(baseUrl);
519
+ const chains = zeroExChains(config.chains);
520
+ const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
521
+ const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;
522
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
523
+ const excluded = (config.excludedSources ?? []).filter((s) => typeof s === "string" && /^[A-Za-z0-9_.\- ]{1,60}$/.test(s));
524
+ const resolver = config.settlerResolver ?? createSettlerResolver({ chains, rpcUrls: config.rpcUrls, maxAgeMs: config.settlerMaxAgeMs });
525
+ const chainIdOf = (caip2) => {
526
+ const id = zeroExChainId(caip2);
527
+ return zeroExChain(chains, id) && readKey(config.apiKey) !== void 0 ? id : null;
528
+ };
529
+ const chainOfIntent = (intentId) => {
530
+ const id = Number(intentId.split(":")[1]);
531
+ return zeroExChain(chains, id) ? id : NaN;
532
+ };
533
+ return {
534
+ name: ZEROEX_PROVIDER,
535
+ describeActivity: describeZeroExActivity,
536
+ supportsSameChain: true,
537
+ // The quoted gas limit is the API's word: a native sale (like a Permit2 call) goes out with the account's own estimate.
538
+ ownGasEstimate: true,
539
+ settlerResolver: resolver,
540
+ enabled: () => config.enabled ?? true,
541
+ supportsChain: (caip2) => chainIdOf(caip2) !== null,
542
+ supportsChainPair: (from, to) => from === to && chainIdOf(from) !== null,
543
+ supportsRoute: (from, to) => from.chain === to.chain && chainIdOf(from.chain) !== null,
544
+ async getQuote(params, signal) {
545
+ const refuse2 = (why, info) => {
546
+ params.onRefusal?.(`zeroex: ${why}`, typeof info === "string" ? { reason: info } : info);
547
+ return null;
548
+ };
549
+ const refuseError = (e, prefix, fallback) => refuse2(e instanceof Error ? e.message.replace(prefix, "") : fallback, (0, import_errors2.refusalOf)(e) ?? "policy_refused");
550
+ if (params.flex) return refuse2("amount-flexible deposits are not supported", "unsupported_pair");
551
+ if (params.sourceChain !== params.destChain) return refuse2("same-chain swaps only", "unsupported_pair");
552
+ const chainId = zeroExChainId(params.sourceChain);
553
+ const chain2 = zeroExChain(chains, chainId);
554
+ if (!chain2) return refuse2(`0x is not configured for ${String(params.sourceChain).slice(0, 40)}`, "unsupported_pair");
555
+ const key = readKey(config.apiKey);
556
+ if (key === void 0) return refuse2("no 0x API key is configured", "key_rejected");
557
+ const src = (0, import_util4.sourceAssetOf)(params);
558
+ if (!src) return refuse2(`unknown source token ${String(params.sourceToken).slice(0, 60)}`, "unsupported_pair");
559
+ if (src.contract && !ADDRESS3.test(src.contract)) return refuse2("source token must be an EVM address");
560
+ const sellToken = src.contract ? (0, import_viem2.getAddress)(src.contract) : ZEROEX_NATIVE;
561
+ if (typeof params.destToken !== "string" || !ADDRESS3.test(params.destToken)) return refuse2("destination token must be an EVM address");
562
+ const buyToken = isZeroExNative(params.destToken) ? ZEROEX_NATIVE : (0, import_viem2.getAddress)(params.destToken);
563
+ const nativeSell = sellToken === ZEROEX_NATIVE;
564
+ const nativeBuy = buyToken === ZEROEX_NATIVE;
565
+ if (same2(sellToken, buyToken)) return refuse2("same token in and out", "unsupported_pair");
566
+ if (chain2.wrappedNative && (nativeSell && same2(buyToken, chain2.wrappedNative) || nativeBuy && same2(sellToken, chain2.wrappedNative))) {
567
+ return refuse2("wrapping and unwrapping are not 0x swaps", "unsupported_pair");
568
+ }
569
+ let amountIn;
570
+ try {
571
+ amountIn = BigInt(params.amountIn);
572
+ } catch {
573
+ return refuse2("amount is not an integer");
574
+ }
575
+ if (amountIn <= 0n) return refuse2("amount must be positive");
576
+ const bps = params.slippageBps ?? slippageDefault;
577
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return refuse2("invalid slippage");
578
+ let floor = null;
579
+ if (params.minAmountOut !== void 0) {
580
+ floor = uint(params.minAmountOut);
581
+ if (floor === null) return refuse2("minimum output is not an integer");
582
+ }
583
+ const dry = params.dry !== false;
584
+ let taker;
585
+ let recipient;
586
+ if (dry) {
587
+ const known = isAddress(params.refundAddress) ? params.refundAddress : isAddress(params.destAddress) ? params.destAddress : void 0;
588
+ taker = known ? (0, import_viem2.getAddress)(known) : void 0;
589
+ } else {
590
+ if (!isAddress(params.destAddress)) return refuse2("recipient must be an EVM address", "recipient_mismatch");
591
+ recipient = (0, import_viem2.getAddress)(params.destAddress);
592
+ taker = (0, import_viem2.getAddress)(isAddress(params.refundAddress) ? params.refundAddress : params.destAddress);
593
+ }
594
+ let settlers = [];
595
+ if (!dry) {
596
+ try {
597
+ settlers = await resolver.resolve(chainId);
598
+ } catch (e) {
599
+ return refuseError(e, /^zeroex: /, "the 0x Settler cannot be resolved");
600
+ }
601
+ }
602
+ const query = [
603
+ ["chainId", String(chainId)],
604
+ ["sellToken", sellToken],
605
+ ["buyToken", buyToken],
606
+ ["sellAmount", amountIn.toString()],
607
+ ["slippageBps", String(bps)]
608
+ ];
609
+ if (taker) query.push(["taker", taker]);
610
+ if (recipient && taker && !same2(recipient, taker)) query.push(["recipient", recipient]);
611
+ if (excluded.length) query.push(["excludedSources", excluded.join(",")]);
612
+ const url = `${baseUrl}/swap/permit2/${dry ? "price" : "quote"}?${query.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&")}`;
613
+ let status;
614
+ let text;
615
+ let retryAfter = null;
616
+ try {
617
+ const timeout = (0, import_util4.timeoutSignal)(timeoutMs);
618
+ const res = await fetch(url, { method: "GET", redirect: "error", headers: { accept: "application/json", "0x-api-key": key, "0x-version": "v2" }, signal: signal ? (0, import_util4.anySignal)([signal, timeout]) : timeout });
619
+ if (res.redirected === true || typeof res.url === "string" && res.url !== "" && originOf(res.url) !== apiOriginOnly) {
620
+ return refuse2("the API answer came through a redirect or from another origin \u2014 refused (the key must not follow one)", "policy_refused");
621
+ }
622
+ status = res.status;
623
+ retryAfter = res.headers?.get?.("retry-after") ?? null;
624
+ text = await res.text();
625
+ } catch (e) {
626
+ return refuse2(`API unreachable (${e instanceof Error ? e.name.slice(0, 40) : "error"})`, signal?.aborted ? void 0 : "upstream_unavailable");
627
+ }
628
+ if (text.length > MAX_RESPONSE_CHARS) return refuse2("the API answer is larger than any quote", "upstream_unavailable");
629
+ let body;
630
+ try {
631
+ body = JSON.parse(text);
632
+ } catch {
633
+ body = void 0;
634
+ }
635
+ if (status < 200 || status >= 300) {
636
+ const byStatus = (0, import_errors2.httpRefusal)(status, retryAfter);
637
+ const name = plain(body) ? own(body, "name") : void 0;
638
+ if (typeof name === "string" && Object.prototype.hasOwnProperty.call(API_ERRORS, name)) {
639
+ const [why, reason] = API_ERRORS[name];
640
+ return refuse2(`${why} (${name})`, byStatus?.reason === "rate_limited" ? byStatus : reason === "upstream_unavailable" || reason === "key_rejected" ? { reason, httpStatus: status } : reason);
641
+ }
642
+ if (status === 401 || status === 403) return refuse2(`API key rejected (HTTP ${status})`, byStatus);
643
+ if (status === 429) return refuse2("rate limited (HTTP 429)", byStatus);
644
+ return refuse2(`API answered HTTP ${status}`, byStatus ?? (plain(body) ? "no_route" : { reason: "upstream_unavailable", httpStatus: status }));
645
+ }
646
+ if (!plain(body)) return refuse2("malformed API response", "upstream_unavailable");
647
+ const r = body;
648
+ if (own(r, "liquidityAvailable") === false) return refuse2("no liquidity for this pair and amount", "insufficient_liquidity");
649
+ if (own(r, "liquidityAvailable") !== true) return refuse2("malformed API response (liquidity)", "upstream_unavailable");
650
+ const mode = own(r, "mode");
651
+ if (mode !== void 0 && mode !== "exact-in") return refuse2("the API answered a quote that is not exact-input", "policy_refused");
652
+ const echoedSell = own(r, "sellToken");
653
+ const echoedBuy = own(r, "buyToken");
654
+ if (!isAddress(echoedSell) || !same2(echoedSell, sellToken) || !isAddress(echoedBuy) || !same2(echoedBuy, buyToken)) return refuse2("the API quoted other tokens than the ones asked for", "policy_refused");
655
+ const quotedIn = uint(own(r, "sellAmount"));
656
+ const buyAmount = uint(own(r, "buyAmount"));
657
+ const minBuyAmount = uint(own(r, "minBuyAmount"));
658
+ if (quotedIn === null || buyAmount === null || minBuyAmount === null) return refuse2("malformed quote amounts", "upstream_unavailable");
659
+ if (quotedIn !== amountIn) return refuse2(`quoted ${quotedIn}, not the requested ${amountIn}`, "policy_refused");
660
+ if (minBuyAmount <= 0n || minBuyAmount > buyAmount) return refuse2("the quoted minimum is not between zero and the quoted output", "price_check_failed");
661
+ if (minBuyAmount < (0, import_validate.slippageFloor)(buyAmount, bps)) return refuse2(`the quoted minimum ${minBuyAmount} is below the requested slippage (${bps} bps of ${buyAmount})`, "price_check_failed");
662
+ if (floor !== null && minBuyAmount < floor) return refuse2(`floor breach (min=${minBuyAmount} < floor=${floor})`, "price_check_failed");
663
+ const metadata = own(r, "tokenMetadata");
664
+ const buyMeta = plain(metadata) ? own(metadata, "buyToken") : void 0;
665
+ if (buyMeta !== void 0 && buyMeta !== null) {
666
+ if (!plain(buyMeta)) return refuse2("malformed API response (token metadata)", "upstream_unavailable");
667
+ for (const field of ["buyTaxBps", "transferTaxBps"]) {
668
+ const tax = taxBps(own(buyMeta, field));
669
+ if (tax === void 0) return refuse2("malformed API response (token tax)", "upstream_unavailable");
670
+ if (tax !== null && tax > 0) return refuse2("the token being bought taxes transfers \u2014 the amount received cannot be guaranteed", "unsupported_pair");
671
+ }
672
+ }
673
+ const transaction = own(r, "transaction");
674
+ if (!dry && !plain(transaction)) return refuse2("the quote carries no transaction", "upstream_unavailable");
675
+ const tx = plain(transaction) ? transaction : void 0;
676
+ const parsedFees = zeroExFees(r, tx ? { gas: own(tx, "gas"), gasPrice: own(tx, "gasPrice") } : { gas: own(r, "gas"), gasPrice: own(r, "gasPrice") });
677
+ if (typeof parsedFees === "string") return refuse2(parsedFees, parsedFees === UNASKED_INTEGRATOR_FEE ? "policy_refused" : "upstream_unavailable");
678
+ const flags = [];
679
+ const issues = own(r, "issues");
680
+ if (plain(issues)) {
681
+ if (own(issues, "balance")) flags.push("balance");
682
+ if (own(issues, "simulationIncomplete") === true) flags.push("simulationIncomplete");
683
+ const allowance = own(issues, "allowance");
684
+ if (plain(allowance)) {
685
+ const spender = own(allowance, "spender");
686
+ if (!isAddress(spender) || !same2(spender, ZEROEX_PERMIT2)) return refuse2("the API asks for an allowance to something other than canonical Permit2", "vault_mismatch");
687
+ flags.push("allowance");
688
+ }
689
+ const invalid = own(issues, "invalidSourcesPassed");
690
+ if (Array.isArray(invalid) && invalid.length) {
691
+ const names = invalid.filter((n) => typeof n === "string" && /^[A-Za-z0-9_.\- ]{1,60}$/.test(n)).slice(0, 3);
692
+ return refuse2(`0x does not know the excluded source${invalid.length > 1 ? "s" : ""} ${names.length ? names.join(", ") : "it was given"}${invalid.length > names.length ? " and more" : ""} \u2014 they would not be excluded`, "policy_refused");
693
+ }
694
+ }
695
+ const allowanceTarget = own(r, "allowanceTarget");
696
+ if (allowanceTarget !== null && allowanceTarget !== void 0) {
697
+ const permit2Target = isAddress(allowanceTarget) && same2(allowanceTarget, ZEROEX_PERMIT2);
698
+ if (nativeSell && !permit2Target) return refuse2("the API asks for a token allowance on a native-coin sale", "policy_refused");
699
+ if (!permit2Target) return refuse2("the API asks for an allowance to something other than canonical Permit2", "vault_mismatch");
700
+ }
701
+ const zidRaw = own(r, "zid");
702
+ const zid = typeof zidRaw === "string" && /^0x[0-9a-fA-F]{1,64}$/.test(zidRaw) ? zidRaw : void 0;
703
+ const now = Date.now();
704
+ let validUntilMs = now + ttl;
705
+ let txRequest;
706
+ let settler;
707
+ if (!dry && tx && recipient) {
708
+ const to = own(tx, "to");
709
+ const data = own(tx, "data");
710
+ const value = uint(own(tx, "value"));
711
+ if (!isAddress(to) || typeof data !== "string" || value === null) return refuse2("malformed quote transaction", "upstream_unavailable");
712
+ let permit2Transfer;
713
+ let permit2;
714
+ const permit = own(r, "permit2");
715
+ if (nativeSell) {
716
+ if (permit !== null && permit !== void 0) return refuse2("the API asks for a Permit2 signature on a native-coin sale", "policy_refused");
717
+ validUntilMs = Math.min(validUntilMs, now + (ZEROEX_MAX_NATIVE_QUOTE_SECONDS - ZEROEX_NATIVE_QUOTE_SKEW_SECONDS) * 1e3);
718
+ } else {
719
+ const eip712 = plain(permit) ? own(permit, "eip712") : void 0;
720
+ if (!plain(permit) || !plain(eip712)) return refuse2("the quote carries no Permit2 payload to sign", "policy_refused");
721
+ try {
722
+ permit2 = (0, import_util4.readPermit2Transfer)(JSON.stringify({ domain: own(eip712, "domain"), types: own(eip712, "types"), primaryType: own(eip712, "primaryType"), message: own(eip712, "message") }), {
723
+ chainId,
724
+ token: sellToken,
725
+ amount: amountIn,
726
+ spender: to,
727
+ nowMs: now
728
+ });
729
+ } catch (e) {
730
+ return refuseError(e, /^swap2: /, "the Permit2 payload is refused");
731
+ }
732
+ const hash = own(permit, "hash");
733
+ if (hash !== null && hash !== void 0) {
734
+ const local = (0, import_viem2.hashTypedData)({
735
+ domain: permit2.domain,
736
+ types: { PermitTransferFrom: permit2.types.PermitTransferFrom, TokenPermissions: permit2.types.TokenPermissions },
737
+ primaryType: permit2.primaryType,
738
+ message: permit2.message
739
+ });
740
+ if (typeof hash !== "string" || !same2(hash, local)) return refuse2("the Permit2 payload does not hash to what the API says is being signed", "policy_refused");
741
+ }
742
+ permit2Transfer = (0, import_util4.permit2TransferJson)(permit2);
743
+ const lapse = permit2.deadline * 1000n - BigInt(DEADLINE_MARGIN_MS);
744
+ if (lapse <= BigInt(now)) return refuse2("the Permit2 deadline is too close to sign against", "quote_expired");
745
+ if (lapse < BigInt(validUntilMs)) validUntilMs = (0, import_core.bigintToNumber)(lapse);
746
+ }
747
+ const gas = uint(own(tx, "gas"));
748
+ const gasLimit = gas !== null && gas > 0n ? (gas * 12n / 10n + 20000n).toString() : void 0;
749
+ const candidate = {
750
+ to,
751
+ data,
752
+ value: value.toString(),
753
+ chainId,
754
+ ...gasLimit !== void 0 ? { gasLimit } : {},
755
+ ...nativeSell ? {} : { approvalAddress: ZEROEX_PERMIT2 },
756
+ ...permit2Transfer !== void 0 ? { permit2Transfer } : {}
757
+ };
758
+ const expectation = (set) => ({ chainId, chain: chain2, settlers: set, sellToken, buyToken, sellAmount: amountIn, recipient, minBuyAmount, nowMs: now });
759
+ try {
760
+ try {
761
+ checkZeroExTransaction(candidate, expectation(settlers));
762
+ } catch (first) {
763
+ if (settlers.some((s) => same2(s, to))) throw first;
764
+ settlers = await resolver.resolve(chainId, { fresh: true });
765
+ checkZeroExTransaction(candidate, expectation(settlers));
766
+ }
767
+ } catch (e) {
768
+ return refuseError(e, /^zeroex: /, "the transaction is refused");
769
+ }
770
+ settler = (0, import_viem2.getAddress)(to);
771
+ txRequest = {
772
+ to: settler,
773
+ data,
774
+ value: value.toString(),
775
+ chainId,
776
+ ...gasLimit !== void 0 ? { gasLimit } : {},
777
+ ...nativeSell ? {} : { approvalAddress: (0, import_viem2.getAddress)(ZEROEX_PERMIT2) },
778
+ ...permit2Transfer !== void 0 ? { permit2Transfer } : {}
779
+ };
780
+ }
781
+ const sources = zeroExSources(own(r, "route"));
782
+ return {
783
+ provider: ZEROEX_PROVIDER,
784
+ intentId: `zeroex:${chainId}:${now.toString(36)}${(sequence = (sequence + 1) % 1e6).toString(36)}`,
785
+ depositAddress: "",
786
+ depositMemo: null,
787
+ ...txRequest ? { txRequest } : {},
788
+ sourceAmount: amountIn.toString(),
789
+ destAmount: buyAmount.toString(),
790
+ minDestAmount: minBuyAmount.toString(),
791
+ feeUsd: 0,
792
+ fees: parsedFees.fees,
793
+ etaSeconds: 15,
794
+ reliability: 0.96,
795
+ validUntilMs,
796
+ providerData: {
797
+ minOut: minBuyAmount.toString(),
798
+ slippageBps: String(bps),
799
+ ...taker ? { sender: taker } : {},
800
+ ...settler ? { settler } : {},
801
+ ...zid ? { zid } : {},
802
+ ...sources ? { sources } : {},
803
+ ...parsedFees.networkFeeKnown ? {} : { networkFee: "unknown" },
804
+ ...flags.length ? { issues: flags.join(",") } : {}
805
+ }
806
+ };
807
+ },
808
+ /**
809
+ * Before the engine signs: the transaction must be the quoted one, and its target must still be a Settler in the
810
+ * registry now ({@link zeroExPreflightDeposit}). The call itself cannot be simulated yet: it needs the Permit2
811
+ * signature, which the engine makes next and then estimates as signed.
812
+ */
813
+ preflightDeposit: (quote, tx) => zeroExPreflightDeposit(quote, tx, { chains, resolver }),
814
+ async buildDeposit(quote) {
815
+ const tx = quote.txRequest;
816
+ if (!tx?.to || !tx.data) throw (0, import_errors2.refusal)("policy_refused", "zeroex: not a live quote \u2014 it carries no transaction");
817
+ return {
818
+ chain: "",
819
+ to: tx.to,
820
+ value: tx.value ?? "0",
821
+ data: tx.data,
822
+ ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {},
823
+ ...tx.gasLimit ? { gasLimit: tx.gasLimit } : {},
824
+ ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {},
825
+ ...tx.permit2Transfer !== void 0 ? { permit2Transfer: tx.permit2Transfer } : {}
826
+ };
827
+ },
828
+ async trackIntent(ref) {
829
+ if (!ref.sourceTxHash || !/^0x[0-9a-fA-F]{64}$/.test(ref.sourceTxHash)) return { state: "pending" };
830
+ const chainId = chainOfIntent(ref.intentId);
831
+ if (Number.isNaN(chainId) || !rpcUrlsFor(config.rpcUrls, chainId).length) return { state: "pending" };
832
+ const answer = await rpcRequest(config.rpcUrls, chainId, "eth_getTransactionReceipt", [ref.sourceTxHash]);
833
+ if (!answer || "error" in answer || !plain(answer.result)) return { state: "pending" };
834
+ const status = own(answer.result, "status");
835
+ if (status === "0x1") return { state: "completed", destTxHash: ref.sourceTxHash };
836
+ return status === "0x0" ? { state: "failed" } : { state: "pending" };
837
+ }
838
+ };
839
+ }
840
+ async function zeroExPreflightDeposit(quote, tx, ctx) {
841
+ const quoted = quote.txRequest;
842
+ 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) {
843
+ throw (0, import_errors2.refusal)("policy_refused", "zeroex: the transaction is not the quoted swap. Nothing was sent; refresh the quote.");
844
+ }
845
+ const chainId = typeof quote.intentId === "string" ? Number(quote.intentId.split(":")[1]) : NaN;
846
+ if (!zeroExChain(ctx.chains, chainId)) throw (0, import_errors2.refusal)("policy_refused", "zeroex: the quote names no chain this provider serves. Nothing was sent.");
847
+ const settlers = await ctx.resolver.resolve(chainId, { fresh: true });
848
+ if (!settlers.some((s) => same2(s, quoted.to))) {
849
+ 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.");
850
+ }
851
+ }
852
+ function zeroExSources(route) {
853
+ const fills = plain(route) ? own(route, "fills") : void 0;
854
+ if (!Array.isArray(fills)) return void 0;
855
+ const names = [];
856
+ for (const fill of fills.slice(0, 64)) {
857
+ const source = plain(fill) ? own(fill, "source") : void 0;
858
+ if (typeof source !== "string" || !/^[A-Za-z0-9_.\- ]{1,40}$/.test(source)) continue;
859
+ if (!names.includes(source)) names.push(source);
860
+ if (names.length === 6) break;
861
+ }
862
+ return names.length ? names.join(",") : void 0;
863
+ }
864
+
865
+ // src/protocol.ts
866
+ var ZeroExSwap2Protocol = class extends import_single.SingleProviderSwap2 {
867
+ provider;
868
+ constructor(account, config) {
869
+ super(account, config);
870
+ this.provider = zeroExProvider(config);
871
+ }
872
+ chainSupported(caip2) {
873
+ return this.provider.supportsChain?.(caip2) === true;
874
+ }
875
+ pairSupported(fromChain, toChain) {
876
+ return fromChain === toChain && this.chainSupported(fromChain);
877
+ }
878
+ };
879
+ //# sourceMappingURL=protocol.cjs.map