@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/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
@@ -27,6 +29,7 @@ __export(provider_exports, {
27
29
  module.exports = __toCommonJS(provider_exports);
28
30
  var import_viem2 = require("viem");
29
31
  var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
32
+ var import_validate = require("@anywalletkit/protocol-swap2-core/validate");
30
33
  var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
31
34
  var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
32
35
  var import_provider = require("@anywalletkit/protocol-swap2-wrap/provider");
@@ -65,6 +68,34 @@ var KYBER_CHAINS = Object.freeze({
65
68
  5042: { slug: "arc", name: "Arc", build: "lite" },
66
69
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
67
70
  });
71
+ var KYBER_LIMIT_ORDER_SOURCES = Object.freeze(["kyberswap-limit-order-v2"]);
72
+ var KYBER_RFQ_SOURCES = Object.freeze({
73
+ 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"],
74
+ 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"],
75
+ 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"],
76
+ 42161: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-13", "pmm-2", "pmm-21", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
77
+ 10: ["bebop", "pmm-13", "swaap-v2"],
78
+ 137: ["bebop", "native-v1", "pmm-5", "pmm-8", "swaap-v2"],
79
+ 43114: ["bebop", "dexalot", "hashflow-v3", "native-v1", "pmm-4", "swaap-v2"],
80
+ 59144: ["native-v1", "swaap-v2"],
81
+ 146: ["swaap-v2"],
82
+ 80094: ["bebop"],
83
+ 130: [],
84
+ 999: ["bebop"],
85
+ 9745: [],
86
+ 143: ["native-v2", "swaap-v2"],
87
+ 4326: [],
88
+ 4663: ["bebop", "native-v2", "pmm-18", "pmm-19", "pmm-20", "swaap-v2"],
89
+ 5042: ["pmm-13"],
90
+ 99901: []
91
+ });
92
+ 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-]*)$/;
93
+ function kyberSourceKind(chainId, exchange, poolType) {
94
+ const id = typeof exchange === "string" ? exchange.split("/")[0] : "";
95
+ if (poolType === "limit-order" || /^kyberswap-limit-order(?:-v\d+)?$/.test(id)) return "limit-order";
96
+ const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : [];
97
+ return poolType === "orderbook" || listed.includes(id) || RFQ_LIKE.test(id) ? "rfq" : "pool";
98
+ }
68
99
  function kyberChain(chainId) {
69
100
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
70
101
  }
@@ -154,6 +185,7 @@ function kyberApiSlippage(amountOut, bps) {
154
185
  for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;
155
186
  return null;
156
187
  }
188
+ var KYBER_DEFAULT_SLIPPAGE_BPS = 50;
157
189
  var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
158
190
  function kyberVerifyQuote(params, quote) {
159
191
  if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
@@ -166,8 +198,9 @@ function kyberVerifyQuote(params, quote) {
166
198
  const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
167
199
  if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
168
200
  if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
169
- const bps = params.slippageBps;
170
- if (bps !== void 0 && Number.isInteger(bps) && bps >= 0 && bps < 1e4 && min < kyberMinimum(out, bps)) {
201
+ const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;
202
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return notes.note("invalid slippage", "policy_refused");
203
+ if (min < kyberMinimum(out, bps)) {
171
204
  return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
172
205
  }
173
206
  const tx = quote.txRequest;
@@ -199,6 +232,9 @@ var kyberPins = Object.freeze({
199
232
  callTargets: routerFor,
200
233
  spenders: routerFor,
201
234
  exactAllowanceOnly: kyberExactAllowanceOnly,
235
+ // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate
236
+ // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.
237
+ ownGasEstimate: true,
202
238
  verifyQuote: kyberVerifyQuote,
203
239
  reasonOf: (refusal2) => notes.reasonOf(refusal2)
204
240
  });
@@ -215,7 +251,7 @@ function describeKyberActivity(tx, ctx) {
215
251
  var ZERO2 = "0x0000000000000000000000000000000000000000";
216
252
  var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
217
253
  var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
218
- var DEFAULT_SLIPPAGE_BPS = 50;
254
+ var DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;
219
255
  var DEFAULT_TTL_MS = 3e4;
220
256
  var DRY_CACHE_MS = 5e3;
221
257
  var BUILD_DEADLINE_S = 20 * 60;
@@ -236,17 +272,23 @@ var ERROR_REASONS = {
236
272
  4227: "simulation_failed"
237
273
  };
238
274
  var errorReason = (code) => typeof code === "number" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : void 0;
275
+ var KYBER_RFQ_TTL_MS = 1e4;
276
+ var KYBER_LIMIT_ORDER_TTL_MS = 3e4;
239
277
  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
278
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
241
279
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
242
280
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
243
281
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
244
282
  var apiToken = (t) => t === ZERO2 ? KYBER_NATIVE : t;
283
+ 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
284
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
246
285
  function kyberGasEstimate(routeGas) {
247
286
  const gas = uint(routeGas);
248
287
  return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
249
288
  }
289
+ function kyberBuildGas(gas) {
290
+ return (0, import_validate.validVenueGas)(gas) ? gas : void 0;
291
+ }
250
292
  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)"]);
251
293
  function revertData(e) {
252
294
  const err = e;
@@ -273,6 +315,14 @@ function revertString(e) {
273
315
  return m ? m[1] : null;
274
316
  }
275
317
  function kyberswapProvider(config = {}) {
318
+ const legacy = config.excludeRfqSources === false ? "include" : "exclude";
319
+ const setting = (v, name) => {
320
+ if (v === void 0) return legacy;
321
+ if (v !== "exclude" && v !== "include") throw new TypeError(`kyberswap: ${name} must be "exclude" or "include"`);
322
+ return v;
323
+ };
324
+ const rfqSetting = setting(config.rfq, "rfq");
325
+ const limitOrderSetting = setting(config.limitOrders, "limitOrders");
276
326
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
277
327
  const clientId = config.clientId ?? "anywalletkit";
278
328
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -331,10 +381,17 @@ function kyberswapProvider(config = {}) {
331
381
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
332
382
  return { ok: true, data: body.data };
333
383
  }
384
+ function sourceFilters(q, chainId) {
385
+ const excluded = [];
386
+ if (rfqSetting === "exclude" && limitOrderSetting === "exclude") q.set("excludeRFQSources", "true");
387
+ else if (rfqSetting === "exclude") excluded.push(...Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : []);
388
+ else if (limitOrderSetting === "exclude") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);
389
+ for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);
390
+ if (excluded.length) q.set("excludedSources", excluded.join(","));
391
+ }
334
392
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
335
393
  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(","));
394
+ sourceFilters(q, chainId);
338
395
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
339
396
  if (!r.ok) return r;
340
397
  const summary = r.data.routeSummary;
@@ -351,16 +408,19 @@ function kyberswapProvider(config = {}) {
351
408
  }
352
409
  const amountOut = uint(summary.amountOut);
353
410
  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 };
411
+ const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === "object") : [];
412
+ const sources = [...new Set(hops.map((h) => h.exchange).filter((x) => typeof x === "string"))].slice(0, 6).map((s) => s.slice(0, 40));
413
+ const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));
414
+ return { ok: true, summary, amountOut, sources, offchain: { rfq: kinds.has("rfq"), limitOrder: kinds.has("limit-order") } };
356
415
  }
357
- async function revertReason(chainId, sender, quoted, e) {
416
+ async function revertReason(chainId, sender, quoted, e, offchain) {
358
417
  const text = revertString(e);
359
418
  if (text && /return amount is not enough|min return/i.test(text)) {
360
419
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
361
420
  }
362
421
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
363
422
  if (lack) return (0, import_errors2.refusal)("simulation_failed", lack);
423
+ 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
424
  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
425
  }
366
426
  async function inputShortfall(chainId, sender, quoted) {
@@ -423,7 +483,8 @@ function kyberswapProvider(config = {}) {
423
483
  name: "kyberswap",
424
484
  describeActivity: describeKyberActivity,
425
485
  supportsSameChain: true,
426
- // The account's own estimate of the exact call, never the API's gas model.
486
+ // The account's own estimate of the exact call, dry-run before broadcast: the limit is built on it (× 1.3 + 100 000),
487
+ // with the build's gas as a floor (`venueGas`), never the API's figure alone.
427
488
  ownGasEstimate: true,
428
489
  // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
429
490
  exactAllowanceOnly: kyberExactAllowanceOnly,
@@ -496,6 +557,8 @@ function kyberswapProvider(config = {}) {
496
557
  const minOut = kyberMinimum(r.amountOut, apiBps);
497
558
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
498
559
  const gasEstimate = kyberGasEstimate(r.summary.gas);
560
+ const offchain = [...r.offchain.rfq ? ["rfq"] : [], ...r.offchain.limitOrder ? ["limit-order"] : []].join(",");
561
+ const life = Math.min(ttl, ...r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : [], ...r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []);
499
562
  const base = {
500
563
  provider: "kyberswap",
501
564
  intentId: `kyberswap:${chainId}`,
@@ -509,14 +572,15 @@ function kyberswapProvider(config = {}) {
509
572
  ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
510
573
  etaSeconds: 15,
511
574
  reliability: 0.95,
512
- validUntilMs: Date.now() + ttl
575
+ validUntilMs: Date.now() + life
513
576
  };
514
577
  const providerData = {
515
578
  amountOut: r.amountOut.toString(),
516
579
  minOut: minOut.toString(),
517
580
  apiSlippageBps: String(apiBps),
518
581
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
519
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
582
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
583
+ ...offchain ? { offchain } : {}
520
584
  };
521
585
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
522
586
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -540,7 +604,16 @@ function kyberswapProvider(config = {}) {
540
604
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
541
605
  const b = built.data;
542
606
  if (uint(b.amountIn) !== amountIn) return refuse("the build spends another amount", "price_check_failed");
607
+ let destAmount = r.amountOut;
608
+ if (offchain) {
609
+ const builtOut = uint(b.amountOut);
610
+ if (builtOut === null) return refuse("malformed build response", "upstream_unavailable");
611
+ 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");
612
+ if (builtOut < destAmount) destAmount = builtOut;
613
+ }
543
614
  if (same2(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
615
+ const buildGas = kyberBuildGas(b.gas);
616
+ const shownGas = base.gasEstimate === void 0 && buildGas !== void 0 ? kyberGasEstimate(buildGas) : void 0;
544
617
  const value = uint(b.transactionValue ?? "0");
545
618
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
546
619
  const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
@@ -573,12 +646,15 @@ function kyberswapProvider(config = {}) {
573
646
  }
574
647
  return {
575
648
  ...base,
649
+ ...shownGas !== void 0 ? { gasEstimate: shownGas, gasEstimateSource: "venue" } : {},
650
+ destAmount: destAmount.toString(),
576
651
  minDestAmount: decoded.minReturnAmount.toString(),
577
652
  txRequest: {
578
653
  to: KYBER_ROUTER_V2,
579
654
  data: tx.data,
580
655
  value: value.toString(),
581
656
  chainId,
657
+ ...buildGas !== void 0 ? { venueGas: buildGas } : {},
582
658
  ...tokenIn === ZERO2 ? {} : { approvalAddress: KYBER_ROUTER_V2 }
583
659
  },
584
660
  providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
@@ -600,14 +676,14 @@ function kyberswapProvider(config = {}) {
600
676
  try {
601
677
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
602
678
  } catch (e) {
603
- if (e.rpc) throw await revertReason(chainId, sender, quoted, e);
679
+ if (e.rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === "string" ? quote.providerData.offchain : void 0);
604
680
  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
681
  }
606
682
  },
607
683
  async buildDeposit(quote) {
608
684
  const tx = quote.txRequest;
609
685
  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)");
610
- return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
686
+ 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 } : {} };
611
687
  },
612
688
  async trackIntent(ref) {
613
689
  if (!ref.sourceTxHash) return { state: "pending" };