@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/protocol.cjs CHANGED
@@ -29,6 +29,7 @@ var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
29
29
  // src/provider.ts
30
30
  var import_viem2 = require("viem");
31
31
  var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
32
+ var import_validate = require("@anywalletkit/protocol-swap2-core/validate");
32
33
  var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
33
34
  var import_swap2_assets2 = require("@anywalletkit/swap2-assets");
34
35
  var import_provider = require("@anywalletkit/protocol-swap2-wrap/provider");
@@ -67,6 +68,34 @@ var KYBER_CHAINS = Object.freeze({
67
68
  5042: { slug: "arc", name: "Arc", build: "lite" },
68
69
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
69
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
+ }
70
99
  function kyberChain(chainId) {
71
100
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
72
101
  }
@@ -156,6 +185,7 @@ function kyberApiSlippage(amountOut, bps) {
156
185
  for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;
157
186
  return null;
158
187
  }
188
+ var KYBER_DEFAULT_SLIPPAGE_BPS = 50;
159
189
  var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
160
190
  function kyberVerifyQuote(params, quote) {
161
191
  if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
@@ -168,8 +198,9 @@ function kyberVerifyQuote(params, quote) {
168
198
  const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
169
199
  if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
170
200
  if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
171
- const bps = params.slippageBps;
172
- 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)) {
173
204
  return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
174
205
  }
175
206
  const tx = quote.txRequest;
@@ -201,6 +232,9 @@ var kyberPins = Object.freeze({
201
232
  callTargets: routerFor,
202
233
  spenders: routerFor,
203
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,
204
238
  verifyQuote: kyberVerifyQuote,
205
239
  reasonOf: (refusal2) => notes.reasonOf(refusal2)
206
240
  });
@@ -217,7 +251,7 @@ function describeKyberActivity(tx, ctx) {
217
251
  var ZERO2 = "0x0000000000000000000000000000000000000000";
218
252
  var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
219
253
  var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
220
- var DEFAULT_SLIPPAGE_BPS = 50;
254
+ var DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;
221
255
  var DEFAULT_TTL_MS = 3e4;
222
256
  var DRY_CACHE_MS = 5e3;
223
257
  var BUILD_DEADLINE_S = 20 * 60;
@@ -238,17 +272,23 @@ var ERROR_REASONS = {
238
272
  4227: "simulation_failed"
239
273
  };
240
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;
241
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;
242
278
  var isAddr2 = (a) => typeof a === "string" && /^0x[0-9a-fA-F]{40}$/.test(a);
243
279
  var same2 = (a, b) => isAddr2(a) && a.toLowerCase() === b.toLowerCase();
244
280
  var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerCase();
245
281
  var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
246
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";
247
284
  var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
248
285
  function kyberGasEstimate(routeGas) {
249
286
  const gas = uint(routeGas);
250
287
  return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
251
288
  }
289
+ function kyberBuildGas(gas) {
290
+ return (0, import_validate.validVenueGas)(gas) ? gas : void 0;
291
+ }
252
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)"]);
253
293
  function revertData(e) {
254
294
  const err = e;
@@ -275,6 +315,14 @@ function revertString(e) {
275
315
  return m ? m[1] : null;
276
316
  }
277
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");
278
326
  const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\/+$/, "");
279
327
  const clientId = config.clientId ?? "anywalletkit";
280
328
  const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
@@ -333,10 +381,17 @@ function kyberswapProvider(config = {}) {
333
381
  if (!body?.data || typeof body.data !== "object") return { ok: false, why: "malformed API response", info: "upstream_unavailable" };
334
382
  return { ok: true, data: body.data };
335
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
+ }
336
392
  async function routes(chainId, tokenIn, tokenOut, amountIn, signal) {
337
393
  const q = new URLSearchParams({ tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: "true" });
338
- if (config.excludeRfqSources ?? true) q.set("excludeRFQSources", "true");
339
- if (config.excludedSources?.length) q.set("excludedSources", config.excludedSources.join(","));
394
+ sourceFilters(q, chainId);
340
395
  const r = await api(`${baseUrl}/${kyberChain(chainId).slug}/api/v1/routes?${q}`, { method: "GET" }, signal);
341
396
  if (!r.ok) return r;
342
397
  const summary = r.data.routeSummary;
@@ -353,16 +408,19 @@ function kyberswapProvider(config = {}) {
353
408
  }
354
409
  const amountOut = uint(summary.amountOut);
355
410
  if (amountOut === null || amountOut <= 0n) return { ok: false, why: "the route pays nothing", info: "no_route" };
356
- 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));
357
- 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") } };
358
415
  }
359
- async function revertReason(chainId, sender, quoted, e) {
416
+ async function revertReason(chainId, sender, quoted, e, offchain) {
360
417
  const text = revertString(e);
361
418
  if (text && /return amount is not enough|min return/i.test(text)) {
362
419
  return (0, import_errors2.refusal)("price_check_failed", "kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.");
363
420
  }
364
421
  const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);
365
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.`);
366
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.`);
367
425
  }
368
426
  async function inputShortfall(chainId, sender, quoted) {
@@ -425,7 +483,8 @@ function kyberswapProvider(config = {}) {
425
483
  name: "kyberswap",
426
484
  describeActivity: describeKyberActivity,
427
485
  supportsSameChain: true,
428
- // 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.
429
488
  ownGasEstimate: true,
430
489
  // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
431
490
  exactAllowanceOnly: kyberExactAllowanceOnly,
@@ -498,6 +557,8 @@ function kyberswapProvider(config = {}) {
498
557
  const minOut = kyberMinimum(r.amountOut, apiBps);
499
558
  if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
500
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] : []);
501
562
  const base = {
502
563
  provider: "kyberswap",
503
564
  intentId: `kyberswap:${chainId}`,
@@ -511,14 +572,15 @@ function kyberswapProvider(config = {}) {
511
572
  ...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
512
573
  etaSeconds: 15,
513
574
  reliability: 0.95,
514
- validUntilMs: Date.now() + ttl
575
+ validUntilMs: Date.now() + life
515
576
  };
516
577
  const providerData = {
517
578
  amountOut: r.amountOut.toString(),
518
579
  minOut: minOut.toString(),
519
580
  apiSlippageBps: String(apiBps),
520
581
  ...typeof r.summary.routeID === "string" ? { routeId: r.summary.routeID.slice(0, 80) } : {},
521
- ...r.sources.length ? { sources: r.sources.join(",") } : {}
582
+ ...r.sources.length ? { sources: r.sources.join(",") } : {},
583
+ ...offchain ? { offchain } : {}
522
584
  };
523
585
  const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);
524
586
  if (lossBps !== null) providerData.priceImpactBps = String(lossBps);
@@ -542,7 +604,16 @@ function kyberswapProvider(config = {}) {
542
604
  if (!built.ok) return refuse(`build: ${built.why}`, built.info);
543
605
  const b = built.data;
544
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
+ }
545
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;
546
617
  const value = uint(b.transactionValue ?? "0");
547
618
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
548
619
  const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
@@ -575,12 +646,15 @@ function kyberswapProvider(config = {}) {
575
646
  }
576
647
  return {
577
648
  ...base,
649
+ ...shownGas !== void 0 ? { gasEstimate: shownGas, gasEstimateSource: "venue" } : {},
650
+ destAmount: destAmount.toString(),
578
651
  minDestAmount: decoded.minReturnAmount.toString(),
579
652
  txRequest: {
580
653
  to: KYBER_ROUTER_V2,
581
654
  data: tx.data,
582
655
  value: value.toString(),
583
656
  chainId,
657
+ ...buildGas !== void 0 ? { venueGas: buildGas } : {},
584
658
  ...tokenIn === ZERO2 ? {} : { approvalAddress: KYBER_ROUTER_V2 }
585
659
  },
586
660
  providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
@@ -602,14 +676,14 @@ function kyberswapProvider(config = {}) {
602
676
  try {
603
677
  await rpc(chainId, "eth_call", [{ from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? "0").toString(16)}` }, "latest"]);
604
678
  } catch (e) {
605
- 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);
606
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");
607
681
  }
608
682
  },
609
683
  async buildDeposit(quote) {
610
684
  const tx = quote.txRequest;
611
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)");
612
- 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 } : {} };
613
687
  },
614
688
  async trackIntent(ref) {
615
689
  if (!ref.sourceTxHash) return { state: "pending" };