@anywalletkit/protocol-swap2-kyberswap 0.2.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.
package/dist/protocol.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  KyberswapSwap2Protocol
3
- } from "./chunk-LO4G4NX7.js";
4
- import "./chunk-RZ2CCM34.js";
5
- import "./chunk-5ZMVXS7P.js";
6
- import "./chunk-OHBN7OQI.js";
3
+ } from "./chunk-LIEIWIYI.js";
4
+ import "./chunk-NFMHUXU6.js";
5
+ import "./chunk-HHZEL5IJ.js";
6
+ import "./chunk-D4UIDHM2.js";
7
7
  export {
8
8
  KyberswapSwap2Protocol
9
9
  };
package/dist/provider.cjs CHANGED
@@ -20,6 +20,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/provider.ts
21
21
  var provider_exports = {};
22
22
  __export(provider_exports, {
23
+ KYBER_LIMIT_ORDER_TTL_MS: () => KYBER_LIMIT_ORDER_TTL_MS,
24
+ KYBER_RFQ_TTL_MS: () => KYBER_RFQ_TTL_MS,
23
25
  kyberGasEstimate: () => kyberGasEstimate,
24
26
  kyberValueLossBps: () => kyberValueLossBps,
25
27
  kyberswapProvider: () => kyberswapProvider
@@ -65,6 +67,34 @@ var KYBER_CHAINS = Object.freeze({
65
67
  5042: { slug: "arc", name: "Arc", build: "lite" },
66
68
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
67
69
  });
70
+ var KYBER_LIMIT_ORDER_SOURCES = Object.freeze(["kyberswap-limit-order-v2"]);
71
+ var KYBER_RFQ_SOURCES = Object.freeze({
72
+ 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"],
73
+ 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"],
74
+ 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"],
75
+ 42161: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-13", "pmm-2", "pmm-21", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
76
+ 10: ["bebop", "pmm-13", "swaap-v2"],
77
+ 137: ["bebop", "native-v1", "pmm-5", "pmm-8", "swaap-v2"],
78
+ 43114: ["bebop", "dexalot", "hashflow-v3", "native-v1", "pmm-4", "swaap-v2"],
79
+ 59144: ["native-v1", "swaap-v2"],
80
+ 146: ["swaap-v2"],
81
+ 80094: ["bebop"],
82
+ 130: [],
83
+ 999: ["bebop"],
84
+ 9745: [],
85
+ 143: ["native-v2", "swaap-v2"],
86
+ 4326: [],
87
+ 4663: ["bebop", "native-v2", "pmm-18", "pmm-19", "pmm-20", "swaap-v2"],
88
+ 5042: ["pmm-13"],
89
+ 99901: []
90
+ });
91
+ 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-]*)$/;
92
+ function kyberSourceKind(chainId, exchange, poolType) {
93
+ const id = typeof exchange === "string" ? exchange.split("/")[0] : "";
94
+ if (poolType === "limit-order" || /^kyberswap-limit-order(?:-v\d+)?$/.test(id)) return "limit-order";
95
+ const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : [];
96
+ return poolType === "orderbook" || listed.includes(id) || RFQ_LIKE.test(id) ? "rfq" : "pool";
97
+ }
68
98
  function kyberChain(chainId) {
69
99
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
70
100
  }
@@ -236,12 +266,15 @@ var ERROR_REASONS = {
236
266
  4227: "simulation_failed"
237
267
  };
238
268
  var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
269
+ var KYBER_RFQ_TTL_MS = 1e4;
270
+ var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
239
271
  var uint = (v) => typeof v === "string" && /^\d{1,78}$/.test(v) ? BigInt(v) : typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null;
240
272
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
241
273
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
242
274
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
243
275
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
244
276
  var apiToken = (t) => t === ZERO2 ? KYBER_NATIVE : t;
277
+ 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";
245
278
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
246
279
  function kyberGasEstimate(routeGas) {
247
280
  const gas = uint(routeGas);
@@ -273,6 +306,14 @@ function revertString(e) {
273
306
  return m ? m[1] : null;
274
307
  }
275
308
  function kyberswapProvider(config = {}) {
309
+ const legacy = config.excludeRfqSources === false ? "include" : "exclude";
310
+ const setting = (v, name) => {
311
+ if (v === void 0) return legacy;
312
+ if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
313
+ return v;
314
+ };
315
+ const rfqSetting = setting(config.rfq, "rfq");
316
+ const limitOrderSetting = setting(config.limitOrders, "limitOrders");
276
317
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
277
318
  const clientId = config.clientId ?? "anywalletkit";
278
319
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -331,10 +372,17 @@ function kyberswapProvider(config = {}) {
331
372
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
332
373
  return { ok: true, data: body.data };
333
374
  }
375
+ function sourceFilters(q, chainId) {
376
+ const excluded = [];
377
+ if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
378
+ else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
379
+ else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
380
+ for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
381
+ if (excluded.length) q.set("excludedSources", excluded.join(","));
382
+ }
334
383
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
335
384
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
336
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
337
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
385
+ sourceFilters(q, chainId);
338
386
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
339
387
  if (!r.ok) return r;
340
388
  const summary = r.data.routeSummary;
@@ -351,16 +399,19 @@ function kyberswapProvider(config = {}) {
351
399
  }
352
400
  const amountOut = uint(summary.amountOut);
353
401
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
354
- 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));
355
- return { ok: true, summary, amountOut, sources };
402
+ const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
403
+ const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
404
+ const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
405
+ return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
356
406
  }
357
- async function revertReason(chainId, sender, quoted, e) {
407
+ async function revertReason(chainId, sender, quoted, e, offchain) {
358
408
  const text = revertString(e);
359
409
  if (text && /return amount is not enough|min return/i.test(text)) {
360
410
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
361
411
  }
362
412
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
363
413
  if (lack) return (0, import_errors2.refusal)("simulation_failed", lack);
414
+ 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.`);
364
415
  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.`);
365
416
  }
366
417
  async function inputShortfall(chainId, sender, quoted) {
@@ -496,6 +547,8 @@ function kyberswapProvider(config = {}) {
496
547
  const minOut = kyberMinimum(r.amountOut, apiBps);
497
548
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
498
549
  const gasEstimate = kyberGasEstimate(r.summary.gas);
550
+ const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
551
+ const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
499
552
  const base = {
500
553
  provider: "kyberswap",
501
554
  intentId: `kyberswap:${chainId}`,
@@ -509,14 +562,15 @@ function kyberswapProvider(config = {}) {
509
562
  ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
510
563
  etaSeconds: 15,
511
564
  reliability: 0.95,
512
- validUntilMs: Date.now() + ttl
565
+ validUntilMs: Date.now() + life
513
566
  };
514
567
  const providerData = {
515
568
  amountOut: r.amountOut.toString(),
516
569
  minOut: minOut.toString(),
517
570
  apiSlippageBps: String(apiBps),
518
571
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
519
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
572
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
573
+ ...offchain ? { offchain } : {}
520
574
  };
521
575
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
522
576
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -540,6 +594,13 @@ function kyberswapProvider(config = {}) {
540
594
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
541
595
  const b = built.data;
542
596
  if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
597
+ let destAmount = r.amountOut;
598
+ if (offchain) {
599
+ const builtOut = uint(b.amountOut);
600
+ if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
601
+ 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");
602
+ if (builtOut < destAmount) destAmount = builtOut;
603
+ }
543
604
  if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
544
605
  const value = uint(b.transactionValue ?? "0");
545
606
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
@@ -573,6 +634,7 @@ function kyberswapProvider(config = {}) {
573
634
  }
574
635
  return {
575
636
  ...base,
637
+ destAmount: destAmount.toString(),
576
638
  minDestAmount: decoded.minReturnAmount.toString(),
577
639
  txRequest: {
578
640
  to: KYBER_ROUTER_V2,
@@ -600,7 +662,7 @@ function kyberswapProvider(config = {}) {
600
662
  try {
601
663
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
602
664
  } catch (e) {
603
- if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
665
+ if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
604
666
  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");
605
667
  }
606
668
  },