@anywalletkit/protocol-swap2-kyberswap 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,21 @@
1
1
  import {
2
2
  describeKyberActivity
3
- } from "./chunk-FWC6K553.js";
3
+ } from "./chunk-HHZEL5IJ.js";
4
4
  import {
5
+ KYBER_LIMIT_ORDER_SOURCES,
5
6
  KYBER_NATIVE,
7
+ KYBER_RFQ_SOURCES,
6
8
  KYBER_ROUTER_ABI,
7
9
  KYBER_ROUTER_V2,
8
10
  KYBER_ROUTER_V3,
9
11
  checkKyberTransaction,
10
12
  kyberApiSlippage,
11
13
  kyberChain,
14
+ kyberExactAllowanceOnly,
12
15
  kyberMinimum,
13
- kyberNativeSwaps
14
- } from "./chunk-WOVGN3FL.js";
16
+ kyberNativeSwaps,
17
+ kyberSourceKind
18
+ } from "./chunk-D4UIDHM2.js";
15
19
 
16
20
  // src/provider.ts
17
21
  import { decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi } from "viem";
@@ -43,13 +47,20 @@ var ERROR_REASONS = {
43
47
  4227: "simulation_failed"
44
48
  };
45
49
  var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
50
+ var KYBER_RFQ_TTL_MS = 1e4;
51
+ var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
46
52
  var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
47
53
  var isAddr = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
48
54
  var same = (a, b) => isAddr(a) && a.toLowerCase() === b.toLowerCase();
49
55
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
50
56
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
51
57
  var apiToken = (t) => t === ZERO ? KYBER_NATIVE : t;
58
+ 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";
52
59
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
60
+ function kyberGasEstimate(routeGas) {
61
+ const gas = uint(routeGas);
62
+ return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
63
+ }
53
64
  var ERC20_READS = parseAbi(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
54
65
  function revertData(e) {
55
66
  const err = e;
@@ -76,6 +87,14 @@ function revertString(e) {
76
87
  return m ? m[1] : null;
77
88
  }
78
89
  function kyberswapProvider(config = {}) {
90
+ const legacy = config.excludeRfqSources === false ? "include" : "exclude";
91
+ const setting = (v, name) => {
92
+ if (v === void 0) return legacy;
93
+ if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
94
+ return v;
95
+ };
96
+ const rfqSetting = setting(config.rfq, "rfq");
97
+ const limitOrderSetting = setting(config.limitOrders, "limitOrders");
79
98
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
80
99
  const clientId = config.clientId ?? "anywalletkit";
81
100
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -134,10 +153,17 @@ function kyberswapProvider(config = {}) {
134
153
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
135
154
  return { ok: true, data: body.data };
136
155
  }
156
+ function sourceFilters(q, chainId) {
157
+ const excluded = [];
158
+ if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
159
+ else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
160
+ else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
161
+ for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
162
+ if (excluded.length) q.set("excludedSources", excluded.join(","));
163
+ }
137
164
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
138
165
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
139
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
140
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
166
+ sourceFilters(q, chainId);
141
167
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
142
168
  if (!r.ok) return r;
143
169
  const summary = r.data.routeSummary;
@@ -154,16 +180,19 @@ function kyberswapProvider(config = {}) {
154
180
  }
155
181
  const amountOut = uint(summary.amountOut);
156
182
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
157
- const sources = [...new Set((summary.route ?? []).flat().map((h) => h?.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
158
- return { ok: true, summary, amountOut, sources };
183
+ const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
184
+ const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
185
+ const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
186
+ return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
159
187
  }
160
- async function revertReason(chainId, sender, quoted, e) {
188
+ async function revertReason(chainId, sender, quoted, e, offchain) {
161
189
  const text = revertString(e);
162
190
  if (text && /return amount is not enough|min return/i.test(text)) {
163
191
  return refusal("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
164
192
  }
165
193
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
166
194
  if (lack) return refusal("simulation_failed", lack);
195
+ 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.`);
167
196
  return refusal("simulation_failed", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : "revert"))}). Nothing was sent; refresh the quote.`);
168
197
  }
169
198
  async function inputShortfall(chainId, sender, quoted) {
@@ -228,6 +257,8 @@ function kyberswapProvider(config = {}) {
228
257
  supportsSameChain: true,
229
258
  // The account's own estimate of the exact call, never the API's gas model.
230
259
  ownGasEstimate: true,
260
+ // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
261
+ exactAllowanceOnly: kyberExactAllowanceOnly,
231
262
  enabled: () => config.enabled ?? true,
232
263
  supportsChain: (caip2) => chainIdOf(caip2) !== null,
233
264
  supportsChainPair: (from, to) => from === to && chainIdOf(from) !== null,
@@ -296,6 +327,9 @@ function kyberswapProvider(config = {}) {
296
327
  if (apiBps === null) return refuse("the output is too small to carry a minimum", "amount_too_small");
297
328
  const minOut = kyberMinimum(r.amountOut, apiBps);
298
329
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
330
+ const gasEstimate = kyberGasEstimate(r.summary.gas);
331
+ const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
332
+ const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
299
333
  const base = {
300
334
  provider: "kyberswap",
301
335
  intentId: `kyberswap:${chainId}`,
@@ -306,16 +340,18 @@ function kyberswapProvider(config = {}) {
306
340
  destAmount: r.amountOut.toString(),
307
341
  minDestAmount: minOut.toString(),
308
342
  feeUsd: 0,
343
+ ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
309
344
  etaSeconds: 15,
310
345
  reliability: 0.95,
311
- validUntilMs: Date.now() + ttl
346
+ validUntilMs: Date.now() + life
312
347
  };
313
348
  const providerData = {
314
349
  amountOut: r.amountOut.toString(),
315
350
  minOut: minOut.toString(),
316
351
  apiSlippageBps: String(apiBps),
317
352
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
318
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
353
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
354
+ ...offchain ? { offchain } : {}
319
355
  };
320
356
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
321
357
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -339,6 +375,13 @@ function kyberswapProvider(config = {}) {
339
375
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
340
376
  const b = built.data;
341
377
  if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
378
+ let destAmount = r.amountOut;
379
+ if (offchain) {
380
+ const builtOut = uint(b.amountOut);
381
+ if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
382
+ 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");
383
+ if (builtOut < destAmount) destAmount = builtOut;
384
+ }
342
385
  if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
343
386
  const value = uint(b.transactionValue ?? "0");
344
387
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
@@ -372,6 +415,7 @@ function kyberswapProvider(config = {}) {
372
415
  }
373
416
  return {
374
417
  ...base,
418
+ destAmount: destAmount.toString(),
375
419
  minDestAmount: decoded.minReturnAmount.toString(),
376
420
  txRequest: {
377
421
  to: KYBER_ROUTER_V2,
@@ -399,7 +443,7 @@ function kyberswapProvider(config = {}) {
399
443
  try {
400
444
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
401
445
  } catch (e) {
402
- if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
446
+ if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
403
447
  throw withReason(new Error("kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again."), refusalOf(e) ?? "upstream_unavailable");
404
448
  }
405
449
  },
@@ -424,7 +468,10 @@ function kyberswapProvider(config = {}) {
424
468
  }
425
469
 
426
470
  export {
471
+ KYBER_RFQ_TTL_MS,
472
+ KYBER_LIMIT_ORDER_TTL_MS,
473
+ kyberGasEstimate,
427
474
  kyberValueLossBps,
428
475
  kyberswapProvider
429
476
  };
430
- //# sourceMappingURL=chunk-DEWODPQQ.js.map
477
+ //# sourceMappingURL=chunk-NFMHUXU6.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 {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_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 = 50;\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\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, never the API's gas model.\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 still sends the account's own estimate.\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 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 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 ...(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.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,mBAAmB,oBAAoB,oBAAoB,YAAY,gBAAyB;AACxG,SAAQ,QAAQ,OAAO,eAAe,qBAAoB;AAC1D,SAAQ,aAAa,SAAS,WAAW,kBAAiE;AAE1G,SAAQ,sBAAqB;AAC7B,SAAQ,sBAAqB;AAkB7B,IAAM,OAAO;AACb,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AACzB,IAAM,uBAAuB;AAE7B,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,mBAAmB,KAAK;AAM9B,IAAM,gBAA8D;AAAA,EAClE,KAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,OAAO;AAAA,EAC/H,MAAM;AAAA,EAAY,OAAO;AAAA,EACzB,MAAM;AAAA,EAA0B,MAAM;AAAA,EACtC,MAAM;AAAA,EAAoB,MAAM;AAAA,EAChC,MAAM;AAAA,EACN,MAAM;AACR;AACA,IAAM,cAAc,CAAC,SACnB,OAAO,SAAS,YAAY,OAAO,UAAU,eAAe,KAAK,eAAe,IAAI,IAAI,cAAc,IAAI,IAAI;AAyCzG,IAAM,mBAAmB;AAKzB,IAAM,2BAA2B;AAg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O,UAAS;AACxF,UAAI;AACF,cAAM,UAAW,MAAM,IAAI,SAAS,6BAA6B,CAAC,IAAI,YAAY,CAAC;AACnF,YAAI,CAAC,QAAS,QAAO,EAAC,OAAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;","names":["balance","value"]}
package/dist/index.cjs CHANGED
@@ -24,8 +24,12 @@ __export(src_exports, {
24
24
  KYBER_CHAINS: () => KYBER_CHAINS,
25
25
  KYBER_EXECUTOR: () => KYBER_EXECUTOR,
26
26
  KYBER_FLAGS_ALLOWED: () => KYBER_FLAGS_ALLOWED,
27
+ KYBER_LIMIT_ORDER_SOURCES: () => KYBER_LIMIT_ORDER_SOURCES,
28
+ KYBER_LIMIT_ORDER_TTL_MS: () => KYBER_LIMIT_ORDER_TTL_MS,
27
29
  KYBER_NATIVE: () => KYBER_NATIVE,
28
30
  KYBER_REFUSED_SELECTORS: () => KYBER_REFUSED_SELECTORS,
31
+ KYBER_RFQ_SOURCES: () => KYBER_RFQ_SOURCES,
32
+ KYBER_RFQ_TTL_MS: () => KYBER_RFQ_TTL_MS,
29
33
  KYBER_ROUTER_ABI: () => KYBER_ROUTER_ABI,
30
34
  KYBER_ROUTER_V2: () => KYBER_ROUTER_V2,
31
35
  KYBER_ROUTER_V3: () => KYBER_ROUTER_V3,
@@ -37,9 +41,12 @@ __export(src_exports, {
37
41
  describeKyberActivity: () => describeKyberActivity,
38
42
  kyberApiSlippage: () => kyberApiSlippage,
39
43
  kyberChain: () => kyberChain,
44
+ kyberExactAllowanceOnly: () => kyberExactAllowanceOnly,
45
+ kyberGasEstimate: () => kyberGasEstimate,
40
46
  kyberMinimum: () => kyberMinimum,
41
47
  kyberNativeSwaps: () => kyberNativeSwaps,
42
48
  kyberPins: () => kyberPins,
49
+ kyberSourceKind: () => kyberSourceKind,
43
50
  kyberValueLossBps: () => kyberValueLossBps,
44
51
  kyberVerifyQuote: () => kyberVerifyQuote,
45
52
  kyberswapProvider: () => kyberswapProvider
@@ -87,6 +94,34 @@ var KYBER_CHAINS = Object.freeze({
87
94
  5042: { slug: "arc", name: "Arc", build: "lite" },
88
95
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
89
96
  });
97
+ var KYBER_LIMIT_ORDER_SOURCES = Object.freeze(["kyberswap-limit-order-v2"]);
98
+ var KYBER_RFQ_SOURCES = Object.freeze({
99
+ 1: ["bebop", "clear-rfq", "hashflow-v3", "native-v1", "native-v2", "pmm-1", "pmm-10", "pmm-11", "pmm-12", "pmm-18", "pmm-2", "pmm-20", "pmm-3", "pmm-4", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
100
+ 8453: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-1", "pmm-13", "pmm-14", "pmm-18", "pmm-19", "pmm-2", "pmm-20", "pmm-21", "pmm-4", "pmm-5", "pmm-8"],
101
+ 56: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-1", "pmm-10", "pmm-13", "pmm-18", "pmm-19", "pmm-2", "pmm-20", "pmm-5", "pmm-8", "swaap-v2"],
102
+ 42161: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-13", "pmm-2", "pmm-21", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
103
+ 10: ["bebop", "pmm-13", "swaap-v2"],
104
+ 137: ["bebop", "native-v1", "pmm-5", "pmm-8", "swaap-v2"],
105
+ 43114: ["bebop", "dexalot", "hashflow-v3", "native-v1", "pmm-4", "swaap-v2"],
106
+ 59144: ["native-v1", "swaap-v2"],
107
+ 146: ["swaap-v2"],
108
+ 80094: ["bebop"],
109
+ 130: [],
110
+ 999: ["bebop"],
111
+ 9745: [],
112
+ 143: ["native-v2", "swaap-v2"],
113
+ 4326: [],
114
+ 4663: ["bebop", "native-v2", "pmm-18", "pmm-19", "pmm-20", "swaap-v2"],
115
+ 5042: ["pmm-13"],
116
+ 99901: []
117
+ });
118
+ var RFQ_LIKE = /^(?:pmm-\d+|kyber-pmm|native-v\d+|bebop|hashflow(?:-v\d+)?|swaap-v\d+|clipper|dexalot|mx-trading|[a-z0-9-]*-rfq|rfq-[a-z0-9-]*)$/;
119
+ function kyberSourceKind(chainId, exchange, poolType) {
120
+ const id = typeof exchange === "string" ? exchange.split("/")[0] : "";
121
+ if (poolType === "limit-order" || /^kyberswap-limit-order(?:-v\d+)?$/.test(id)) return "limit-order";
122
+ const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : [];
123
+ return poolType === "orderbook" || listed.includes(id) || RFQ_LIKE.test(id) ? "rfq" : "pool";
124
+ }
90
125
  function kyberChain(chainId) {
91
126
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
92
127
  }
@@ -214,9 +249,13 @@ function kyberVerifyQuote(params, quote) {
214
249
  function routerFor(chain) {
215
250
  return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
216
251
  }
252
+ function kyberExactAllowanceOnly(chain) {
253
+ return kyberChain(chainIdOf(chain))?.build !== "lite";
254
+ }
217
255
  var kyberPins = Object.freeze({
218
256
  callTargets: routerFor,
219
257
  spenders: routerFor,
258
+ exactAllowanceOnly: kyberExactAllowanceOnly,
220
259
  verifyQuote: kyberVerifyQuote,
221
260
  reasonOf: (refusal2) => notes.reasonOf(refusal2)
222
261
  });
@@ -254,13 +293,20 @@ var ERROR_REASONS = {
254
293
  4227: "simulation_failed"
255
294
  };
256
295
  var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
296
+ var KYBER_RFQ_TTL_MS = 1e4;
297
+ var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
257
298
  var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
258
299
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
259
300
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
260
301
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
261
302
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
262
303
  var apiToken = (t) => t === ZERO2 ? KYBER_NATIVE : t;
304
+ 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";
263
305
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
306
+ function kyberGasEstimate(routeGas) {
307
+ const gas = uint(routeGas);
308
+ return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
309
+ }
264
310
  var ERC20_READS = (0, import_viem2.parseAbi)(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
265
311
  function revertData(e) {
266
312
  const err = e;
@@ -287,6 +333,14 @@ function revertString(e) {
287
333
  return m ? m[1] : null;
288
334
  }
289
335
  function kyberswapProvider(config = {}) {
336
+ const legacy = config.excludeRfqSources === false ? "include" : "exclude";
337
+ const setting = (v, name) => {
338
+ if (v === void 0) return legacy;
339
+ if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
340
+ return v;
341
+ };
342
+ const rfqSetting = setting(config.rfq, "rfq");
343
+ const limitOrderSetting = setting(config.limitOrders, "limitOrders");
290
344
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
291
345
  const clientId = config.clientId ?? "anywalletkit";
292
346
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -345,10 +399,17 @@ function kyberswapProvider(config = {}) {
345
399
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
346
400
  return { ok: true, data: body.data };
347
401
  }
402
+ function sourceFilters(q, chainId) {
403
+ const excluded = [];
404
+ if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
405
+ else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
406
+ else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
407
+ for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
408
+ if (excluded.length) q.set("excludedSources", excluded.join(","));
409
+ }
348
410
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
349
411
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
350
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
351
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
412
+ sourceFilters(q, chainId);
352
413
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
353
414
  if (!r.ok) return r;
354
415
  const summary = r.data.routeSummary;
@@ -365,16 +426,19 @@ function kyberswapProvider(config = {}) {
365
426
  }
366
427
  const amountOut = uint(summary.amountOut);
367
428
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
368
- const sources = [...new Set((summary.route ?? []).flat().map((h) => h?.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
369
- return { ok: true, summary, amountOut, sources };
429
+ const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
430
+ const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
431
+ const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
432
+ return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
370
433
  }
371
- async function revertReason(chainId, sender, quoted, e) {
434
+ async function revertReason(chainId, sender, quoted, e, offchain) {
372
435
  const text = revertString(e);
373
436
  if (text && /return amount is not enough|min return/i.test(text)) {
374
437
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
375
438
  }
376
439
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
377
440
  if (lack) return (0, import_errors2.refusal)("simulation_failed", lack);
441
+ if (offchain) return (0, import_errors2.refusal)("quote_expired", `kyberswap: the ${offchainName(offchain)} in this route no longer fills (expired or taken). Nothing was sent; refresh the quote.`);
378
442
  return (0, import_errors2.refusal)("simulation_failed", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : "revert"))}). Nothing was sent; refresh the quote.`);
379
443
  }
380
444
  async function inputShortfall(chainId, sender, quoted) {
@@ -439,6 +503,8 @@ function kyberswapProvider(config = {}) {
439
503
  supportsSameChain: true,
440
504
  // The account's own estimate of the exact call, never the API's gas model.
441
505
  ownGasEstimate: true,
506
+ // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
507
+ exactAllowanceOnly: kyberExactAllowanceOnly,
442
508
  enabled: () => config.enabled ?? true,
443
509
  supportsChain: (caip2) => chainIdOf2(caip2) !== null,
444
510
  supportsChainPair: (from, to) => from === to && chainIdOf2(from) !== null,
@@ -507,6 +573,9 @@ function kyberswapProvider(config = {}) {
507
573
  if (apiBps === null) return refuse("the output is too small to carry a minimum", "amount_too_small");
508
574
  const minOut = kyberMinimum(r.amountOut, apiBps);
509
575
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
576
+ const gasEstimate = kyberGasEstimate(r.summary.gas);
577
+ const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
578
+ const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
510
579
  const base = {
511
580
  provider: "kyberswap",
512
581
  intentId: `kyberswap:${chainId}`,
@@ -517,16 +586,18 @@ function kyberswapProvider(config = {}) {
517
586
  destAmount: r.amountOut.toString(),
518
587
  minDestAmount: minOut.toString(),
519
588
  feeUsd: 0,
589
+ ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
520
590
  etaSeconds: 15,
521
591
  reliability: 0.95,
522
- validUntilMs: Date.now() + ttl
592
+ validUntilMs: Date.now() + life
523
593
  };
524
594
  const providerData = {
525
595
  amountOut: r.amountOut.toString(),
526
596
  minOut: minOut.toString(),
527
597
  apiSlippageBps: String(apiBps),
528
598
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
529
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
599
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
600
+ ...offchain ? { offchain } : {}
530
601
  };
531
602
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
532
603
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -550,6 +621,13 @@ function kyberswapProvider(config = {}) {
550
621
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
551
622
  const b = built.data;
552
623
  if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
624
+ let destAmount = r.amountOut;
625
+ if (offchain) {
626
+ const builtOut = uint(b.amountOut);
627
+ if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
628
+ 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");
629
+ if (builtOut < destAmount) destAmount = builtOut;
630
+ }
553
631
  if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
554
632
  const value = uint(b.transactionValue ?? "0");
555
633
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
@@ -583,6 +661,7 @@ function kyberswapProvider(config = {}) {
583
661
  }
584
662
  return {
585
663
  ...base,
664
+ destAmount: destAmount.toString(),
586
665
  minDestAmount: decoded.minReturnAmount.toString(),
587
666
  txRequest: {
588
667
  to: KYBER_ROUTER_V2,
@@ -610,7 +689,7 @@ function kyberswapProvider(config = {}) {
610
689
  try {
611
690
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
612
691
  } catch (e) {
613
- if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
692
+ if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
614
693
  throw (0, import_errors2.withReason)(new Error("kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again."), (0, import_errors2.refusalOf)(e) ?? "upstream_unavailable");
615
694
  }
616
695
  },