@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.
package/dist/provider.cjs CHANGED
@@ -20,6 +20,9 @@ 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,
25
+ kyberGasEstimate: () => kyberGasEstimate,
23
26
  kyberValueLossBps: () => kyberValueLossBps,
24
27
  kyberswapProvider: () => kyberswapProvider
25
28
  });
@@ -64,6 +67,34 @@ var KYBER_CHAINS = Object.freeze({
64
67
  5042: { slug: "arc", name: "Arc", build: "lite" },
65
68
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
66
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
+ }
67
98
  function kyberChain(chainId) {
68
99
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
69
100
  }
@@ -191,9 +222,13 @@ function kyberVerifyQuote(params, quote) {
191
222
  function routerFor(chain) {
192
223
  return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
193
224
  }
225
+ function kyberExactAllowanceOnly(chain) {
226
+ return kyberChain(chainIdOf(chain))?.build !== "lite";
227
+ }
194
228
  var kyberPins = Object.freeze({
195
229
  callTargets: routerFor,
196
230
  spenders: routerFor,
231
+ exactAllowanceOnly: kyberExactAllowanceOnly,
197
232
  verifyQuote: kyberVerifyQuote,
198
233
  reasonOf: (refusal2) => notes.reasonOf(refusal2)
199
234
  });
@@ -231,13 +266,20 @@ var ERROR_REASONS = {
231
266
  4227: "simulation_failed"
232
267
  };
233
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;
234
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;
235
272
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
236
273
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
237
274
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
238
275
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
239
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";
240
278
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
279
+ function kyberGasEstimate(routeGas) {
280
+ const gas = uint(routeGas);
281
+ return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
282
+ }
241
283
  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)"]);
242
284
  function revertData(e) {
243
285
  const err = e;
@@ -264,6 +306,14 @@ function revertString(e) {
264
306
  return m ? m[1] : null;
265
307
  }
266
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");
267
317
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
268
318
  const clientId = config.clientId ?? "anywalletkit";
269
319
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -322,10 +372,17 @@ function kyberswapProvider(config = {}) {
322
372
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
323
373
  return { ok: true, data: body.data };
324
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
+ }
325
383
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
326
384
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
327
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
328
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
385
+ sourceFilters(q, chainId);
329
386
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
330
387
  if (!r.ok) return r;
331
388
  const summary = r.data.routeSummary;
@@ -342,16 +399,19 @@ function kyberswapProvider(config = {}) {
342
399
  }
343
400
  const amountOut = uint(summary.amountOut);
344
401
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
345
- 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));
346
- 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") } };
347
406
  }
348
- async function revertReason(chainId, sender, quoted, e) {
407
+ async function revertReason(chainId, sender, quoted, e, offchain) {
349
408
  const text = revertString(e);
350
409
  if (text && /return amount is not enough|min return/i.test(text)) {
351
410
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
352
411
  }
353
412
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
354
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.`);
355
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.`);
356
416
  }
357
417
  async function inputShortfall(chainId, sender, quoted) {
@@ -416,6 +476,8 @@ function kyberswapProvider(config = {}) {
416
476
  supportsSameChain: true,
417
477
  // The account's own estimate of the exact call, never the API's gas model.
418
478
  ownGasEstimate: true,
479
+ // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
480
+ exactAllowanceOnly: kyberExactAllowanceOnly,
419
481
  enabled: () => config.enabled ?? true,
420
482
  supportsChain: (caip2) => chainIdOf2(caip2) !== null,
421
483
  supportsChainPair: (from, to) => from === to && chainIdOf2(from) !== null,
@@ -484,6 +546,9 @@ function kyberswapProvider(config = {}) {
484
546
  if (apiBps === null) return refuse("the output is too small to carry a minimum", "amount_too_small");
485
547
  const minOut = kyberMinimum(r.amountOut, apiBps);
486
548
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
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] : []);
487
552
  const base = {
488
553
  provider: "kyberswap",
489
554
  intentId: `kyberswap:${chainId}`,
@@ -494,16 +559,18 @@ function kyberswapProvider(config = {}) {
494
559
  destAmount: r.amountOut.toString(),
495
560
  minDestAmount: minOut.toString(),
496
561
  feeUsd: 0,
562
+ ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
497
563
  etaSeconds: 15,
498
564
  reliability: 0.95,
499
- validUntilMs: Date.now() + ttl
565
+ validUntilMs: Date.now() + life
500
566
  };
501
567
  const providerData = {
502
568
  amountOut: r.amountOut.toString(),
503
569
  minOut: minOut.toString(),
504
570
  apiSlippageBps: String(apiBps),
505
571
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
506
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
572
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
573
+ ...offchain ? { offchain } : {}
507
574
  };
508
575
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
509
576
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -527,6 +594,13 @@ function kyberswapProvider(config = {}) {
527
594
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
528
595
  const b = built.data;
529
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
+ }
530
604
  if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
531
605
  const value = uint(b.transactionValue ?? "0");
532
606
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
@@ -560,6 +634,7 @@ function kyberswapProvider(config = {}) {
560
634
  }
561
635
  return {
562
636
  ...base,
637
+ destAmount: destAmount.toString(),
563
638
  minDestAmount: decoded.minReturnAmount.toString(),
564
639
  txRequest: {
565
640
  to: KYBER_ROUTER_V2,
@@ -587,7 +662,7 @@ function kyberswapProvider(config = {}) {
587
662
  try {
588
663
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
589
664
  } catch (e) {
590
- 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);
591
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");
592
667
  }
593
668
  },