@anywalletkit/protocol-swap2-kyberswap 0.2.0 → 0.3.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.
- package/README.md +150 -6
- package/dist/activity.cjs +28 -2
- package/dist/activity.cjs.map +1 -1
- package/dist/activity.js +2 -2
- package/dist/{chunk-LO4G4NX7.js → chunk-BGMHF5MC.js} +3 -3
- package/dist/{chunk-OHBN7OQI.js → chunk-CFL4E4AW.js} +40 -3
- package/dist/chunk-CFL4E4AW.js.map +1 -0
- package/dist/{chunk-5ZMVXS7P.js → chunk-DP4WDX4C.js} +2 -2
- package/dist/{chunk-RZ2CCM34.js → chunk-INSCVUFN.js} +62 -15
- package/dist/chunk-INSCVUFN.js.map +1 -0
- package/dist/index.cjs +93 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +16 -4
- package/dist/protocol.cjs +87 -13
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.js +4 -4
- package/dist/provider.cjs +89 -13
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +25 -2
- package/dist/provider.d.ts +25 -2
- package/dist/provider.js +7 -3
- package/dist/router.cjs +39 -2
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts +23 -2
- package/dist/router.d.ts +23 -2
- package/dist/router.js +9 -1
- package/package.json +7 -7
- package/dist/chunk-OHBN7OQI.js.map +0 -1
- package/dist/chunk-RZ2CCM34.js.map +0 -1
- /package/dist/{chunk-LO4G4NX7.js.map → chunk-BGMHF5MC.js.map} +0 -0
- /package/dist/{chunk-5ZMVXS7P.js.map → chunk-DP4WDX4C.js.map} +0 -0
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
describeKyberActivity
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-DP4WDX4C.js";
|
|
4
4
|
import {
|
|
5
|
+
KYBER_DEFAULT_SLIPPAGE_BPS,
|
|
6
|
+
KYBER_LIMIT_ORDER_SOURCES,
|
|
5
7
|
KYBER_NATIVE,
|
|
8
|
+
KYBER_RFQ_SOURCES,
|
|
6
9
|
KYBER_ROUTER_ABI,
|
|
7
10
|
KYBER_ROUTER_V2,
|
|
8
11
|
KYBER_ROUTER_V3,
|
|
@@ -11,19 +14,21 @@ import {
|
|
|
11
14
|
kyberChain,
|
|
12
15
|
kyberExactAllowanceOnly,
|
|
13
16
|
kyberMinimum,
|
|
14
|
-
kyberNativeSwaps
|
|
15
|
-
|
|
17
|
+
kyberNativeSwaps,
|
|
18
|
+
kyberSourceKind
|
|
19
|
+
} from "./chunk-CFL4E4AW.js";
|
|
16
20
|
|
|
17
21
|
// src/provider.ts
|
|
18
22
|
import { decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi } from "viem";
|
|
19
23
|
import { evmRef, isEvm, timeoutSignal, sourceAssetOf } from "@anywalletkit/protocol-swap2-core/util";
|
|
24
|
+
import { validVenueGas } from "@anywalletkit/protocol-swap2-core/validate";
|
|
20
25
|
import { httpRefusal, refusal, refusalOf, withReason } from "@anywalletkit/protocol-swap2-core/errors";
|
|
21
26
|
import { ccAssetByToken } from "@anywalletkit/swap2-assets";
|
|
22
27
|
import { WRAPPED_NATIVE } from "@anywalletkit/protocol-swap2-wrap/provider";
|
|
23
28
|
var ZERO = "0x0000000000000000000000000000000000000000";
|
|
24
29
|
var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
|
|
25
30
|
var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
|
|
26
|
-
var DEFAULT_SLIPPAGE_BPS =
|
|
31
|
+
var DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;
|
|
27
32
|
var DEFAULT_TTL_MS = 3e4;
|
|
28
33
|
var DRY_CACHE_MS = 5e3;
|
|
29
34
|
var BUILD_DEADLINE_S = 20 * 60;
|
|
@@ -44,17 +49,23 @@ var ERROR_REASONS = {
|
|
|
44
49
|
4227: "simulation_failed"
|
|
45
50
|
};
|
|
46
51
|
var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
|
|
52
|
+
var KYBER_RFQ_TTL_MS = 1e4;
|
|
53
|
+
var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
|
|
47
54
|
var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
|
|
48
55
|
var isAddr = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
|
|
49
56
|
var same = (a, b) => isAddr(a) && a.toLowerCase() === b.toLowerCase();
|
|
50
57
|
var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
|
|
51
58
|
var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
|
|
52
59
|
var apiToken = (t) => t === ZERO ? KYBER_NATIVE : t;
|
|
60
|
+
var offchainName = (offchain) => offchain.includes("rfq") && offchain.includes("limit-order") ? "market maker's quote or limit order" : offchain.includes("rfq") ? "market maker's quote" : "limit order";
|
|
53
61
|
var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
|
|
54
62
|
function kyberGasEstimate(routeGas) {
|
|
55
63
|
const gas = uint(routeGas);
|
|
56
64
|
return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
|
|
57
65
|
}
|
|
66
|
+
function kyberBuildGas(gas) {
|
|
67
|
+
return validVenueGas(gas) ? gas : void 0;
|
|
68
|
+
}
|
|
58
69
|
var ERC20_READS = parseAbi(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
|
|
59
70
|
function revertData(e) {
|
|
60
71
|
const err = e;
|
|
@@ -81,6 +92,14 @@ function revertString(e) {
|
|
|
81
92
|
return m ? m[1] : null;
|
|
82
93
|
}
|
|
83
94
|
function kyberswapProvider(config = {}) {
|
|
95
|
+
const legacy = config.excludeRfqSources === false ? "include" : "exclude";
|
|
96
|
+
const setting = (v, name) => {
|
|
97
|
+
if (v === void 0) return legacy;
|
|
98
|
+
if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
|
|
99
|
+
return v;
|
|
100
|
+
};
|
|
101
|
+
const rfqSetting = setting(config.rfq, "rfq");
|
|
102
|
+
const limitOrderSetting = setting(config.limitOrders, "limitOrders");
|
|
84
103
|
const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
|
|
85
104
|
const clientId = config.clientId ?? "anywalletkit";
|
|
86
105
|
const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
|
|
@@ -139,10 +158,17 @@ function kyberswapProvider(config = {}) {
|
|
|
139
158
|
if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
|
|
140
159
|
return { ok: true, data: body.data };
|
|
141
160
|
}
|
|
161
|
+
function sourceFilters(q, chainId) {
|
|
162
|
+
const excluded = [];
|
|
163
|
+
if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
|
|
164
|
+
else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
|
|
165
|
+
else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
|
|
166
|
+
for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
|
|
167
|
+
if (excluded.length) q.set("excludedSources", excluded.join(","));
|
|
168
|
+
}
|
|
142
169
|
async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
|
|
143
170
|
const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
|
|
144
|
-
|
|
145
|
-
if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
|
|
171
|
+
sourceFilters(q, chainId);
|
|
146
172
|
const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
|
|
147
173
|
if (!r.ok) return r;
|
|
148
174
|
const summary = r.data.routeSummary;
|
|
@@ -159,16 +185,19 @@ function kyberswapProvider(config = {}) {
|
|
|
159
185
|
}
|
|
160
186
|
const amountOut = uint(summary.amountOut);
|
|
161
187
|
if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
|
|
162
|
-
const
|
|
163
|
-
|
|
188
|
+
const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
|
|
189
|
+
const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
|
|
190
|
+
const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
|
|
191
|
+
return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
|
|
164
192
|
}
|
|
165
|
-
async function revertReason(chainId, sender, quoted, e) {
|
|
193
|
+
async function revertReason(chainId, sender, quoted, e, offchain) {
|
|
166
194
|
const text = revertString(e);
|
|
167
195
|
if (text && /return amount is not enough|min return/i.test(text)) {
|
|
168
196
|
return refusal("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
|
|
169
197
|
}
|
|
170
198
|
const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
|
|
171
199
|
if (lack) return refusal("simulation_failed", lack);
|
|
200
|
+
if (offchain) return refusal("quote_expired", `kyberswap: the ${offchainName(offchain)} in this route no longer fills (expired or taken). Nothing was sent; refresh the quote.`);
|
|
172
201
|
return refusal("simulation_failed", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : "revert"))}). Nothing was sent; refresh the quote.`);
|
|
173
202
|
}
|
|
174
203
|
async function inputShortfall(chainId, sender, quoted) {
|
|
@@ -231,7 +260,8 @@ function kyberswapProvider(config = {}) {
|
|
|
231
260
|
name: "kyberswap",
|
|
232
261
|
describeActivity: describeKyberActivity,
|
|
233
262
|
supportsSameChain: true,
|
|
234
|
-
// The account's own estimate of the exact call,
|
|
263
|
+
// The account's own estimate of the exact call, dry-run before broadcast: the limit is built on it (× 1.3 + 100 000),
|
|
264
|
+
// with the build's gas as a floor (`venueGas`), never the API's figure alone.
|
|
235
265
|
ownGasEstimate: true,
|
|
236
266
|
// On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
|
|
237
267
|
exactAllowanceOnly: kyberExactAllowanceOnly,
|
|
@@ -304,6 +334,8 @@ function kyberswapProvider(config = {}) {
|
|
|
304
334
|
const minOut = kyberMinimum(r.amountOut, apiBps);
|
|
305
335
|
if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
|
|
306
336
|
const gasEstimate = kyberGasEstimate(r.summary.gas);
|
|
337
|
+
const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
|
|
338
|
+
const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
|
|
307
339
|
const base = {
|
|
308
340
|
provider: "kyberswap",
|
|
309
341
|
intentId: `kyberswap:${chainId}`,
|
|
@@ -317,14 +349,15 @@ function kyberswapProvider(config = {}) {
|
|
|
317
349
|
...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
|
|
318
350
|
etaSeconds: 15,
|
|
319
351
|
reliability: 0.95,
|
|
320
|
-
validUntilMs: Date.now() +
|
|
352
|
+
validUntilMs: Date.now() + life
|
|
321
353
|
};
|
|
322
354
|
const providerData = {
|
|
323
355
|
amountOut: r.amountOut.toString(),
|
|
324
356
|
minOut: minOut.toString(),
|
|
325
357
|
apiSlippageBps: String(apiBps),
|
|
326
358
|
...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
|
|
327
|
-
...r.sources.length ? { sources: r.sources.join(",") } : {}
|
|
359
|
+
...r.sources.length ? { sources: r.sources.join(",") } : {},
|
|
360
|
+
...offchain ? { offchain } : {}
|
|
328
361
|
};
|
|
329
362
|
const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
|
|
330
363
|
if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
|
|
@@ -348,7 +381,16 @@ function kyberswapProvider(config = {}) {
|
|
|
348
381
|
if (!built.ok) return refuse(`build: ${built.why}`, built.info);
|
|
349
382
|
const b = built.data;
|
|
350
383
|
if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
|
|
384
|
+
let destAmount = r.amountOut;
|
|
385
|
+
if (offchain) {
|
|
386
|
+
const builtOut = uint(b.amountOut);
|
|
387
|
+
if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
|
|
388
|
+
if (builtOut < minOut || builtOut < floor) return refuse(`the ${offchainName(offchain)} came in under the minimum when the route was built (${builtOut} < ${minOut}); refresh the quote`, "price_check_failed");
|
|
389
|
+
if (builtOut < destAmount) destAmount = builtOut;
|
|
390
|
+
}
|
|
351
391
|
if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
|
|
392
|
+
const buildGas = kyberBuildGas(b.gas);
|
|
393
|
+
const shownGas = base.gasEstimate === void 0 && buildGas !== void 0 ? kyberGasEstimate(buildGas) : void 0;
|
|
352
394
|
const value = uint(b.transactionValue ?? "0");
|
|
353
395
|
if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
|
|
354
396
|
const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
|
|
@@ -381,12 +423,15 @@ function kyberswapProvider(config = {}) {
|
|
|
381
423
|
}
|
|
382
424
|
return {
|
|
383
425
|
...base,
|
|
426
|
+
...shownGas !== void 0 ? { gasEstimate: shownGas, gasEstimateSource: "venue" } : {},
|
|
427
|
+
destAmount: destAmount.toString(),
|
|
384
428
|
minDestAmount: decoded.minReturnAmount.toString(),
|
|
385
429
|
txRequest: {
|
|
386
430
|
to: KYBER_ROUTER_V2,
|
|
387
431
|
data: tx.data,
|
|
388
432
|
value: value.toString(),
|
|
389
433
|
chainId,
|
|
434
|
+
...buildGas !== void 0 ? { venueGas: buildGas } : {},
|
|
390
435
|
...tokenIn === ZERO ? {} : { approvalAddress: KYBER_ROUTER_V2 }
|
|
391
436
|
},
|
|
392
437
|
providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
|
|
@@ -408,14 +453,14 @@ function kyberswapProvider(config = {}) {
|
|
|
408
453
|
try {
|
|
409
454
|
await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
|
|
410
455
|
} catch (e) {
|
|
411
|
-
if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
|
|
456
|
+
if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
|
|
412
457
|
throw withReason(new Error("kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again."), refusalOf(e) ?? "upstream_unavailable");
|
|
413
458
|
}
|
|
414
459
|
},
|
|
415
460
|
async buildDeposit(quote) {
|
|
416
461
|
const tx = quote.txRequest;
|
|
417
462
|
if (!tx?.to || !tx.data) throw refusal("policy_refused", "swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)");
|
|
418
|
-
return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
|
|
463
|
+
return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.venueGas !== void 0 ? { venueGas: tx.venueGas } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
|
|
419
464
|
},
|
|
420
465
|
async trackIntent(ref) {
|
|
421
466
|
if (!ref.sourceTxHash) return { state: "pending" };
|
|
@@ -433,8 +478,10 @@ function kyberswapProvider(config = {}) {
|
|
|
433
478
|
}
|
|
434
479
|
|
|
435
480
|
export {
|
|
481
|
+
KYBER_RFQ_TTL_MS,
|
|
482
|
+
KYBER_LIMIT_ORDER_TTL_MS,
|
|
436
483
|
kyberGasEstimate,
|
|
437
484
|
kyberValueLossBps,
|
|
438
485
|
kyberswapProvider
|
|
439
486
|
};
|
|
440
|
-
//# sourceMappingURL=chunk-
|
|
487
|
+
//# sourceMappingURL=chunk-INSCVUFN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts"],"sourcesContent":["import {decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {validVenueGas} from \"@anywalletkit/protocol-swap2-core/validate\";\nimport {httpRefusal, refusal, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {WRAPPED_NATIVE} from \"@anywalletkit/protocol-swap2-wrap/provider\";\nimport {describeKyberActivity} from \"./activity.js\";\nimport {KYBER_DEFAULT_SLIPPAGE_BPS, KYBER_LIMIT_ORDER_SOURCES, KYBER_NATIVE, KYBER_RFQ_SOURCES, KYBER_ROUTER_ABI, KYBER_ROUTER_V2, KYBER_ROUTER_V3, checkKyberTransaction, kyberApiSlippage, kyberChain, kyberExactAllowanceOnly, kyberMinimum, kyberNativeSwaps, kyberSourceKind} from \"./router.js\";\n\n/**\n * KyberSwap Aggregator (docs.kyberswap.com) as a same-chain swap2 provider: exact-input swaps on the chains in\n * `KYBER_CHAINS`, routed by KyberSwap and settled through MetaAggregationRouterV2.\n *\n * A dry quote is `GET /routes` only. An execution quote (the engine's, with `dry: false`) also calls\n * `POST /route/build` and returns the encoded transaction, checked field by field against the request\n * (`checkKyberTransaction`): the build endpoint encodes whatever route summary it is sent, fee entries included, so\n * nothing in its answer is taken on trust. Before the transaction is signed it is simulated from the account at the\n * latest block; with no RPC answering, the swap is refused.\n *\n * Keyless by default (the public API, 3 requests per second per IP). With `apiKey`, requests go to KyberSwap's API\n * gateway instead. No integrator fee is ever charged; KyberSwap keeps any output above the quote (positive slippage).\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst PUBLIC_BASE_URL = \"https://aggregator-api.kyberswap.com\";\nconst GATEWAY_BASE_URL = \"https://api.kyberswap.com/swap\";\nconst DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;\n/** How long a quote stays executable for the engine: the user's review fits, an approval mined meanwhile gets one re-quote. */\nconst DEFAULT_TTL_MS = 30_000;\n/** A dry route is reused this long for the same request (KyberSwap asks not to cache routes for more than 5–10 s). */\nconst DRY_CACHE_MS = 5_000;\n/** The executor's own deadline for a built swap (the build endpoint's default). */\nconst BUILD_DEADLINE_S = 20 * 60;\n\n/**\n * KyberSwap's error codes (docs.kyberswap.com, aggregator API errors) → refusal reasons. 4222: the route quoted\n * under KyberSwap's own estimate; 4227: its gas estimation failed.\n */\nconst ERROR_REASONS: Readonly<Record<number, Swap2RefusalReason>> = {\n 4000: \"policy_refused\", 4001: \"policy_refused\", 4002: \"policy_refused\", 4005: \"policy_refused\", 4007: \"policy_refused\", 40017: \"policy_refused\",\n 4008: \"no_route\", 40011: \"no_route\",\n 4009: \"insufficient_liquidity\", 4010: \"insufficient_liquidity\",\n 4011: \"unsupported_pair\", 4221: \"unsupported_pair\",\n 4222: \"price_check_failed\",\n 4227: \"simulation_failed\",\n};\nconst errorReason = (code: unknown): Swap2RefusalReason | undefined =>\n typeof code === \"number\" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : undefined;\n\nexport interface KyberswapProviderConfig {\n enabled?: boolean;\n /** `x-client-id` and the build's `source` (written on-chain in the swap's `clientData`). Default \"anywalletkit\". */\n clientId?: string;\n /** KyberSwap API-gateway key (`X-Api-Key`); keep it on a server. Without it the keyless public API is used. */\n apiKey?: string;\n /** Override the API base (`{baseUrl}/{chain}/api/v1/...`). */\n baseUrl?: string;\n /** JSON-RPC endpoints per chain id: required for execution (pre-broadcast simulation) and receipts. */\n rpcUrls?: Readonly<Record<number, readonly string[]>>;\n /** Chains to quote on (default: every chain in `KYBER_CHAINS`). */\n enabledChains?: readonly number[];\n defaultSlippageBps?: number;\n quoteTtlMs?: number;\n timeoutMs?: number;\n /**\n * RFQ market makers (KyberSwap's \"RFQ sources\": `pmm-N`, Bebop, Native, Hashflow, …), whose firm quote is signed\n * when the route is built. Default \"exclude\". See the README (\"RFQ and limit orders\") for what including them costs.\n */\n rfq?: KyberSourceSetting;\n /** KyberSwap's own limit orders (`kyberswap-limit-order-v2`), filled from an off-chain order book. Default \"exclude\". */\n limitOrders?: KyberSourceSetting;\n /**\n * @deprecated Use `rfq` and `limitOrders`. `false` includes both (KyberSwap's `excludeRFQSources` leaves out RFQ\n * makers and limit orders together); each of `rfq` / `limitOrders` overrides it for its own sources.\n */\n excludeRfqSources?: boolean;\n /** KyberSwap source ids to leave out of routes. */\n excludedSources?: readonly string[];\n}\n\n/** Whether a kind of off-chain liquidity may be in a route. */\nexport type KyberSourceSetting = \"exclude\" | \"include\";\n\n/**\n * How long a quote whose route uses an RFQ maker stays executable, at most. The API states no expiry; measured\n * 2026-11-30 (README, \"RFQ and limit orders\"): one of seven RFQ routes built at the quote ran at 11 s and reverted at\n * 30 s. The module's `quoteTtlMs` still caps it.\n */\nexport const KYBER_RFQ_TTL_MS = 10_000;\n/**\n * The same for a route through a KyberSwap limit order: every limit-order route built at the quote still ran at 60 s\n * (the one followed further: at 91 s, reverting from 121 s). The module's `quoteTtlMs` (default 30 s) still caps it.\n */\nexport const KYBER_LIMIT_ORDER_TTL_MS = 30_000;\n\ninterface RouteSummary {\n tokenIn?: string;\n amountIn?: string;\n tokenOut?: string;\n amountOut?: string;\n amountInUsd?: string;\n amountOutUsd?: string;\n gas?: string;\n extraFee?: {feeAmount?: string; feeReceiver?: string; chargeFeeBy?: string; isInBps?: boolean};\n route?: {pool?: string; exchange?: string; poolType?: string}[][];\n routeID?: string;\n [k: string]: unknown;\n}\n\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^\\d{1,78}$/.test(v) ? BigInt(v) : typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null);\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: unknown, b: string): boolean => isAddr(a) && a.toLowerCase() === b.toLowerCase();\nconst sameText = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^\\d{1,80}$/.test(a) && /^\\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);\nconst apiToken = (t: string): string => (t === ZERO ? KYBER_NATIVE : t);\n/** \"rfq\" / \"limit-order\" / both, as a refusal names them. */\nconst offchainName = (offchain: string): string =>\n offchain.includes(\"rfq\") && offchain.includes(\"limit-order\") ? \"market maker's quote or limit order\" : offchain.includes(\"rfq\") ? \"market maker's quote\" : \"limit order\";\n/** An API text as it may appear in a refusal: one line, at most 120 characters. */\nconst short = (s: unknown): string => String(s ?? \"\").replace(/\\s+/g, \" \").slice(0, 120);\n\n/**\n * A quote's `gasEstimate`: KyberSwap's `routeSummary.gas` from `GET /routes` (asked with `gasInclude=true`) as canonical\n * digits, the same figure on a dry quote and on the execution quote built from that route. Undefined when the route\n * states none, zero, or a figure past the contract's ten digits: no figure is made up. See the README for how it\n * compares with the gas the built call used.\n */\nexport function kyberGasEstimate(routeGas: unknown): string | undefined {\n const gas = uint(routeGas);\n return gas !== null && gas > 0n && gas < 10_000_000_000n ? gas.toString() : undefined;\n}\n\n/**\n * The build's `gas` (`POST /route/build`) as the swap's {@link UnsignedTx.venueGas}: a decimal string from 21 000 to\n * 10 000 000 (`validVenueGas`), else undefined — a malformed figure is ignored, never refused. KyberSwap's model of the\n * route's gas (the same number as `routeSummary.gas` in every recording), so the engine takes it as a floor for the\n * limit the swap is sent with — `max(the account's estimate, it) × 1.3 + 100 000` — never as a ceiling.\n */\nfunction kyberBuildGas(gas: unknown): string | undefined {\n return validVenueGas(gas) ? gas : undefined;\n}\n\nconst ERC20_READS = parseAbi([\"function balanceOf(address) view returns (uint256)\", \"function allowance(address, address) view returns (uint256)\", \"function approve(address, uint256) returns (bool)\"]);\n\n/** The revert data an RPC error carries, at most 4 KB of it. */\nfunction revertData(e: unknown): Hex | null {\n const err = e as {data?: unknown; message?: unknown};\n const nested = err.data && typeof err.data === \"object\" ? (err.data as {data?: unknown}).data : undefined;\n for (const v of [err.data, nested]) if (typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v as Hex;\n return null;\n}\n/**\n * KyberSwap's own USD value of the output against the input, as basis points lost (pool impact and pool fees together).\n * Information for the user's \"be careful\" warning, never a refusal. null when KyberSwap does not price either side\n * (\"0\" means unpriced, not worthless) or the numbers are not plain decimals.\n */\nexport function kyberValueLossBps(amountInUsd: unknown, amountOutUsd: unknown): number | null {\n const num = (v: unknown) => (typeof v === \"string\" && /^\\d{1,15}(\\.\\d{1,30})?$/.test(v) ? Number(v) : null);\n const vin = num(amountInUsd), vout = num(amountOutUsd);\n if (vin === null || vout === null || vin <= 0 || vout <= 0) return null;\n return Math.min(10_000, Math.max(0, Math.round(((vin - vout) / vin) * 10_000)));\n}\n\n/** `Error(string)` from revert data, if that is what it is. */\nfunction revertString(e: unknown): string | null {\n const data = revertData(e);\n if (data) {\n try {\n // viem knows Error(string) and Panic(uint256) without an ABI.\n const r = decodeErrorResult({abi: [], data});\n if (r.errorName === \"Error\" && typeof r.args?.[0] === \"string\") return r.args[0].slice(0, 200);\n } catch {\n // not a plain revert string\n }\n }\n const m = e instanceof Error ? /execution reverted:?\\s*([^\\n]{1,160})/.exec(e.message) : null;\n return m ? m[1]! : null;\n}\n\nexport function kyberswapProvider(config: KyberswapProviderConfig = {}): CrossChainProvider {\n const legacy: KyberSourceSetting = config.excludeRfqSources === false ? \"include\" : \"exclude\";\n const setting = (v: unknown, name: string): KyberSourceSetting => {\n if (v === undefined) return legacy;\n if (v !== \"exclude\" && v !== \"include\") throw new TypeError(`kyberswap: ${name} must be \"exclude\" or \"include\"`);\n return v;\n };\n const rfqSetting = setting(config.rfq, \"rfq\");\n const limitOrderSetting = setting(config.limitOrders, \"limitOrders\");\n const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\\/+$/, \"\");\n const clientId = config.clientId ?? \"anywalletkit\";\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? 10_000;\n const enabledChains = config.enabledChains ? new Set(config.enabledChains) : null;\n // KyberSwap asked (2026-11-25): with a key, send X-Api-Key only, without x-client-id.\n // The build's `source` still carries the client id on-chain.\n const headers: Record<string, string> = config.apiKey ? {\"x-api-key\": config.apiKey} : {\"x-client-id\": clientId};\n const dryCache = new Map<string, {at: number; value: Promise<RoutesResult>}>();\n\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return kyberChain(id) && (!enabledChains || enabledChains.has(id)) ? id : null;\n };\n\n async function rpc(chainId: number, method: string, params: unknown[]): Promise<unknown> {\n let lastErr: unknown;\n for (const url of config.rpcUrls?.[chainId] ?? []) {\n try {\n const res = await fetch(url, {method: \"POST\", headers: {\"content-type\": \"application/json\"}, body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}), signal: timeoutSignal(12_000)});\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status}`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n const body = (await res.json()) as {result?: unknown; error?: {message?: string; data?: unknown}};\n if (body.error) throw Object.assign(new Error(body.error.message ?? \"rpc error\"), {rpc: true, data: body.error.data});\n return body.result ?? null;\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw e;\n lastErr = e;\n }\n }\n throw withReason(new Error(`kyberswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr ?? \"none configured\")})`), refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n type ApiResult = {ok: true; data: Record<string, unknown>} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function api(url: string, init: RequestInit, signal?: AbortSignal): Promise<ApiResult> {\n let res: Response;\n try {\n res = await fetch(url, {...init, headers: {...headers, ...(init.body ? {\"content-type\": \"application/json\"} : {})}, signal: signal ?? timeoutSignal(timeoutMs)});\n } catch (e) {\n return {ok: false, why: `API unreachable (${e instanceof Error ? e.name : \"error\"})`, ...(signal?.aborted ? {} : {info: \"upstream_unavailable\" as const})};\n }\n type Body = {code?: unknown; message?: unknown; data?: unknown};\n let body: Body | null;\n try {\n const parsed: unknown = await res.json();\n body = parsed && typeof parsed === \"object\" ? (parsed as Body) : null;\n } catch {\n body = null;\n }\n if (res.status === 429) return {ok: false, why: \"rate limited (HTTP 429)\", info: httpRefusal(429, res.headers?.get?.(\"retry-after\")) ?? \"rate_limited\"};\n if (res.status === 401 || res.status === 403) return {ok: false, why: `API key rejected (HTTP ${res.status})`, info: httpRefusal(res.status) ?? \"policy_refused\"};\n if (res.status === 404 && !body?.code) return {ok: false, why: \"KyberSwap does not serve this chain (HTTP 404)\", info: \"unsupported_pair\"};\n if (!res.ok || body?.code !== 0) {\n const code = typeof body?.code === \"number\" ? body.code : undefined;\n const reason = errorReason(code) ?? (res.status >= 500 ? \"upstream_unavailable\" : undefined);\n return {ok: false, why: `${code !== undefined ? `error ${code}` : `HTTP ${res.status}`}${body?.message ? `: ${short(body.message)}` : \"\"}`, ...(reason ? {info: reason} : {})};\n }\n if (!body?.data || typeof body.data !== \"object\") return {ok: false, why: \"malformed API response\", info: \"upstream_unavailable\"};\n return {ok: true, data: body.data as Record<string, unknown>};\n }\n\n /**\n * The source filters of every `GET /routes`, dry or for execution, so the route reviewed and the route built draw on\n * the same liquidity. Both excluded (the default): `excludeRFQSources=true`, as in 0.2.0. Limit orders without RFQ:\n * the chain's RFQ sources (`KYBER_RFQ_SOURCES`) in `excludedSources`; RFQ without limit orders: the limit-order source\n * there instead; both included: no filter.\n */\n function sourceFilters(q: URLSearchParams, chainId: number): void {\n const excluded: string[] = [];\n if (rfqSetting === \"exclude\" && limitOrderSetting === \"exclude\") q.set(\"excludeRFQSources\", \"true\");\n else if (rfqSetting === \"exclude\") excluded.push(...(Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : []));\n else if (limitOrderSetting === \"exclude\") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);\n for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);\n if (excluded.length) q.set(\"excludedSources\", excluded.join(\",\"));\n }\n\n type Offchain = {rfq: boolean; limitOrder: boolean};\n type RoutesResult = {ok: true; summary: RouteSummary; amountOut: bigint; sources: string[]; offchain: Offchain} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function routes(chainId: number, tokenIn: string, tokenOut: string, amountIn: bigint, signal?: AbortSignal): Promise<RoutesResult> {\n const q = new URLSearchParams({tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: \"true\"});\n sourceFilters(q, chainId);\n const r = await api(`${baseUrl}/${kyberChain(chainId)!.slug}/api/v1/routes?${q}`, {method: \"GET\"}, signal);\n if (!r.ok) return r;\n const summary = r.data.routeSummary as RouteSummary | undefined;\n const router = r.data.routerAddress;\n if (!summary || typeof summary !== \"object\") return {ok: false, why: \"malformed API response (no route)\", info: \"upstream_unavailable\"};\n if (same(router, KYBER_ROUTER_V3)) return {ok: false, why: \"Kyber router V3 not supported yet\", info: \"policy_refused\"};\n if (!same(router, KYBER_ROUTER_V2)) return {ok: false, why: \"the route settles through another router than the pinned one\", info: \"vault_mismatch\"};\n if (!same(summary.tokenIn, apiToken(tokenIn)) || !same(summary.tokenOut, apiToken(tokenOut))) return {ok: false, why: \"the route swaps other tokens than requested\", info: \"policy_refused\"};\n if (uint(summary.amountIn) !== amountIn) return {ok: false, why: \"the route prices another amount\", info: \"price_check_failed\"};\n const fee = summary.extraFee;\n // No fee is ever asked for: the API answers with empty fields (\"\" amount, \"\" receiver); anything else is refused.\n if (fee !== undefined && fee !== null) {\n const amount = fee.feeAmount === \"\" || fee.feeAmount === undefined ? 0n : uint(fee.feeAmount);\n if (typeof fee !== \"object\" || amount !== 0n || (fee.feeReceiver !== undefined && fee.feeReceiver !== \"\")) return {ok: false, why: \"the route carries an integrator fee\", info: \"policy_refused\"};\n }\n const amountOut = uint(summary.amountOut);\n if (amountOut === null || amountOut <= 0n) return {ok: false, why: \"the route pays nothing\", info: \"no_route\"};\n const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === \"object\") : [];\n const sources = [...new Set(hops.map((h) => h.exchange).filter((x): x is string => typeof x === \"string\"))].slice(0, 6).map((s) => s.slice(0, 40));\n const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));\n return {ok: true, summary, amountOut, sources, offchain: {rfq: kinds.has(\"rfq\"), limitOrder: kinds.has(\"limit-order\")}};\n }\n\n /**\n * Why the swap reverts for `sender` now: the price (the router's minimum check), the wallet's input, an RFQ quote or\n * limit order in the route that no longer fills, or the revert as it is.\n */\n async function revertReason(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>, e: unknown, offchain?: string): Promise<Error> {\n const text = revertString(e);\n if (text && /return amount is not enough|min return/i.test(text)) {\n return refusal(\"price_check_failed\", \"kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.\");\n }\n const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);\n if (lack) return refusal(\"simulation_failed\", lack);\n if (offchain) return refusal(\"quote_expired\", `kyberswap: the ${offchainName(offchain)} in this route no longer fills (expired or taken). Nothing was sent; refresh the quote.`);\n return refusal(\"simulation_failed\", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : \"revert\"))}). Nothing was sent; refresh the quote.`);\n }\n\n async function inputShortfall(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>): Promise<string | null> {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: quoted.data as Hex});\n const desc = (call.args[0] as {desc: {srcToken: string; amount: bigint}}).desc;\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n if (same(desc.srcToken, KYBER_NATIVE)) {\n const balance = word(await rpc(chainId, \"eth_getBalance\", [sender, \"latest\"]));\n return balance !== null && balance < desc.amount ? `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.` : null;\n }\n const read = (data: Hex) => rpc(chainId, \"eth_call\", [{to: desc.srcToken, data}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance != null && balance < desc.amount) return `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.`;\n if (allowance != null && allowance < desc.amount) return \"kyberswap: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.\";\n return null;\n }\n\n /**\n * A token sale is checked before the user pays for an approval: with the allowance already in place the exact call\n * runs against the latest block; without it the approval and the swap run as one simulated block (eth_simulateV1),\n * so a route that reverts never asks for an approval. A wallet without the input, or an RPC that cannot simulate a\n * block, skips the check (`null` with the reason in `skipped`) — preflightDeposit still simulates before signing.\n */\n async function tokenSwapCheck(chainId: number, sender: string, token: string, amount: bigint, data: Hex): Promise<{refusal: ReturnType<typeof refuseRevert> | null; simulated: string}> {\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n const read = (call: Hex) => rpc(chainId, \"eth_call\", [{to: token, data: call}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance == null || allowance == null) return {refusal: null, simulated: \"none\"};\n if (balance < amount) return {refusal: null, simulated: \"none\"};\n if (allowance >= amount) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}, \"latest\"]);\n return {refusal: null, simulated: \"swap\"};\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) return {refusal: refuseRevert(revertString(e)), simulated: \"swap\"};\n throw e;\n }\n }\n const approve = (n: bigint) => ({from: sender, to: token, data: encodeFunctionData({abi: ERC20_READS, functionName: \"approve\", args: [KYBER_ROUTER_V2, n]})});\n // A token that refuses to change a non-zero allowance (USDT) is reset first, as the wallet's own approval does.\n const calls = [...(allowance > 0n ? [approve(0n)] : []), approve(amount), {from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}];\n let result: unknown;\n try {\n result = await rpc(chainId, \"eth_simulateV1\", [{blockStateCalls: [{calls}], validation: false}, \"latest\"]);\n } catch {\n return {refusal: null, simulated: \"none\"};\n }\n type Call = {status?: unknown; returnData?: unknown; error?: {message?: unknown; data?: unknown}};\n const out = (Array.isArray(result) ? (result[0] as {calls?: Call[]} | undefined)?.calls : undefined) ?? [];\n if (out.length !== calls.length || out.slice(0, -1).some((c) => c.status !== \"0x1\")) return {refusal: null, simulated: \"none\"};\n const swap = out[out.length - 1]!;\n if (swap.status === \"0x1\") return {refusal: null, simulated: \"approve+swap\"};\n const err = {data: swap.error?.data ?? swap.returnData, message: typeof swap.error?.message === \"string\" ? swap.error.message : \"\"};\n return {refusal: refuseRevert(revertString(Object.assign(new Error(err.message), {data: err.data}))), simulated: \"approve+swap\"};\n }\n\n function refuseRevert(why: string | null): {why: string; reason: Swap2RefusalReason} {\n return {\n why: `the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`,\n reason: why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\",\n };\n }\n\n return {\n name: \"kyberswap\",\n describeActivity: describeKyberActivity,\n supportsSameChain: true,\n // The account's own estimate of the exact call, dry-run before broadcast: the limit is built on it (× 1.3 + 100 000),\n // with the build's gas as a floor (`venueGas`), never the API's figure alone.\n ownGasEstimate: true,\n // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.\n exactAllowanceOnly: kyberExactAllowanceOnly,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => {\n if (from.chain !== to.chain) return false;\n const id = chainIdOf(from.chain);\n if (id === null) return false;\n // Native ↔ wrapped is a wrap (the Wrap provider's), which KyberSwap does not route: no request is spent on it.\n const wrapped = Object.prototype.hasOwnProperty.call(WRAPPED_NATIVE, id) ? WRAPPED_NATIVE[id]!.address : null;\n const isNative = (t: string) => /^0x0+$/.test(t) || same(t, KYBER_NATIVE) || t === ccAssetByToken(from.chain, ZERO)?.symbol;\n const isWrapped = (t: string) => !!wrapped && (same(t, wrapped) || t === WRAPPED_NATIVE[id]!.symbol);\n return !((isNative(from.token) && isWrapped(to.token)) || (isWrapped(from.token) && isNative(to.token)));\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`kyberswap: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`KyberSwap is not enabled for ${params.sourceChain}`, \"unsupported_pair\");\n const chain = kyberChain(chainId)!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tokenIn = src.contract ? getAddress(src.contract) : ZERO;\n const nativeOut = /^0x0+$/.test(params.destToken) || same(params.destToken, KYBER_NATIVE);\n if (!nativeOut && !isAddr(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n const tokenOut = nativeOut ? ZERO : getAddress(params.destToken);\n // Refused before any request: a useless call spends the shared keyless quota.\n if (tokenIn === tokenOut) return refuse(\"same token in and out\", \"unsupported_pair\");\n if ((tokenIn === ZERO || tokenOut === ZERO) && !kyberNativeSwaps(chainId)) return refuse(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps <= 0 || bps >= 2_000) return refuse(\"invalid slippage (KyberSwap accepts under 20%)\", \"price_check_failed\");\n let floor = 0n;\n if (params.minAmountOut !== undefined) {\n const f = uint(params.minAmountOut);\n if (f === null) return refuse(\"minimum output is not an integer\");\n floor = f;\n }\n const dry = params.dry !== false;\n if (!dry && !isAddr(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n if (!dry && !config.rpcUrls?.[chainId]?.length) return refuse(`no RPC configured for ${chain.name}: a KyberSwap swap is simulated before it is signed`, \"upstream_unavailable\");\n\n // Dry quotes for the same request share one route for a few seconds; an execution quote always asks afresh.\n let r: RoutesResult;\n if (dry) {\n const key = `${chainId}|${tokenIn}|${tokenOut}|${amountIn}`;\n const hit = dryCache.get(key);\n if (hit && Date.now() - hit.at < DRY_CACHE_MS) r = await hit.value;\n else {\n const value = routes(chainId, tokenIn, tokenOut, amountIn, signal);\n dryCache.set(key, {at: Date.now(), value});\n if (dryCache.size > 64) for (const [k, v] of dryCache) if (Date.now() - v.at >= DRY_CACHE_MS) dryCache.delete(k);\n r = await value;\n if (!r.ok) dryCache.delete(key);\n }\n } else r = await routes(chainId, tokenIn, tokenOut, amountIn, signal);\n if (!r.ok) return refuse(r.why, r.info);\n // KyberSwap's minimum lands one unit under the plain floor; asking for a hair less slippage keeps it at or\n // above the engine's floor for the user's slippage (a tiny output needs more than 1 bps for that unit).\n const apiBps = kyberApiSlippage(r.amountOut, bps);\n if (apiBps === null) return refuse(\"the output is too small to carry a minimum\", \"amount_too_small\");\n const minOut = kyberMinimum(r.amountOut, apiBps);\n if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, \"price_check_failed\");\n\n // The route's own gas figure, for comparing routes. Execution builds its limit on the account's own estimate, with\n // the build's gas (`venueGas`) as a floor.\n const gasEstimate = kyberGasEstimate(r.summary.gas);\n // A route through an RFQ maker or a limit order lives no longer than that liquidity (KYBER_RFQ_TTL_MS, KYBER_LIMIT_ORDER_TTL_MS).\n const offchain = [...(r.offchain.rfq ? [\"rfq\"] : []), ...(r.offchain.limitOrder ? [\"limit-order\"] : [])].join(\",\");\n const life = Math.min(ttl, ...(r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : []), ...(r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []));\n const base = {\n provider: \"kyberswap\",\n intentId: `kyberswap:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n sourceAmount: amountIn.toString(),\n // KyberSwap's amountOut is the route's ceiling, not an average: the executed output came 1.5–7.4 bps under it.\n destAmount: r.amountOut.toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n ...(gasEstimate !== undefined ? {gasEstimate, gasEstimateSource: \"venue\" as const} : {}),\n etaSeconds: 15,\n reliability: 0.95,\n validUntilMs: Date.now() + life,\n } satisfies Partial<Quote>;\n const providerData: Record<string, string> = {\n amountOut: r.amountOut.toString(),\n minOut: minOut.toString(),\n apiSlippageBps: String(apiBps),\n ...(typeof r.summary.routeID === \"string\" ? {routeId: r.summary.routeID.slice(0, 80)} : {}),\n ...(r.sources.length ? {sources: r.sources.join(\",\")} : {}),\n ...(offchain ? {offchain} : {}),\n };\n // The router's quoteValues reads priceImpactBps into the user's \"be careful\" warning (Unichain USDC → JUP: −78 %).\n const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);\n if (lossBps !== null) providerData.priceImpactBps = String(lossBps);\n if (dry) {\n // A token sale approves the router first; the auction's gas estimate reads the spender from here.\n return {...base, providerData: tokenIn === ZERO ? providerData : {...providerData, approvalAddress: KYBER_ROUTER_V2}};\n }\n\n const receiver = getAddress(params.destAddress);\n const signer = isAddr(params.sender) ? params.sender : isAddr(params.refundAddress) ? params.refundAddress : params.destAddress;\n const sender = getAddress(signer);\n const built = await api(`${baseUrl}/${chain.slug}/api/v1/route/build`, {\n method: \"POST\",\n body: JSON.stringify({\n routeSummary: r.summary,\n sender,\n recipient: receiver,\n slippageTolerance: apiBps,\n deadline: Math.floor(Date.now() / 1000) + BUILD_DEADLINE_S,\n source: clientId,\n }),\n }, signal);\n if (!built.ok) return refuse(`build: ${built.why}`, built.info);\n const b = built.data;\n if (uint(b.amountIn) !== amountIn) return refuse(\"the build spends another amount\", \"price_check_failed\");\n // An RFQ maker signs (or the route falls back to the pool KyberSwap named after it) only now, and a limit order is\n // picked now: the build's amountOut is what this route pays, never more than the quote shown.\n let destAmount = r.amountOut;\n if (offchain) {\n const builtOut = uint(b.amountOut);\n if (builtOut === null) return refuse(\"malformed build response\", \"upstream_unavailable\");\n if (builtOut < minOut || builtOut < floor) return refuse(`the ${offchainName(offchain)} came in under the minimum when the route was built (${builtOut} < ${minOut}); refresh the quote`, \"price_check_failed\");\n if (builtOut < destAmount) destAmount = builtOut;\n }\n if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse(\"Kyber router V3 not supported yet\", \"policy_refused\");\n // KyberSwap's own gas figure for the built call: the floor of the limit the engine sends (`venueGas`), and the\n // quote's gasEstimate when the route stated none.\n const buildGas = kyberBuildGas(b.gas);\n const shownGas = base.gasEstimate === undefined && buildGas !== undefined ? kyberGasEstimate(buildGas) : undefined;\n const value = uint(b.transactionValue ?? \"0\");\n if (value === null || typeof b.data !== \"string\") return refuse(\"malformed build response\", \"upstream_unavailable\");\n const tx = {to: typeof b.routerAddress === \"string\" ? b.routerAddress : \"\", value, data: b.data};\n let decoded;\n try {\n decoded = checkKyberTransaction(tx, {chainId, tokenIn, tokenOut, amountIn, receiver, minAmountOut: minOut > floor ? minOut : floor});\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e));\n }\n // Native input needs no allowance: the exact call runs against the latest block now, so a route that would revert\n // never reaches the user. Token input is checked the same way before any approval (tokenSwapCheck).\n let simulated = \"swap\";\n if (tokenIn !== ZERO) {\n try {\n const check = await tokenSwapCheck(chainId, sender, tokenIn, amountIn, tx.data as Hex);\n if (check.refusal) return refuse(check.refusal.why, check.refusal.reason);\n simulated = check.simulated;\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n if (tokenIn === ZERO) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data: tx.data, value: `0x${value.toString(16)}`}, \"latest\", {[sender]: {balance: `0x${(value + 10n ** 18n).toString(16)}`}}]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) {\n const why = revertString(e);\n return refuse(`the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`, why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\");\n }\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n return {\n ...base,\n ...(shownGas !== undefined ? {gasEstimate: shownGas, gasEstimateSource: \"venue\" as const} : {}),\n destAmount: destAmount.toString(),\n minDestAmount: decoded.minReturnAmount.toString(),\n txRequest: {\n to: KYBER_ROUTER_V2,\n data: tx.data,\n value: value.toString(),\n chainId,\n ...(buildGas !== undefined ? {venueGas: buildGas} : {}),\n ...(tokenIn === ZERO ? {} : {approvalAddress: KYBER_ROUTER_V2}),\n },\n providerData: {...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated},\n };\n },\n\n /**\n * Simulate the exact quoted transaction from the account at the latest block (approval in place) and refuse when\n * it would revert or when no RPC answers — the API is not trusted, so an unsimulated swap is not sent.\n * Only the quote's own transaction is simulated, never a caller's.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const sender = quote.providerData?.sender;\n const quoted = quote.txRequest;\n if (!kyberChain(chainId) || !isAddr(sender)) throw refusal(\"policy_refused\", \"kyberswap: the quote is not an execution quote. Nothing was sent; refresh the quote.\");\n if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data ?? \"\", quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\")) {\n throw refusal(\"policy_refused\", \"kyberswap: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? \"0\").toString(16)}`}, \"latest\"]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === \"string\" ? quote.providerData.offchain : undefined);\n throw withReason(new Error(\"kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again.\"), refusalOf(e) ?? \"upstream_unavailable\");\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.venueGas !== undefined ? {venueGas: tx.venueGas} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!kyberChain(chainId) || !config.rpcUrls?.[chainId]?.length) return {state: \"pending\"};\n try {\n const receipt = (await rpc(chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash])) as {status?: string} | null;\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAQ,mBA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