@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/dist/index.cjs CHANGED
@@ -22,10 +22,15 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  KYBERSWAP_MODULE: () => KYBERSWAP_MODULE,
24
24
  KYBER_CHAINS: () => KYBER_CHAINS,
25
+ KYBER_DEFAULT_SLIPPAGE_BPS: () => KYBER_DEFAULT_SLIPPAGE_BPS,
25
26
  KYBER_EXECUTOR: () => KYBER_EXECUTOR,
26
27
  KYBER_FLAGS_ALLOWED: () => KYBER_FLAGS_ALLOWED,
28
+ KYBER_LIMIT_ORDER_SOURCES: () => KYBER_LIMIT_ORDER_SOURCES,
29
+ KYBER_LIMIT_ORDER_TTL_MS: () => KYBER_LIMIT_ORDER_TTL_MS,
27
30
  KYBER_NATIVE: () => KYBER_NATIVE,
28
31
  KYBER_REFUSED_SELECTORS: () => KYBER_REFUSED_SELECTORS,
32
+ KYBER_RFQ_SOURCES: () => KYBER_RFQ_SOURCES,
33
+ KYBER_RFQ_TTL_MS: () => KYBER_RFQ_TTL_MS,
29
34
  KYBER_ROUTER_ABI: () => KYBER_ROUTER_ABI,
30
35
  KYBER_ROUTER_V2: () => KYBER_ROUTER_V2,
31
36
  KYBER_ROUTER_V3: () => KYBER_ROUTER_V3,
@@ -42,6 +47,7 @@ __export(src_exports, {
42
47
  kyberMinimum: () => kyberMinimum,
43
48
  kyberNativeSwaps: () => kyberNativeSwaps,
44
49
  kyberPins: () => kyberPins,
50
+ kyberSourceKind: () => kyberSourceKind,
45
51
  kyberValueLossBps: () => kyberValueLossBps,
46
52
  kyberVerifyQuote: () => kyberVerifyQuote,
47
53
  kyberswapProvider: () => kyberswapProvider
@@ -51,6 +57,7 @@ module.exports = __toCommonJS(src_exports);
51
57
  // src/provider.ts
52
58
  var import_viem2 = require("viem");
53
59
  var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
60
+ var import_validate = require("@anywalletkit/protocol-swap2-core/validate");
54
61
  var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
55
62
  var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
56
63
  var import_provider = require("@anywalletkit/protocol-swap2-wrap/provider");
@@ -89,6 +96,34 @@ var KYBER_CHAINS = Object.freeze({
89
96
  5042: { slug: "arc", name: "Arc", build: "lite" },
90
97
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
91
98
  });
99
+ var KYBER_LIMIT_ORDER_SOURCES = Object.freeze(["kyberswap-limit-order-v2"]);
100
+ var KYBER_RFQ_SOURCES = Object.freeze({
101
+ 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"],
102
+ 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"],
103
+ 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"],
104
+ 42161: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-13", "pmm-2", "pmm-21", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
105
+ 10: ["bebop", "pmm-13", "swaap-v2"],
106
+ 137: ["bebop", "native-v1", "pmm-5", "pmm-8", "swaap-v2"],
107
+ 43114: ["bebop", "dexalot", "hashflow-v3", "native-v1", "pmm-4", "swaap-v2"],
108
+ 59144: ["native-v1", "swaap-v2"],
109
+ 146: ["swaap-v2"],
110
+ 80094: ["bebop"],
111
+ 130: [],
112
+ 999: ["bebop"],
113
+ 9745: [],
114
+ 143: ["native-v2", "swaap-v2"],
115
+ 4326: [],
116
+ 4663: ["bebop", "native-v2", "pmm-18", "pmm-19", "pmm-20", "swaap-v2"],
117
+ 5042: ["pmm-13"],
118
+ 99901: []
119
+ });
120
+ 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-]*)$/;
121
+ function kyberSourceKind(chainId, exchange, poolType) {
122
+ const id = typeof exchange === "string" ? exchange.split("/")[0] : "";
123
+ if (poolType === "limit-order" || /^kyberswap-limit-order(?:-v\d+)?$/.test(id)) return "limit-order";
124
+ const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : [];
125
+ return poolType === "orderbook" || listed.includes(id) || RFQ_LIKE.test(id) ? "rfq" : "pool";
126
+ }
92
127
  function kyberChain(chainId) {
93
128
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
94
129
  }
@@ -178,6 +213,7 @@ function kyberApiSlippage(amountOut, bps) {
178
213
  for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;
179
214
  return null;
180
215
  }
216
+ var KYBER_DEFAULT_SLIPPAGE_BPS = 50;
181
217
  var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
182
218
  function kyberVerifyQuote(params, quote) {
183
219
  if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
@@ -190,8 +226,9 @@ function kyberVerifyQuote(params, quote) {
190
226
  const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
191
227
  if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
192
228
  if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
193
- const bps = params.slippageBps;
194
- if (bps !== void 0 && Number.isInteger(bps) && bps >= 0 && bps < 1e4 && min < kyberMinimum(out, bps)) {
229
+ const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;
230
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return notes.note("invalid slippage", "policy_refused");
231
+ if (min < kyberMinimum(out, bps)) {
195
232
  return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
196
233
  }
197
234
  const tx = quote.txRequest;
@@ -223,6 +260,9 @@ var kyberPins = Object.freeze({
223
260
  callTargets: routerFor,
224
261
  spenders: routerFor,
225
262
  exactAllowanceOnly: kyberExactAllowanceOnly,
263
+ // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate
264
+ // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.
265
+ ownGasEstimate: true,
226
266
  verifyQuote: kyberVerifyQuote,
227
267
  reasonOf: (refusal2) => notes.reasonOf(refusal2)
228
268
  });
@@ -239,7 +279,7 @@ function describeKyberActivity(tx, ctx) {
239
279
  var ZERO2 = "0x0000000000000000000000000000000000000000";
240
280
  var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
241
281
  var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
242
- var DEFAULT_SLIPPAGE_BPS = 50;
282
+ var DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;
243
283
  var DEFAULT_TTL_MS = 3e4;
244
284
  var DRY_CACHE_MS = 5e3;
245
285
  var BUILD_DEADLINE_S = 20 * 60;
@@ -260,17 +300,23 @@ var ERROR_REASONS = {
260
300
  4227: "simulation_failed"
261
301
  };
262
302
  var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
303
+ var KYBER_RFQ_TTL_MS = 1e4;
304
+ var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
263
305
  var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
264
306
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
265
307
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
266
308
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
267
309
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
268
310
  var apiToken = (t) => t === ZERO2 ? KYBER_NATIVE : t;
311
+ 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";
269
312
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
270
313
  function kyberGasEstimate(routeGas) {
271
314
  const gas = uint(routeGas);
272
315
  return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
273
316
  }
317
+ function kyberBuildGas(gas) {
318
+ return (0, import_validate.validVenueGas)(gas) ? gas : void 0;
319
+ }
274
320
  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)"]);
275
321
  function revertData(e) {
276
322
  const err = e;
@@ -297,6 +343,14 @@ function revertString(e) {
297
343
  return m ? m[1] : null;
298
344
  }
299
345
  function kyberswapProvider(config = {}) {
346
+ const legacy = config.excludeRfqSources === false ? "include" : "exclude";
347
+ const setting = (v, name) => {
348
+ if (v === void 0) return legacy;
349
+ if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
350
+ return v;
351
+ };
352
+ const rfqSetting = setting(config.rfq, "rfq");
353
+ const limitOrderSetting = setting(config.limitOrders, "limitOrders");
300
354
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
301
355
  const clientId = config.clientId ?? "anywalletkit";
302
356
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -355,10 +409,17 @@ function kyberswapProvider(config = {}) {
355
409
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
356
410
  return { ok: true, data: body.data };
357
411
  }
412
+ function sourceFilters(q, chainId) {
413
+ const excluded = [];
414
+ if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
415
+ else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
416
+ else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
417
+ for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
418
+ if (excluded.length) q.set("excludedSources", excluded.join(","));
419
+ }
358
420
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
359
421
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
360
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
361
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
422
+ sourceFilters(q, chainId);
362
423
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
363
424
  if (!r.ok) return r;
364
425
  const summary = r.data.routeSummary;
@@ -375,16 +436,19 @@ function kyberswapProvider(config = {}) {
375
436
  }
376
437
  const amountOut = uint(summary.amountOut);
377
438
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
378
- 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));
379
- return { ok: true, summary, amountOut, sources };
439
+ const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
440
+ const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
441
+ const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
442
+ return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
380
443
  }
381
- async function revertReason(chainId, sender, quoted, e) {
444
+ async function revertReason(chainId, sender, quoted, e, offchain) {
382
445
  const text = revertString(e);
383
446
  if (text && /return amount is not enough|min return/i.test(text)) {
384
447
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
385
448
  }
386
449
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
387
450
  if (lack) return (0, import_errors2.refusal)("simulation_failed", lack);
451
+ 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.`);
388
452
  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.`);
389
453
  }
390
454
  async function inputShortfall(chainId, sender, quoted) {
@@ -447,7 +511,8 @@ function kyberswapProvider(config = {}) {
447
511
  name: "kyberswap",
448
512
  describeActivity: describeKyberActivity,
449
513
  supportsSameChain: true,
450
- // The account's own estimate of the exact call, never the API's gas model.
514
+ // The account's own estimate of the exact call, dry-run before broadcast: the limit is built on it (× 1.3 + 100 000),
515
+ // with the build's gas as a floor (`venueGas`), never the API's figure alone.
451
516
  ownGasEstimate: true,
452
517
  // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
453
518
  exactAllowanceOnly: kyberExactAllowanceOnly,
@@ -520,6 +585,8 @@ function kyberswapProvider(config = {}) {
520
585
  const minOut = kyberMinimum(r.amountOut, apiBps);
521
586
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
522
587
  const gasEstimate = kyberGasEstimate(r.summary.gas);
588
+ const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
589
+ const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
523
590
  const base = {
524
591
  provider: "kyberswap",
525
592
  intentId: `kyberswap:${chainId}`,
@@ -533,14 +600,15 @@ function kyberswapProvider(config = {}) {
533
600
  ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
534
601
  etaSeconds: 15,
535
602
  reliability: 0.95,
536
- validUntilMs: Date.now() + ttl
603
+ validUntilMs: Date.now() + life
537
604
  };
538
605
  const providerData = {
539
606
  amountOut: r.amountOut.toString(),
540
607
  minOut: minOut.toString(),
541
608
  apiSlippageBps: String(apiBps),
542
609
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
543
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
610
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
611
+ ...offchain ? { offchain } : {}
544
612
  };
545
613
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
546
614
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -564,7 +632,16 @@ function kyberswapProvider(config = {}) {
564
632
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
565
633
  const b = built.data;
566
634
  if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
635
+ let destAmount = r.amountOut;
636
+ if (offchain) {
637
+ const builtOut = uint(b.amountOut);
638
+ if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
639
+ 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");
640
+ if (builtOut < destAmount) destAmount = builtOut;
641
+ }
567
642
  if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
643
+ const buildGas = kyberBuildGas(b.gas);
644
+ const shownGas = base.gasEstimate === void 0 && buildGas !== void 0 ? kyberGasEstimate(buildGas) : void 0;
568
645
  const value = uint(b.transactionValue ?? "0");
569
646
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
570
647
  const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
@@ -597,12 +674,15 @@ function kyberswapProvider(config = {}) {
597
674
  }
598
675
  return {
599
676
  ...base,
677
+ ...shownGas !== void 0 ? { gasEstimate: shownGas, gasEstimateSource: "venue" } : {},
678
+ destAmount: destAmount.toString(),
600
679
  minDestAmount: decoded.minReturnAmount.toString(),
601
680
  txRequest: {
602
681
  to: KYBER_ROUTER_V2,
603
682
  data: tx.data,
604
683
  value: value.toString(),
605
684
  chainId,
685
+ ...buildGas !== void 0 ? { venueGas: buildGas } : {},
606
686
  ...tokenIn === ZERO2 ? {} : { approvalAddress: KYBER_ROUTER_V2 }
607
687
  },
608
688
  providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
@@ -624,14 +704,14 @@ function kyberswapProvider(config = {}) {
624
704
  try {
625
705
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
626
706
  } catch (e) {
627
- if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
707
+ if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
628
708
  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");
629
709
  }
630
710
  },
631
711
  async buildDeposit(quote) {
632
712
  const tx = quote.txRequest;
633
713
  if (!tx?.to || !tx.data) throw (0, import_errors2.refusal)("policy_refused", "swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)");
634
- return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
714
+ 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 } : {} };
635
715
  },
636
716
  async trackIntent(ref) {
637
717
  if (!ref.sourceTxHash) return { state: "pending" };