@anywalletkit/protocol-swap2-kyberswap 0.3.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/README.md CHANGED
@@ -62,8 +62,9 @@ returns is checked on the device against the pinned router and the app's own req
62
62
  allowance is already there — so a route that reverts never asks for an approval. A wallet without the input, or an
63
63
  RPC without `eth_simulateV1` (Monad, Avalanche, HyperEVM on 2026-11-25), skips that early check
64
64
  (`providerData.simulated: "none"`). Every swap is simulated again from the account at the latest block right before
65
- signing (`preflightDeposit`). A revert, or no RPC answering, refuses the swap — nothing is sent unsimulated. Gas is
66
- the account's own estimate of the exact call (`ownGasEstimate`).
65
+ signing (`preflightDeposit`). A revert, or no RPC answering, refuses the swap — nothing is sent unsimulated. The
66
+ gas limit is built on the account's own estimate of the exact call (`ownGasEstimate`): `max(estimate, build gas) ×
67
+ 1.3 + 100 000`, see "Gas" below.
67
68
  - Token inputs approve exactly the amount to the router (the engine default), spent in the same transaction.
68
69
  - KyberSwap's own USD values of the input and the output (`amountInUsd` / `amountOutUsd`) reach the router's
69
70
  `quoteValues` as `providerData.priceImpactBps` — the value lost to pool impact and pool fees — so a near-total loss
@@ -190,9 +191,35 @@ the execution quote, asking without RFQ, may not reach.
190
191
  Every quote, dry or for execution, carries `gasEstimate` = KyberSwap's `routeSummary.gas` from `GET /routes` (asked
191
192
  with `gasInclude=true`), `gasEstimateSource: "venue"`. It is there to compare routes (see protocol-swap2-core, "Gas:
192
193
  `gasEstimate` vs `gasLimit`"): a dry quote has no transaction, so before this the router could only assume a gas limit
193
- for it. Nothing in execution reads it: the swap still goes out with the account's own estimate of the exact call
194
- (`ownGasEstimate`), and the transaction carries no gas limit. It counts the swap call only, no approval. A route that
195
- states no gas (or 0) gives a quote without one.
194
+ for it. It counts the swap call only, no approval. A route that states no gas (or 0) gives a dry quote without one;
195
+ an execution quote then takes the build's `gas` instead, when that is a valid figure.
196
+
197
+ ## Gas: the limit the swap is sent with
198
+
199
+ The execution quote carries the build's `gas` as `txRequest.venueGas` (a decimal string from 21 000 to
200
+ 10 000 000; anything else is left out, never refused), and the transaction carries no `gasLimit`. Right before the
201
+ broadcast the engine dry-runs the exact call from the account (`ownGasEstimate`) and sends it with
202
+ `max(the account's estimate, venueGas) × 1.3 + 100 000`, at most 10 000 000 (30 000 000 on Monad; above it the swap is refused,
203
+ `policy_refused`); the native-gas check prices that limit. KyberSwap's figure is a floor, never a ceiling: it can
204
+ raise the limit, never lower it below the account's estimate. An account that does not report its estimate
205
+ (`quoteSendTransaction` without `gas`) sends with its own estimate, as before. A remote stub with `kyberPins` declares
206
+ `ownGasEstimate` too, and a swap2 server carries `venueGas` in the sealed quote.
207
+
208
+ Why (2026-12-04, Ethereum, 19 WETH → USDC through MetaAggregationRouterV2, three execution quotes in a row): the
209
+ routes went through many oracle-priced PMM pools, whose gas moves between the estimate and inclusion, and the router's
210
+ catch turns an out-of-gas inside the executor into a plain "Call failed".
211
+
212
+ | Transaction | Sent with (the wallet's estimate × 1.2) | Gas used | Result | The new rule from that estimate alone |
213
+ |---|---|---|---|---|
214
+ | 0x4da3fd71… | 1 187 136 (989 280) | 1 152 501 | out of gas | 1 386 064 |
215
+ | 0x05151ebb… | 2 882 809 (2 402 341) | 2 762 524 | out of gas | 3 223 044 |
216
+ | 0x6fc9f8ac… | 4 316 655 (3 597 212) | 2 864 620 | success | 4 776 376 |
217
+
218
+ For the first one the build's `gas` decides: the new limit reaches the 2 864 620 the successful route used when that
219
+ figure is at least 2 126 631. A fresh build of the same swap (19 WETH → USDC, 2026-12-04, a public WETH holder as
220
+ sender) stated 1 949 706 (RFQ excluded, as the module asks; limit 2 634 618) and 2 241 582 (all sources; limit
221
+ 3 014 057). The first route's own figure is not recoverable and its calldata was about half the size of the
222
+ successful one (7.5 kB against 15.8 kB), so what it needed is not known.
196
223
 
197
224
  What KyberSwap's figure is: its own model of the route's gas, not a simulation. The build answers the same number
198
225
  (`gas` of `POST /route/build` equalled `routeSummary.gas` in all 16 recordings), and routine routes land on round model
package/dist/activity.cjs CHANGED
@@ -162,6 +162,7 @@ function kyberMinimum(amountOut, bps) {
162
162
  const m = amountOut * BigInt(1e4 - bps) / 10000n - 1n;
163
163
  return m > 0n ? m : 0n;
164
164
  }
165
+ var KYBER_DEFAULT_SLIPPAGE_BPS = 50;
165
166
  var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
166
167
  function kyberVerifyQuote(params, quote) {
167
168
  if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
@@ -174,8 +175,9 @@ function kyberVerifyQuote(params, quote) {
174
175
  const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
175
176
  if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
176
177
  if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
177
- const bps = params.slippageBps;
178
- if (bps !== void 0 && Number.isInteger(bps) && bps >= 0 && bps < 1e4 && min < kyberMinimum(out, bps)) {
178
+ const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;
179
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return notes.note("invalid slippage", "policy_refused");
180
+ if (min < kyberMinimum(out, bps)) {
179
181
  return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
180
182
  }
181
183
  const tx = quote.txRequest;
@@ -207,6 +209,9 @@ var kyberPins = Object.freeze({
207
209
  callTargets: routerFor,
208
210
  spenders: routerFor,
209
211
  exactAllowanceOnly: kyberExactAllowanceOnly,
212
+ // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate
213
+ // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.
214
+ ownGasEstimate: true,
210
215
  verifyQuote: kyberVerifyQuote,
211
216
  reasonOf: (refusal) => notes.reasonOf(refusal)
212
217
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/activity.ts","../src/router.ts"],"sourcesContent":["/**\n * Activity recognition for KyberSwap: a `swap()` call to MetaAggregationRouterV2 on a chain the module serves →\n * `swap`, \"Swapped A → B\" from the owner's net transfers.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {KYBER_ROUTER_V2, KYBER_SWAP_SELECTOR, kyberChain} from \"./router.js\";\n\nexport const KYBERSWAP_MODULE = \"@anywalletkit/protocol-swap2-kyberswap\";\n\nexport function describeKyberActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain) || !kyberChain(evmRef(tx.chain))) return null;\n if (!matchesCall(tx, [KYBER_ROUTER_V2], [KYBER_SWAP_SELECTOR])) return null;\n return describeSwapLike(tx, ctx, {protocol: KYBERSWAP_MODULE, subtitle: `KyberSwap · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** KyberSwap's own limit orders: makers' signed orders kept off-chain, filled on-chain by the executor (the active source id). */\nexport const KYBER_LIMIT_ORDER_SOURCES: readonly string[] = Object.freeze([\"kyberswap-limit-order-v2\"]);\n\n/**\n * KyberSwap's RFQ sources per chain — private market makers whose firm quote is signed when the route is built: the\n * sources tagged \"RFQ sources\" in KyberSwap's own source list (`ks-setting.kyberswap.com/api/v1/dexes`, read\n * 2026-11-30). `excludeRFQSources=true` leaves out these and the limit orders together; this list is how the provider\n * asks for limit orders without RFQ (`limitOrders: \"include\"`, `rfq: \"exclude\"`). An empty list: the chain had no RFQ\n * source. A source KyberSwap adds later is still recognised in a route by `kyberSourceKind` (its `poolType`, or an\n * RFQ-like id), so the quote is marked and timed as RFQ; only the request would not leave it out.\n */\nexport const KYBER_RFQ_SOURCES: Readonly<Record<number, readonly string[]>> = Object.freeze({\n 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\"],\n 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\"],\n 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\"],\n 42161: [\"bebop\", \"hashflow-v3\", \"native-v1\", \"native-v2\", \"pmm-13\", \"pmm-2\", \"pmm-21\", \"pmm-5\", \"pmm-6\", \"pmm-7\", \"pmm-8\", \"swaap-v2\"],\n 10: [\"bebop\", \"pmm-13\", \"swaap-v2\"],\n 137: [\"bebop\", \"native-v1\", \"pmm-5\", \"pmm-8\", \"swaap-v2\"],\n 43114: [\"bebop\", \"dexalot\", \"hashflow-v3\", \"native-v1\", \"pmm-4\", \"swaap-v2\"],\n 59144: [\"native-v1\", \"swaap-v2\"],\n 146: [\"swaap-v2\"],\n 80094: [\"bebop\"],\n 130: [],\n 999: [\"bebop\"],\n 9745: [],\n 143: [\"native-v2\", \"swaap-v2\"],\n 4326: [],\n 4663: [\"bebop\", \"native-v2\", \"pmm-18\", \"pmm-19\", \"pmm-20\", \"swaap-v2\"],\n 5042: [\"pmm-13\"],\n 99901: [],\n});\n\n/** Source ids that look like RFQ wherever KyberSwap lists them (a source added after the list above was read). */\nconst 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-]*)$/;\n\n/**\n * What a route hop's liquidity is: an RFQ market maker, a KyberSwap limit order, or anything else (a pool, a\n * proprietary AMM). Read from the hop as `GET /routes` returns it: `poolType` (\"orderbook\" for an RFQ maker,\n * \"limit-order\" for a limit order) or the source id — the part before \"/\" when KyberSwap names a fallback after it\n * (\"pmm-19/uniswapv3\": the maker, and the pool the route falls back to when the maker does not sign).\n */\nexport function kyberSourceKind(chainId: number, exchange: unknown, poolType?: unknown): \"rfq\" | \"limit-order\" | \"pool\" {\n const id = typeof exchange === \"string\" ? exchange.split(\"/\")[0]! : \"\";\n if (poolType === \"limit-order\" || /^kyberswap-limit-order(?:-v\\d+)?$/.test(id)) return \"limit-order\";\n const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : [];\n return poolType === \"orderbook\" || listed.includes(id) || RFQ_LIKE.test(id) ? \"rfq\" : \"pool\";\n}\n\n/** The chain entry for an id, never an inherited property. */\nexport function kyberChain(chainId: number): (typeof KYBER_CHAINS)[number] | undefined {\n return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : undefined;\n}\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one. Arc's gas token is\n * USDC with 18-decimal native accounting, listed only through its 6-decimal ERC-20 interface, so a native leg there\n * would carry amounts 10^12 off the catalog's USDC; it is refused and the ERC-20 swaps instead.\n */\nexport function kyberNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** `swap(SwapExecutionParams)` — the one router entry point this module accepts. */\nexport const KYBER_ROUTER_ABI = parseAbi([\n \"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }\",\n \"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }\",\n \"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)\",\n]);\nexport const KYBER_SWAP_SELECTOR = \"0xe21fd0e9\";\n/** Router entry points that are refused by name: `swapGeneric` (owner-whitelisted arbitrary call) and `swapSimpleMode` (no minimum check). */\nexport const KYBER_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x59e50fed\": \"swapGeneric\",\n \"0x8af033fb\": \"swapSimpleMode\",\n});\n/**\n * The only flag bit accepted: `0x200`, set on every swap the build endpoint encodes (not one of the V2 source's named\n * flags; its meaning is not documented). Partial fill (0x01), extra value (0x02), claim (0x04), burns (0x08/0x10),\n * simple mode (0x20), fee on output (0x40), fee in bps (0x80) and approve-fund (0x100) are refused, as is any other bit.\n */\nexport const KYBER_FLAGS_ALLOWED = 0x200n;\n\nexport class KyberTransactionError extends Error {\n constructor(message: string) {\n super(`kyberswap: ${message}`);\n this.name = \"KyberTransactionError\";\n }\n}\nconst fail = (message: string, reason: Swap2RefusalReason): KyberTransactionError => withReason(new KyberTransactionError(message), reason);\nconst notes = refusalNotes();\n\nexport interface ExpectedKyberSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n /** Who must receive the output (the request's recipient). */\n receiver: string;\n /** The least `minReturnAmount` the calldata may name: the quote's minimum (and the caller's floor). */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nexport interface DecodedKyberSwap {\n srcToken: string;\n dstToken: string;\n dstReceiver: string;\n amount: bigint;\n minReturnAmount: bigint;\n flags: bigint;\n}\n\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: string, b: string): boolean => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();\nconst routerToken = (t: string): string => (same(t, ZERO) ? KYBER_NATIVE : t);\n/** The calldata may be a megabyte from an untrusted source: names in refusals are addresses only. */\nconst named = (a: unknown): string => (isAddr(a) ? a : \"something that is not an address\");\n/** At most this much calldata is decoded (a routed swap is a few KB). */\nconst MAX_CALLDATA_BYTES = 64 * 1024;\n\n/** Refuses (throws {@link KyberTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkKyberTransaction(tx: EncodedTx, expected: ExpectedKyberSwap): DecodedKyberSwap {\n const chain = kyberChain(expected.chainId);\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, \"unsupported_pair\");\n if (same(tx.to, KYBER_ROUTER_V3)) throw fail(\"Kyber router V3 not supported yet\", \"policy_refused\");\n if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, \"vault_mismatch\");\n if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {\n throw fail(\"invalid receiver\", \"recipient_mismatch\");\n }\n const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);\n if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n if (same(expected.tokenIn, expected.tokenOut)) throw fail(\"same token in and out\", \"unsupported_pair\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail(\"invalid quote amounts\", \"price_check_failed\");\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail(\"calldata is larger than any routed swap\", \"policy_refused\");\n const selector = tx.data.slice(0, 10).toLowerCase();\n const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : undefined;\n if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, \"policy_refused\");\n if (selector !== KYBER_SWAP_SELECTOR) throw fail(\"not a router swap() call\", \"policy_refused\");\n\n let x: {callTarget: string; approveTarget: string; targetData: Hex; desc: {srcToken: string; dstToken: string; srcReceivers: readonly string[]; srcAmounts: readonly bigint[]; feeReceivers: readonly string[]; feeAmounts: readonly bigint[]; dstReceiver: string; amount: bigint; minReturnAmount: bigint; flags: bigint; permit: Hex}; clientData: Hex};\n try {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: tx.data as Hex});\n x = call.args[0] as typeof x;\n // Strict: the calldata must be exactly the canonical encoding of what was decoded (no trailing bytes, no odd offsets or padding).\n const again = encodeFunctionData({abi: KYBER_ROUTER_ABI, functionName: \"swap\", args: [x as never]});\n if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error(\"non-canonical\");\n } catch {\n throw fail(\"the calldata is not a canonical router swap() encoding\", \"policy_refused\");\n }\n const d = x.desc;\n if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, \"vault_mismatch\");\n if (!same(x.approveTarget, ZERO)) throw fail(\"the swap asks the router to approve another contract\", \"policy_refused\");\n if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, \"price_check_failed\");\n if (d.srcReceivers.length !== d.srcAmounts.length) throw fail(\"malformed input split\", \"policy_refused\");\n if (nativeIn) {\n if (d.srcReceivers.length !== 0) throw fail(\"a native-coin swap must not split the input\", \"policy_refused\");\n if (tx.value !== expected.amountIn) throw fail(\"native value does not match the input\", \"price_check_failed\");\n } else {\n if (tx.value !== 0n) throw fail(\"a token swap must not send the native coin\", \"price_check_failed\");\n const total = d.srcAmounts.reduce((s, a) => s + a, 0n);\n if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, \"price_check_failed\");\n }\n if (same(d.dstReceiver, ZERO)) throw fail(\"the swap names no receiver\", \"recipient_mismatch\");\n if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (d.minReturnAmount <= 0n) throw fail(\"the swap names no minimum\", \"price_check_failed\");\n if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, \"price_check_failed\");\n if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail(\"calldata pays a fee receiver — this module charges none\", \"policy_refused\");\n if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, \"policy_refused\");\n if (d.permit !== \"0x\") throw fail(\"calldata carries a permit\", \"policy_refused\");\n return {srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags};\n}\n\n/**\n * The minimum KyberSwap's build encodes for `amountOut` at `bps` slippage: the expected output less the slippage,\n * rounded down, less one more unit — the build endpoint always lands exactly one base unit under the plain\n * `floor(amountOut × (10000 − bps) / 10000)` (18 chains, 2026-11-24). The quote shows this value, so the dry quote,\n * the build and the check agree to the unit.\n */\nexport function kyberMinimum(amountOut: bigint, bps: number): bigint {\n const m = (amountOut * BigInt(10_000 - bps)) / 10_000n - 1n;\n return m > 0n ? m : 0n;\n}\n\n/**\n * The slippage to ask KyberSwap for so that its minimum — one unit under the plain floor ({@link kyberMinimum}) — still\n * meets the engine's floor for the slippage the user chose, `floor(amountOut × (10000 − bps) / 10000)`. One basis point\n * less for most outputs; more for a tiny output (a $1 WBTC buy is a few thousand units, where 1 bps is under one unit).\n * Null when no positive slippage does (an output too small to carry a minimum).\n */\nexport function kyberApiSlippage(amountOut: bigint, bps: number): number | null {\n const floor = (amountOut * BigInt(10_000 - bps)) / 10_000n;\n for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;\n return null;\n}\n\nconst chainIdOf = (caip2: string): number => (/^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN);\n\n/**\n * The app's own check of a KyberSwap quote (behind `remoteProvider`, or on any quote): one chain, the exact input,\n * a minimum at or under the expected output and at or above the caller's floor; an execution quote's transaction must\n * pass {@link checkKyberTransaction} against this app's request. A dry quote carries no transaction. The reason it fails, or null.\n */\nexport function kyberVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = chainIdOf(params.sourceChain);\n if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, \"unsupported_pair\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n if (quote.sourceAmount !== params.amountIn) return notes.note(\"the quote prices another amount\", \"price_check_failed\");\n const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);\n if (min <= 0n || min > out) return notes.note(\"invalid quote amounts\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && min < BigInt(params.minAmountOut)) return notes.note(\"the quote's minimum is under the floor\", \"price_check_failed\");\n // The minimum is the expected output less the requested slippage, never more slippage than asked for.\n const bps = params.slippageBps;\n if (bps !== undefined && Number.isInteger(bps) && bps >= 0 && bps < 10_000 && min < kyberMinimum(out, bps)) {\n return notes.note(\"the quote's minimum allows more slippage than requested\", \"price_check_failed\");\n }\n const tx = quote.txRequest;\n if (!tx) return params.dry === false ? notes.note(\"the quote carries no router transaction\", \"policy_refused\") : null;\n if (!tx.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n if (tx.approvalAddress !== undefined && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note(\"the quote asks to approve another spender\", \"vault_mismatch\");\n checkKyberTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n minAmountOut: min,\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e);\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\nfunction routerFor(chain: string): readonly string[] {\n return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];\n}\n\n/**\n * The provider's `exactAllowanceOnly` (protocol-swap2-core): true on the chains whose router is the `generic` build —\n * `swapGeneric` behind an owner-managed executor whitelist, so the router's owner (a single key on all but Linea) could\n * make it spend an allowance left on it. The engine then approves exactly the input and revokes it when the swap does\n * not spend it, whatever the app's `allowanceReuse` / `revokeUnspentApproval` say. False on the `lite` chains; true\n * for a chain this module does not know (fail closed).\n */\nexport function kyberExactAllowanceOnly(chain: string): boolean {\n return kyberChain(chainIdOf(chain))?.build !== \"lite\";\n}\n\n/**\n * The router a KyberSwap swap calls and approves, and {@link kyberVerifyQuote}: the app's side of\n * `remoteProvider({name: \"kyberswap\", baseUrl, ...kyberPins})`, so a backend's quote is checked against the pinned\n * router and the app's own request, never against itself.\n */\nexport const kyberPins: RemotePins = Object.freeze({\n callTargets: routerFor,\n spenders: routerFor,\n exactAllowanceOnly: kyberExactAllowanceOnly,\n verifyQuote: kyberVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,sBAAwD;AACxD,IAAAA,eAA4B;;;ACM5B,kBAA4B;AAC5B,oBAA2E;AAC3E,0BAA6B;A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OAAkC;AACnD,SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AASO,SAAS,wBAAwB,OAAwB;AAC9D,SAAO,WAAW,UAAU,KAAK,CAAC,GAAG,UAAU;AACjD;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;;;ADnUM,IAAM,mBAAmB;AAEzB,SAAS,sBAAsB,IAAa,KAAmD;AACpG,MAAI,KAAC,oBAAM,GAAG,KAAK,KAAK,CAAC,eAAW,qBAAO,GAAG,KAAK,CAAC,EAAG,QAAO;AAC9D,MAAI,KAAC,6BAAY,IAAI,CAAC,eAAe,GAAG,CAAC,mBAAmB,CAAC,EAAG,QAAO;AACvE,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,kBAAkB,UAAU,sBAAe,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AAC9H;","names":["import_util"]}
1
+ {"version":3,"sources":["../src/activity.ts","../src/router.ts"],"sourcesContent":["/**\n * Activity recognition for KyberSwap: a `swap()` call to MetaAggregationRouterV2 on a chain the module serves →\n * `swap`, \"Swapped A → B\" from the owner's net transfers.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {KYBER_ROUTER_V2, KYBER_SWAP_SELECTOR, kyberChain} from \"./router.js\";\n\nexport const KYBERSWAP_MODULE = \"@anywalletkit/protocol-swap2-kyberswap\";\n\nexport function describeKyberActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain) || !kyberChain(evmRef(tx.chain))) return null;\n if (!matchesCall(tx, [KYBER_ROUTER_V2], [KYBER_SWAP_SELECTOR])) return null;\n return describeSwapLike(tx, ctx, {protocol: KYBERSWAP_MODULE, subtitle: `KyberSwap · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** KyberSwap's own limit orders: makers' signed orders kept off-chain, filled on-chain by the executor (the active source id). */\nexport const KYBER_LIMIT_ORDER_SOURCES: readonly string[] = Object.freeze([\"kyberswap-limit-order-v2\"]);\n\n/**\n * KyberSwap's RFQ sources per chain — private market makers whose firm quote is signed when the route is built: the\n * sources tagged \"RFQ sources\" in KyberSwap's own source list (`ks-setting.kyberswap.com/api/v1/dexes`, read\n * 2026-11-30). `excludeRFQSources=true` leaves out these and the limit orders together; this list is how the provider\n * asks for limit orders without RFQ (`limitOrders: \"include\"`, `rfq: \"exclude\"`). An empty list: the chain had no RFQ\n * source. A source KyberSwap adds later is still recognised in a route by `kyberSourceKind` (its `poolType`, or an\n * RFQ-like id), so the quote is marked and timed as RFQ; only the request would not leave it out.\n */\nexport const KYBER_RFQ_SOURCES: Readonly<Record<number, readonly string[]>> = Object.freeze({\n 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\"],\n 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\"],\n 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\"],\n 42161: [\"bebop\", \"hashflow-v3\", \"native-v1\", \"native-v2\", \"pmm-13\", \"pmm-2\", \"pmm-21\", \"pmm-5\", \"pmm-6\", \"pmm-7\", \"pmm-8\", \"swaap-v2\"],\n 10: [\"bebop\", \"pmm-13\", \"swaap-v2\"],\n 137: [\"bebop\", \"native-v1\", \"pmm-5\", \"pmm-8\", \"swaap-v2\"],\n 43114: [\"bebop\", \"dexalot\", \"hashflow-v3\", \"native-v1\", \"pmm-4\", \"swaap-v2\"],\n 59144: [\"native-v1\", \"swaap-v2\"],\n 146: [\"swaap-v2\"],\n 80094: [\"bebop\"],\n 130: [],\n 999: [\"bebop\"],\n 9745: [],\n 143: [\"native-v2\", \"swaap-v2\"],\n 4326: [],\n 4663: [\"bebop\", \"native-v2\", \"pmm-18\", \"pmm-19\", \"pmm-20\", \"swaap-v2\"],\n 5042: [\"pmm-13\"],\n 99901: [],\n});\n\n/** Source ids that look like RFQ wherever KyberSwap lists them (a source added after the list above was read). */\nconst 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-]*)$/;\n\n/**\n * What a route hop's liquidity is: an RFQ market maker, a KyberSwap limit order, or anything else (a pool, a\n * proprietary AMM). Read from the hop as `GET /routes` returns it: `poolType` (\"orderbook\" for an RFQ maker,\n * \"limit-order\" for a limit order) or the source id — the part before \"/\" when KyberSwap names a fallback after it\n * (\"pmm-19/uniswapv3\": the maker, and the pool the route falls back to when the maker does not sign).\n */\nexport function kyberSourceKind(chainId: number, exchange: unknown, poolType?: unknown): \"rfq\" | \"limit-order\" | \"pool\" {\n const id = typeof exchange === \"string\" ? exchange.split(\"/\")[0]! : \"\";\n if (poolType === \"limit-order\" || /^kyberswap-limit-order(?:-v\\d+)?$/.test(id)) return \"limit-order\";\n const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : [];\n return poolType === \"orderbook\" || listed.includes(id) || RFQ_LIKE.test(id) ? \"rfq\" : \"pool\";\n}\n\n/** The chain entry for an id, never an inherited property. */\nexport function kyberChain(chainId: number): (typeof KYBER_CHAINS)[number] | undefined {\n return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : undefined;\n}\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one. Arc's gas token is\n * USDC with 18-decimal native accounting, listed only through its 6-decimal ERC-20 interface, so a native leg there\n * would carry amounts 10^12 off the catalog's USDC; it is refused and the ERC-20 swaps instead.\n */\nexport function kyberNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** `swap(SwapExecutionParams)` — the one router entry point this module accepts. */\nexport const KYBER_ROUTER_ABI = parseAbi([\n \"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }\",\n \"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }\",\n \"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)\",\n]);\nexport const KYBER_SWAP_SELECTOR = \"0xe21fd0e9\";\n/** Router entry points that are refused by name: `swapGeneric` (owner-whitelisted arbitrary call) and `swapSimpleMode` (no minimum check). */\nexport const KYBER_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x59e50fed\": \"swapGeneric\",\n \"0x8af033fb\": \"swapSimpleMode\",\n});\n/**\n * The only flag bit accepted: `0x200`, set on every swap the build endpoint encodes (not one of the V2 source's named\n * flags; its meaning is not documented). Partial fill (0x01), extra value (0x02), claim (0x04), burns (0x08/0x10),\n * simple mode (0x20), fee on output (0x40), fee in bps (0x80) and approve-fund (0x100) are refused, as is any other bit.\n */\nexport const KYBER_FLAGS_ALLOWED = 0x200n;\n\nexport class KyberTransactionError extends Error {\n constructor(message: string) {\n super(`kyberswap: ${message}`);\n this.name = \"KyberTransactionError\";\n }\n}\nconst fail = (message: string, reason: Swap2RefusalReason): KyberTransactionError => withReason(new KyberTransactionError(message), reason);\nconst notes = refusalNotes();\n\nexport interface ExpectedKyberSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n /** Who must receive the output (the request's recipient). */\n receiver: string;\n /** The least `minReturnAmount` the calldata may name: the quote's minimum (and the caller's floor). */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nexport interface DecodedKyberSwap {\n srcToken: string;\n dstToken: string;\n dstReceiver: string;\n amount: bigint;\n minReturnAmount: bigint;\n flags: bigint;\n}\n\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: string, b: string): boolean => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();\nconst routerToken = (t: string): string => (same(t, ZERO) ? KYBER_NATIVE : t);\n/** The calldata may be a megabyte from an untrusted source: names in refusals are addresses only. */\nconst named = (a: unknown): string => (isAddr(a) ? a : \"something that is not an address\");\n/** At most this much calldata is decoded (a routed swap is a few KB). */\nconst MAX_CALLDATA_BYTES = 64 * 1024;\n\n/** Refuses (throws {@link KyberTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkKyberTransaction(tx: EncodedTx, expected: ExpectedKyberSwap): DecodedKyberSwap {\n const chain = kyberChain(expected.chainId);\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, \"unsupported_pair\");\n if (same(tx.to, KYBER_ROUTER_V3)) throw fail(\"Kyber router V3 not supported yet\", \"policy_refused\");\n if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, \"vault_mismatch\");\n if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {\n throw fail(\"invalid receiver\", \"recipient_mismatch\");\n }\n const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);\n if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n if (same(expected.tokenIn, expected.tokenOut)) throw fail(\"same token in and out\", \"unsupported_pair\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail(\"invalid quote amounts\", \"price_check_failed\");\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail(\"calldata is larger than any routed swap\", \"policy_refused\");\n const selector = tx.data.slice(0, 10).toLowerCase();\n const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : undefined;\n if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, \"policy_refused\");\n if (selector !== KYBER_SWAP_SELECTOR) throw fail(\"not a router swap() call\", \"policy_refused\");\n\n let x: {callTarget: string; approveTarget: string; targetData: Hex; desc: {srcToken: string; dstToken: string; srcReceivers: readonly string[]; srcAmounts: readonly bigint[]; feeReceivers: readonly string[]; feeAmounts: readonly bigint[]; dstReceiver: string; amount: bigint; minReturnAmount: bigint; flags: bigint; permit: Hex}; clientData: Hex};\n try {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: tx.data as Hex});\n x = call.args[0] as typeof x;\n // Strict: the calldata must be exactly the canonical encoding of what was decoded (no trailing bytes, no odd offsets or padding).\n const again = encodeFunctionData({abi: KYBER_ROUTER_ABI, functionName: \"swap\", args: [x as never]});\n if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error(\"non-canonical\");\n } catch {\n throw fail(\"the calldata is not a canonical router swap() encoding\", \"policy_refused\");\n }\n const d = x.desc;\n if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, \"vault_mismatch\");\n if (!same(x.approveTarget, ZERO)) throw fail(\"the swap asks the router to approve another contract\", \"policy_refused\");\n if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, \"price_check_failed\");\n if (d.srcReceivers.length !== d.srcAmounts.length) throw fail(\"malformed input split\", \"policy_refused\");\n if (nativeIn) {\n if (d.srcReceivers.length !== 0) throw fail(\"a native-coin swap must not split the input\", \"policy_refused\");\n if (tx.value !== expected.amountIn) throw fail(\"native value does not match the input\", \"price_check_failed\");\n } else {\n if (tx.value !== 0n) throw fail(\"a token swap must not send the native coin\", \"price_check_failed\");\n const total = d.srcAmounts.reduce((s, a) => s + a, 0n);\n if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, \"price_check_failed\");\n }\n if (same(d.dstReceiver, ZERO)) throw fail(\"the swap names no receiver\", \"recipient_mismatch\");\n if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (d.minReturnAmount <= 0n) throw fail(\"the swap names no minimum\", \"price_check_failed\");\n if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, \"price_check_failed\");\n if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail(\"calldata pays a fee receiver — this module charges none\", \"policy_refused\");\n if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, \"policy_refused\");\n if (d.permit !== \"0x\") throw fail(\"calldata carries a permit\", \"policy_refused\");\n return {srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags};\n}\n\n/**\n * The minimum KyberSwap's build encodes for `amountOut` at `bps` slippage: the expected output less the slippage,\n * rounded down, less one more unit — the build endpoint always lands exactly one base unit under the plain\n * `floor(amountOut × (10000 − bps) / 10000)` (18 chains, 2026-11-24). The quote shows this value, so the dry quote,\n * the build and the check agree to the unit.\n */\nexport function kyberMinimum(amountOut: bigint, bps: number): bigint {\n const m = (amountOut * BigInt(10_000 - bps)) / 10_000n - 1n;\n return m > 0n ? m : 0n;\n}\n\n/**\n * The slippage to ask KyberSwap for so that its minimum — one unit under the plain floor ({@link kyberMinimum}) — still\n * meets the engine's floor for the slippage the user chose, `floor(amountOut × (10000 − bps) / 10000)`. One basis point\n * less for most outputs; more for a tiny output (a $1 WBTC buy is a few thousand units, where 1 bps is under one unit).\n * Null when no positive slippage does (an output too small to carry a minimum).\n */\nexport function kyberApiSlippage(amountOut: bigint, bps: number): number | null {\n const floor = (amountOut * BigInt(10_000 - bps)) / 10_000n;\n for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;\n return null;\n}\n\n/** The slippage a KyberSwap quote is held to when the request names none, in bps: 0.5 %, the provider's own default. */\nexport const KYBER_DEFAULT_SLIPPAGE_BPS = 50;\n\nconst chainIdOf = (caip2: string): number => (/^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN);\n\n/**\n * The app's own check of a KyberSwap quote (behind `remoteProvider`, or on any quote): one chain, the exact input,\n * a minimum at or under the expected output, within the slippage (default {@link KYBER_DEFAULT_SLIPPAGE_BPS}) and at or\n * above the caller's floor; an execution quote's transaction must\n * pass {@link checkKyberTransaction} against this app's request. A dry quote carries no transaction. The reason it fails, or null.\n */\nexport function kyberVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = chainIdOf(params.sourceChain);\n if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, \"unsupported_pair\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n if (quote.sourceAmount !== params.amountIn) return notes.note(\"the quote prices another amount\", \"price_check_failed\");\n const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);\n if (min <= 0n || min > out) return notes.note(\"invalid quote amounts\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && min < BigInt(params.minAmountOut)) return notes.note(\"the quote's minimum is under the floor\", \"price_check_failed\");\n // The minimum is the expected output less the requested slippage — the provider's default when the request names\n // none — never more slippage than that: without a default, a backend's minimum of one unit would pass.\n const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return notes.note(\"invalid slippage\", \"policy_refused\");\n if (min < kyberMinimum(out, bps)) {\n return notes.note(\"the quote's minimum allows more slippage than requested\", \"price_check_failed\");\n }\n const tx = quote.txRequest;\n if (!tx) return params.dry === false ? notes.note(\"the quote carries no router transaction\", \"policy_refused\") : null;\n if (!tx.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n if (tx.approvalAddress !== undefined && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note(\"the quote asks to approve another spender\", \"vault_mismatch\");\n checkKyberTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n minAmountOut: min,\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e);\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\nfunction routerFor(chain: string): readonly string[] {\n return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];\n}\n\n/**\n * The provider's `exactAllowanceOnly` (protocol-swap2-core): true on the chains whose router is the `generic` build —\n * `swapGeneric` behind an owner-managed executor whitelist, so the router's owner (a single key on all but Linea) could\n * make it spend an allowance left on it. The engine then approves exactly the input and revokes it when the swap does\n * not spend it, whatever the app's `allowanceReuse` / `revokeUnspentApproval` say. False on the `lite` chains; true\n * for a chain this module does not know (fail closed).\n */\nexport function kyberExactAllowanceOnly(chain: string): boolean {\n return kyberChain(chainIdOf(chain))?.build !== \"lite\";\n}\n\n/**\n * The router a KyberSwap swap calls and approves, and {@link kyberVerifyQuote}: the app's side of\n * `remoteProvider({name: \"kyberswap\", baseUrl, ...kyberPins})`, so a backend's quote is checked against the pinned\n * router and the app's own request, never against itself.\n */\nexport const kyberPins: RemotePins = Object.freeze({\n callTargets: routerFor,\n spenders: routerFor,\n exactAllowanceOnly: kyberExactAllowanceOnly,\n // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate\n // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.\n ownGasEstimate: true,\n verifyQuote: kyberVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,sBAAwD;AACxD,IAAAA,eAA4B;;;ACM5B,kBAA4B;AAC5B,oBAA2E;AAC3E,0BAA6B;AAC7B,kBAAqF;AAG9E,IAAM,kBAAkB;AAExB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkB;AAExB,IAAM,eAAe;AAC5B,IAAM,OAAO;AAeN,IAAM,eAAgG,OAAO,OAAO;AAAA,EACzH,GAAG,EAAC,MAAM,YAAY,MA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AO,WAAW,UAAU,KAAK,CAAC,GAAG,UAAU;AACjD;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,oBAAoB;AAAA;AAAA;AAAA,EAGpB,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;;;AD5UM,IAAM,mBAAmB;AAEzB,SAAS,sBAAsB,IAAa,KAAmD;AACpG,MAAI,KAAC,oBAAM,GAAG,KAAK,KAAK,CAAC,eAAW,qBAAO,GAAG,KAAK,CAAC,EAAG,QAAO;AAC9D,MAAI,KAAC,6BAAY,IAAI,CAAC,eAAe,GAAG,CAAC,mBAAmB,CAAC,EAAG,QAAO;AACvE,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,kBAAkB,UAAU,sBAAe,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AAC9H;","names":["import_util"]}
package/dist/activity.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  KYBERSWAP_MODULE,
3
3
  describeKyberActivity
4
- } from "./chunk-HHZEL5IJ.js";
5
- import "./chunk-D4UIDHM2.js";
4
+ } from "./chunk-DP4WDX4C.js";
5
+ import "./chunk-CFL4E4AW.js";
6
6
  export {
7
7
  KYBERSWAP_MODULE,
8
8
  describeKyberActivity
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  kyberswapProvider
3
- } from "./chunk-NFMHUXU6.js";
3
+ } from "./chunk-INSCVUFN.js";
4
4
  import {
5
5
  kyberChain
6
- } from "./chunk-D4UIDHM2.js";
6
+ } from "./chunk-CFL4E4AW.js";
7
7
 
8
8
  // src/protocol.ts
9
9
  import { SingleProviderSwap2 } from "@anywalletkit/protocol-swap2-core/swap2/single";
@@ -29,4 +29,4 @@ var KyberswapSwap2Protocol = class extends SingleProviderSwap2 {
29
29
  export {
30
30
  KyberswapSwap2Protocol
31
31
  };
32
- //# sourceMappingURL=chunk-LIEIWIYI.js.map
32
+ //# sourceMappingURL=chunk-BGMHF5MC.js.map
@@ -145,6 +145,7 @@ function kyberApiSlippage(amountOut, bps) {
145
145
  for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;
146
146
  return null;
147
147
  }
148
+ var KYBER_DEFAULT_SLIPPAGE_BPS = 50;
148
149
  var chainIdOf = (caip2) => /^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN;
149
150
  function kyberVerifyQuote(params, quote) {
150
151
  if (params.sourceChain !== params.destChain) return notes.note("same-chain swaps only", "unsupported_pair");
@@ -157,8 +158,9 @@ function kyberVerifyQuote(params, quote) {
157
158
  const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);
158
159
  if (min <= 0n || min > out) return notes.note("invalid quote amounts", "price_check_failed");
159
160
  if (params.minAmountOut !== void 0 && min < BigInt(params.minAmountOut)) return notes.note("the quote's minimum is under the floor", "price_check_failed");
160
- const bps = params.slippageBps;
161
- if (bps !== void 0 && Number.isInteger(bps) && bps >= 0 && bps < 1e4 && min < kyberMinimum(out, bps)) {
161
+ const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;
162
+ if (!Number.isInteger(bps) || bps < 0 || bps >= 1e4) return notes.note("invalid slippage", "policy_refused");
163
+ if (min < kyberMinimum(out, bps)) {
162
164
  return notes.note("the quote's minimum allows more slippage than requested", "price_check_failed");
163
165
  }
164
166
  const tx = quote.txRequest;
@@ -190,6 +192,9 @@ var kyberPins = Object.freeze({
190
192
  callTargets: routerFor,
191
193
  spenders: routerFor,
192
194
  exactAllowanceOnly: kyberExactAllowanceOnly,
195
+ // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate
196
+ // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.
197
+ ownGasEstimate: true,
193
198
  verifyQuote: kyberVerifyQuote,
194
199
  reasonOf: (refusal) => notes.reasonOf(refusal)
195
200
  });
@@ -213,8 +218,9 @@ export {
213
218
  checkKyberTransaction,
214
219
  kyberMinimum,
215
220
  kyberApiSlippage,
221
+ KYBER_DEFAULT_SLIPPAGE_BPS,
216
222
  kyberVerifyQuote,
217
223
  kyberExactAllowanceOnly,
218
224
  kyberPins
219
225
  };
220
- //# sourceMappingURL=chunk-D4UIDHM2.js.map
226
+ //# sourceMappingURL=chunk-CFL4E4AW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/router.ts"],"sourcesContent":["/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** KyberSwap's own limit orders: makers' signed orders kept off-chain, filled on-chain by the executor (the active source id). */\nexport const KYBER_LIMIT_ORDER_SOURCES: readonly string[] = Object.freeze([\"kyberswap-limit-order-v2\"]);\n\n/**\n * KyberSwap's RFQ sources per chain — private market makers whose firm quote is signed when the route is built: the\n * sources tagged \"RFQ sources\" in KyberSwap's own source list (`ks-setting.kyberswap.com/api/v1/dexes`, read\n * 2026-11-30). `excludeRFQSources=true` leaves out these and the limit orders together; this list is how the provider\n * asks for limit orders without RFQ (`limitOrders: \"include\"`, `rfq: \"exclude\"`). An empty list: the chain had no RFQ\n * source. A source KyberSwap adds later is still recognised in a route by `kyberSourceKind` (its `poolType`, or an\n * RFQ-like id), so the quote is marked and timed as RFQ; only the request would not leave it out.\n */\nexport const KYBER_RFQ_SOURCES: Readonly<Record<number, readonly string[]>> = Object.freeze({\n 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\"],\n 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\"],\n 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\"],\n 42161: [\"bebop\", \"hashflow-v3\", \"native-v1\", \"native-v2\", \"pmm-13\", \"pmm-2\", \"pmm-21\", \"pmm-5\", \"pmm-6\", \"pmm-7\", \"pmm-8\", \"swaap-v2\"],\n 10: [\"bebop\", \"pmm-13\", \"swaap-v2\"],\n 137: [\"bebop\", \"native-v1\", \"pmm-5\", \"pmm-8\", \"swaap-v2\"],\n 43114: [\"bebop\", \"dexalot\", \"hashflow-v3\", \"native-v1\", \"pmm-4\", \"swaap-v2\"],\n 59144: [\"native-v1\", \"swaap-v2\"],\n 146: [\"swaap-v2\"],\n 80094: [\"bebop\"],\n 130: [],\n 999: [\"bebop\"],\n 9745: [],\n 143: [\"native-v2\", \"swaap-v2\"],\n 4326: [],\n 4663: [\"bebop\", \"native-v2\", \"pmm-18\", \"pmm-19\", \"pmm-20\", \"swaap-v2\"],\n 5042: [\"pmm-13\"],\n 99901: [],\n});\n\n/** Source ids that look like RFQ wherever KyberSwap lists them (a source added after the list above was read). */\nconst 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-]*)$/;\n\n/**\n * What a route hop's liquidity is: an RFQ market maker, a KyberSwap limit order, or anything else (a pool, a\n * proprietary AMM). Read from the hop as `GET /routes` returns it: `poolType` (\"orderbook\" for an RFQ maker,\n * \"limit-order\" for a limit order) or the source id — the part before \"/\" when KyberSwap names a fallback after it\n * (\"pmm-19/uniswapv3\": the maker, and the pool the route falls back to when the maker does not sign).\n */\nexport function kyberSourceKind(chainId: number, exchange: unknown, poolType?: unknown): \"rfq\" | \"limit-order\" | \"pool\" {\n const id = typeof exchange === \"string\" ? exchange.split(\"/\")[0]! : \"\";\n if (poolType === \"limit-order\" || /^kyberswap-limit-order(?:-v\\d+)?$/.test(id)) return \"limit-order\";\n const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : [];\n return poolType === \"orderbook\" || listed.includes(id) || RFQ_LIKE.test(id) ? \"rfq\" : \"pool\";\n}\n\n/** The chain entry for an id, never an inherited property. */\nexport function kyberChain(chainId: number): (typeof KYBER_CHAINS)[number] | undefined {\n return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : undefined;\n}\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one. Arc's gas token is\n * USDC with 18-decimal native accounting, listed only through its 6-decimal ERC-20 interface, so a native leg there\n * would carry amounts 10^12 off the catalog's USDC; it is refused and the ERC-20 swaps instead.\n */\nexport function kyberNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** `swap(SwapExecutionParams)` — the one router entry point this module accepts. */\nexport const KYBER_ROUTER_ABI = parseAbi([\n \"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }\",\n \"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }\",\n \"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)\",\n]);\nexport const KYBER_SWAP_SELECTOR = \"0xe21fd0e9\";\n/** Router entry points that are refused by name: `swapGeneric` (owner-whitelisted arbitrary call) and `swapSimpleMode` (no minimum check). */\nexport const KYBER_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x59e50fed\": \"swapGeneric\",\n \"0x8af033fb\": \"swapSimpleMode\",\n});\n/**\n * The only flag bit accepted: `0x200`, set on every swap the build endpoint encodes (not one of the V2 source's named\n * flags; its meaning is not documented). Partial fill (0x01), extra value (0x02), claim (0x04), burns (0x08/0x10),\n * simple mode (0x20), fee on output (0x40), fee in bps (0x80) and approve-fund (0x100) are refused, as is any other bit.\n */\nexport const KYBER_FLAGS_ALLOWED = 0x200n;\n\nexport class KyberTransactionError extends Error {\n constructor(message: string) {\n super(`kyberswap: ${message}`);\n this.name = \"KyberTransactionError\";\n }\n}\nconst fail = (message: string, reason: Swap2RefusalReason): KyberTransactionError => withReason(new KyberTransactionError(message), reason);\nconst notes = refusalNotes();\n\nexport interface ExpectedKyberSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n /** Who must receive the output (the request's recipient). */\n receiver: string;\n /** The least `minReturnAmount` the calldata may name: the quote's minimum (and the caller's floor). */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nexport interface DecodedKyberSwap {\n srcToken: string;\n dstToken: string;\n dstReceiver: string;\n amount: bigint;\n minReturnAmount: bigint;\n flags: bigint;\n}\n\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: string, b: string): boolean => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();\nconst routerToken = (t: string): string => (same(t, ZERO) ? KYBER_NATIVE : t);\n/** The calldata may be a megabyte from an untrusted source: names in refusals are addresses only. */\nconst named = (a: unknown): string => (isAddr(a) ? a : \"something that is not an address\");\n/** At most this much calldata is decoded (a routed swap is a few KB). */\nconst MAX_CALLDATA_BYTES = 64 * 1024;\n\n/** Refuses (throws {@link KyberTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkKyberTransaction(tx: EncodedTx, expected: ExpectedKyberSwap): DecodedKyberSwap {\n const chain = kyberChain(expected.chainId);\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, \"unsupported_pair\");\n if (same(tx.to, KYBER_ROUTER_V3)) throw fail(\"Kyber router V3 not supported yet\", \"policy_refused\");\n if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, \"vault_mismatch\");\n if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {\n throw fail(\"invalid receiver\", \"recipient_mismatch\");\n }\n const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);\n if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n if (same(expected.tokenIn, expected.tokenOut)) throw fail(\"same token in and out\", \"unsupported_pair\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail(\"invalid quote amounts\", \"price_check_failed\");\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail(\"calldata is larger than any routed swap\", \"policy_refused\");\n const selector = tx.data.slice(0, 10).toLowerCase();\n const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : undefined;\n if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, \"policy_refused\");\n if (selector !== KYBER_SWAP_SELECTOR) throw fail(\"not a router swap() call\", \"policy_refused\");\n\n let x: {callTarget: string; approveTarget: string; targetData: Hex; desc: {srcToken: string; dstToken: string; srcReceivers: readonly string[]; srcAmounts: readonly bigint[]; feeReceivers: readonly string[]; feeAmounts: readonly bigint[]; dstReceiver: string; amount: bigint; minReturnAmount: bigint; flags: bigint; permit: Hex}; clientData: Hex};\n try {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: tx.data as Hex});\n x = call.args[0] as typeof x;\n // Strict: the calldata must be exactly the canonical encoding of what was decoded (no trailing bytes, no odd offsets or padding).\n const again = encodeFunctionData({abi: KYBER_ROUTER_ABI, functionName: \"swap\", args: [x as never]});\n if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error(\"non-canonical\");\n } catch {\n throw fail(\"the calldata is not a canonical router swap() encoding\", \"policy_refused\");\n }\n const d = x.desc;\n if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, \"vault_mismatch\");\n if (!same(x.approveTarget, ZERO)) throw fail(\"the swap asks the router to approve another contract\", \"policy_refused\");\n if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, \"price_check_failed\");\n if (d.srcReceivers.length !== d.srcAmounts.length) throw fail(\"malformed input split\", \"policy_refused\");\n if (nativeIn) {\n if (d.srcReceivers.length !== 0) throw fail(\"a native-coin swap must not split the input\", \"policy_refused\");\n if (tx.value !== expected.amountIn) throw fail(\"native value does not match the input\", \"price_check_failed\");\n } else {\n if (tx.value !== 0n) throw fail(\"a token swap must not send the native coin\", \"price_check_failed\");\n const total = d.srcAmounts.reduce((s, a) => s + a, 0n);\n if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, \"price_check_failed\");\n }\n if (same(d.dstReceiver, ZERO)) throw fail(\"the swap names no receiver\", \"recipient_mismatch\");\n if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (d.minReturnAmount <= 0n) throw fail(\"the swap names no minimum\", \"price_check_failed\");\n if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, \"price_check_failed\");\n if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail(\"calldata pays a fee receiver — this module charges none\", \"policy_refused\");\n if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, \"policy_refused\");\n if (d.permit !== \"0x\") throw fail(\"calldata carries a permit\", \"policy_refused\");\n return {srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags};\n}\n\n/**\n * The minimum KyberSwap's build encodes for `amountOut` at `bps` slippage: the expected output less the slippage,\n * rounded down, less one more unit — the build endpoint always lands exactly one base unit under the plain\n * `floor(amountOut × (10000 − bps) / 10000)` (18 chains, 2026-11-24). The quote shows this value, so the dry quote,\n * the build and the check agree to the unit.\n */\nexport function kyberMinimum(amountOut: bigint, bps: number): bigint {\n const m = (amountOut * BigInt(10_000 - bps)) / 10_000n - 1n;\n return m > 0n ? m : 0n;\n}\n\n/**\n * The slippage to ask KyberSwap for so that its minimum — one unit under the plain floor ({@link kyberMinimum}) — still\n * meets the engine's floor for the slippage the user chose, `floor(amountOut × (10000 − bps) / 10000)`. One basis point\n * less for most outputs; more for a tiny output (a $1 WBTC buy is a few thousand units, where 1 bps is under one unit).\n * Null when no positive slippage does (an output too small to carry a minimum).\n */\nexport function kyberApiSlippage(amountOut: bigint, bps: number): number | null {\n const floor = (amountOut * BigInt(10_000 - bps)) / 10_000n;\n for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;\n return null;\n}\n\nconst chainIdOf = (caip2: string): number => (/^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN);\n\n/**\n * The app's own check of a KyberSwap quote (behind `remoteProvider`, or on any quote): one chain, the exact input,\n * a minimum at or under the expected output and at or above the caller's floor; an execution quote's transaction must\n * pass {@link checkKyberTransaction} against this app's request. A dry quote carries no transaction. The reason it fails, or null.\n */\nexport function kyberVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = chainIdOf(params.sourceChain);\n if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, \"unsupported_pair\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n if (quote.sourceAmount !== params.amountIn) return notes.note(\"the quote prices another amount\", \"price_check_failed\");\n const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);\n if (min <= 0n || min > out) return notes.note(\"invalid quote amounts\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && min < BigInt(params.minAmountOut)) return notes.note(\"the quote's minimum is under the floor\", \"price_check_failed\");\n // The minimum is the expected output less the requested slippage, never more slippage than asked for.\n const bps = params.slippageBps;\n if (bps !== undefined && Number.isInteger(bps) && bps >= 0 && bps < 10_000 && min < kyberMinimum(out, bps)) {\n return notes.note(\"the quote's minimum allows more slippage than requested\", \"price_check_failed\");\n }\n const tx = quote.txRequest;\n if (!tx) return params.dry === false ? notes.note(\"the quote carries no router transaction\", \"policy_refused\") : null;\n if (!tx.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n if (tx.approvalAddress !== undefined && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note(\"the quote asks to approve another spender\", \"vault_mismatch\");\n checkKyberTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n minAmountOut: min,\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e);\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\nfunction routerFor(chain: string): readonly string[] {\n return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];\n}\n\n/**\n * The provider's `exactAllowanceOnly` (protocol-swap2-core): true on the chains whose router is the `generic` build —\n * `swapGeneric` behind an owner-managed executor whitelist, so the router's owner (a single key on all but Linea) could\n * make it spend an allowance left on it. The engine then approves exactly the input and revokes it when the swap does\n * not spend it, whatever the app's `allowanceReuse` / `revokeUnspentApproval` say. False on the `lite` chains; true\n * for a chain this module does not know (fail closed).\n */\nexport function kyberExactAllowanceOnly(chain: string): boolean {\n return kyberChain(chainIdOf(chain))?.build !== \"lite\";\n}\n\n/**\n * The router a KyberSwap swap calls and approves, and {@link kyberVerifyQuote}: the app's side of\n * `remoteProvider({name: \"kyberswap\", baseUrl, ...kyberPins})`, so a backend's quote is checked against the pinned\n * router and the app's own request, never against itself.\n */\nexport const kyberPins: RemotePins = Object.freeze({\n callTargets: routerFor,\n spenders: routerFor,\n exactAllowanceOnly: kyberExactAllowanceOnly,\n verifyQuote: kyberVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\n"],"mappings":";AAYA,SAAQ,qBAAoB;AAC5B,SAAQ,cAAc,WAAW,kBAA0C;AAC3E,SAAQ,sBAAqB;AAC7B,SAAQ,oBAAoB,oBAAoB,YAAY,gBAAyB;AAG9E,IAAM,kBAAkB;AAExB,IAAM,iBAAiB;AAEvB,IAAM,kBAAkB;AAExB,IAAM,eAAe;AAC5B,IAAM,OAAO;AAeN,IAAM,eAAgG,OAAO,OAAO;AAAA,EACzH,GAAG,EAAC,MAAM,YAAY,MAAM,YAAY,OAAO,UAAS;AAAA,EACxD,MAAM,EAAC,MAAM,QAAQ,MAAM,QAAQ,OAAO,UAAS;AAAA,EACnD,IAAI,EAAC,MAAM,OAAO,MAAM,mBAAmB,OAAO,UAAS;AAAA,EAC3D,OAAO,EAAC,MAAM,YAAY,MAAM,YAAY,OAAO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AM,OAAO,aAAa,QAAQ,EAAE,QAAQ,QAAQ,gBAAgB,EAAE,IAAI,OAAO,CAAC;AAClF,UAAM,OAAO,UAAU,CAAC;AACxB,WAAO,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,EACzC;AACF;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AASO,SAAS,wBAAwB,OAAwB;AAC9D,SAAO,WAAW,UAAU,KAAK,CAAC,GAAG,UAAU;AACjD;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;","names":[]}
1
+ {"version":3,"sources":["../src/router.ts"],"sourcesContent":["/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** KyberSwap's own limit orders: makers' signed orders kept off-chain, filled on-chain by the executor (the active source id). */\nexport const KYBER_LIMIT_ORDER_SOURCES: readonly string[] = Object.freeze([\"kyberswap-limit-order-v2\"]);\n\n/**\n * KyberSwap's RFQ sources per chain — private market makers whose firm quote is signed when the route is built: the\n * sources tagged \"RFQ sources\" in KyberSwap's own source list (`ks-setting.kyberswap.com/api/v1/dexes`, read\n * 2026-11-30). `excludeRFQSources=true` leaves out these and the limit orders together; this list is how the provider\n * asks for limit orders without RFQ (`limitOrders: \"include\"`, `rfq: \"exclude\"`). An empty list: the chain had no RFQ\n * source. A source KyberSwap adds later is still recognised in a route by `kyberSourceKind` (its `poolType`, or an\n * RFQ-like id), so the quote is marked and timed as RFQ; only the request would not leave it out.\n */\nexport const KYBER_RFQ_SOURCES: Readonly<Record<number, readonly string[]>> = Object.freeze({\n 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\"],\n 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\"],\n 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\"],\n 42161: [\"bebop\", \"hashflow-v3\", \"native-v1\", \"native-v2\", \"pmm-13\", \"pmm-2\", \"pmm-21\", \"pmm-5\", \"pmm-6\", \"pmm-7\", \"pmm-8\", \"swaap-v2\"],\n 10: [\"bebop\", \"pmm-13\", \"swaap-v2\"],\n 137: [\"bebop\", \"native-v1\", \"pmm-5\", \"pmm-8\", \"swaap-v2\"],\n 43114: [\"bebop\", \"dexalot\", \"hashflow-v3\", \"native-v1\", \"pmm-4\", \"swaap-v2\"],\n 59144: [\"native-v1\", \"swaap-v2\"],\n 146: [\"swaap-v2\"],\n 80094: [\"bebop\"],\n 130: [],\n 999: [\"bebop\"],\n 9745: [],\n 143: [\"native-v2\", \"swaap-v2\"],\n 4326: [],\n 4663: [\"bebop\", \"native-v2\", \"pmm-18\", \"pmm-19\", \"pmm-20\", \"swaap-v2\"],\n 5042: [\"pmm-13\"],\n 99901: [],\n});\n\n/** Source ids that look like RFQ wherever KyberSwap lists them (a source added after the list above was read). */\nconst 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-]*)$/;\n\n/**\n * What a route hop's liquidity is: an RFQ market maker, a KyberSwap limit order, or anything else (a pool, a\n * proprietary AMM). Read from the hop as `GET /routes` returns it: `poolType` (\"orderbook\" for an RFQ maker,\n * \"limit-order\" for a limit order) or the source id — the part before \"/\" when KyberSwap names a fallback after it\n * (\"pmm-19/uniswapv3\": the maker, and the pool the route falls back to when the maker does not sign).\n */\nexport function kyberSourceKind(chainId: number, exchange: unknown, poolType?: unknown): \"rfq\" | \"limit-order\" | \"pool\" {\n const id = typeof exchange === \"string\" ? exchange.split(\"/\")[0]! : \"\";\n if (poolType === \"limit-order\" || /^kyberswap-limit-order(?:-v\\d+)?$/.test(id)) return \"limit-order\";\n const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : [];\n return poolType === \"orderbook\" || listed.includes(id) || RFQ_LIKE.test(id) ? \"rfq\" : \"pool\";\n}\n\n/** The chain entry for an id, never an inherited property. */\nexport function kyberChain(chainId: number): (typeof KYBER_CHAINS)[number] | undefined {\n return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : undefined;\n}\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one. Arc's gas token is\n * USDC with 18-decimal native accounting, listed only through its 6-decimal ERC-20 interface, so a native leg there\n * would carry amounts 10^12 off the catalog's USDC; it is refused and the ERC-20 swaps instead.\n */\nexport function kyberNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** `swap(SwapExecutionParams)` — the one router entry point this module accepts. */\nexport const KYBER_ROUTER_ABI = parseAbi([\n \"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }\",\n \"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }\",\n \"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)\",\n]);\nexport const KYBER_SWAP_SELECTOR = \"0xe21fd0e9\";\n/** Router entry points that are refused by name: `swapGeneric` (owner-whitelisted arbitrary call) and `swapSimpleMode` (no minimum check). */\nexport const KYBER_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x59e50fed\": \"swapGeneric\",\n \"0x8af033fb\": \"swapSimpleMode\",\n});\n/**\n * The only flag bit accepted: `0x200`, set on every swap the build endpoint encodes (not one of the V2 source's named\n * flags; its meaning is not documented). Partial fill (0x01), extra value (0x02), claim (0x04), burns (0x08/0x10),\n * simple mode (0x20), fee on output (0x40), fee in bps (0x80) and approve-fund (0x100) are refused, as is any other bit.\n */\nexport const KYBER_FLAGS_ALLOWED = 0x200n;\n\nexport class KyberTransactionError extends Error {\n constructor(message: string) {\n super(`kyberswap: ${message}`);\n this.name = \"KyberTransactionError\";\n }\n}\nconst fail = (message: string, reason: Swap2RefusalReason): KyberTransactionError => withReason(new KyberTransactionError(message), reason);\nconst notes = refusalNotes();\n\nexport interface ExpectedKyberSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n /** Who must receive the output (the request's recipient). */\n receiver: string;\n /** The least `minReturnAmount` the calldata may name: the quote's minimum (and the caller's floor). */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nexport interface DecodedKyberSwap {\n srcToken: string;\n dstToken: string;\n dstReceiver: string;\n amount: bigint;\n minReturnAmount: bigint;\n flags: bigint;\n}\n\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: string, b: string): boolean => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();\nconst routerToken = (t: string): string => (same(t, ZERO) ? KYBER_NATIVE : t);\n/** The calldata may be a megabyte from an untrusted source: names in refusals are addresses only. */\nconst named = (a: unknown): string => (isAddr(a) ? a : \"something that is not an address\");\n/** At most this much calldata is decoded (a routed swap is a few KB). */\nconst MAX_CALLDATA_BYTES = 64 * 1024;\n\n/** Refuses (throws {@link KyberTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkKyberTransaction(tx: EncodedTx, expected: ExpectedKyberSwap): DecodedKyberSwap {\n const chain = kyberChain(expected.chainId);\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, \"unsupported_pair\");\n if (same(tx.to, KYBER_ROUTER_V3)) throw fail(\"Kyber router V3 not supported yet\", \"policy_refused\");\n if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, \"vault_mismatch\");\n if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {\n throw fail(\"invalid receiver\", \"recipient_mismatch\");\n }\n const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);\n if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n if (same(expected.tokenIn, expected.tokenOut)) throw fail(\"same token in and out\", \"unsupported_pair\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail(\"invalid quote amounts\", \"price_check_failed\");\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail(\"calldata is larger than any routed swap\", \"policy_refused\");\n const selector = tx.data.slice(0, 10).toLowerCase();\n const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : undefined;\n if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, \"policy_refused\");\n if (selector !== KYBER_SWAP_SELECTOR) throw fail(\"not a router swap() call\", \"policy_refused\");\n\n let x: {callTarget: string; approveTarget: string; targetData: Hex; desc: {srcToken: string; dstToken: string; srcReceivers: readonly string[]; srcAmounts: readonly bigint[]; feeReceivers: readonly string[]; feeAmounts: readonly bigint[]; dstReceiver: string; amount: bigint; minReturnAmount: bigint; flags: bigint; permit: Hex}; clientData: Hex};\n try {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: tx.data as Hex});\n x = call.args[0] as typeof x;\n // Strict: the calldata must be exactly the canonical encoding of what was decoded (no trailing bytes, no odd offsets or padding).\n const again = encodeFunctionData({abi: KYBER_ROUTER_ABI, functionName: \"swap\", args: [x as never]});\n if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error(\"non-canonical\");\n } catch {\n throw fail(\"the calldata is not a canonical router swap() encoding\", \"policy_refused\");\n }\n const d = x.desc;\n if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, \"vault_mismatch\");\n if (!same(x.approveTarget, ZERO)) throw fail(\"the swap asks the router to approve another contract\", \"policy_refused\");\n if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, \"price_check_failed\");\n if (d.srcReceivers.length !== d.srcAmounts.length) throw fail(\"malformed input split\", \"policy_refused\");\n if (nativeIn) {\n if (d.srcReceivers.length !== 0) throw fail(\"a native-coin swap must not split the input\", \"policy_refused\");\n if (tx.value !== expected.amountIn) throw fail(\"native value does not match the input\", \"price_check_failed\");\n } else {\n if (tx.value !== 0n) throw fail(\"a token swap must not send the native coin\", \"price_check_failed\");\n const total = d.srcAmounts.reduce((s, a) => s + a, 0n);\n if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, \"price_check_failed\");\n }\n if (same(d.dstReceiver, ZERO)) throw fail(\"the swap names no receiver\", \"recipient_mismatch\");\n if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (d.minReturnAmount <= 0n) throw fail(\"the swap names no minimum\", \"price_check_failed\");\n if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, \"price_check_failed\");\n if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail(\"calldata pays a fee receiver — this module charges none\", \"policy_refused\");\n if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, \"policy_refused\");\n if (d.permit !== \"0x\") throw fail(\"calldata carries a permit\", \"policy_refused\");\n return {srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags};\n}\n\n/**\n * The minimum KyberSwap's build encodes for `amountOut` at `bps` slippage: the expected output less the slippage,\n * rounded down, less one more unit — the build endpoint always lands exactly one base unit under the plain\n * `floor(amountOut × (10000 − bps) / 10000)` (18 chains, 2026-11-24). The quote shows this value, so the dry quote,\n * the build and the check agree to the unit.\n */\nexport function kyberMinimum(amountOut: bigint, bps: number): bigint {\n const m = (amountOut * BigInt(10_000 - bps)) / 10_000n - 1n;\n return m > 0n ? m : 0n;\n}\n\n/**\n * The slippage to ask KyberSwap for so that its minimum — one unit under the plain floor ({@link kyberMinimum}) — still\n * meets the engine's floor for the slippage the user chose, `floor(amountOut × (10000 − bps) / 10000)`. One basis point\n * less for most outputs; more for a tiny output (a $1 WBTC buy is a few thousand units, where 1 bps is under one unit).\n * Null when no positive slippage does (an output too small to carry a minimum).\n */\nexport function kyberApiSlippage(amountOut: bigint, bps: number): number | null {\n const floor = (amountOut * BigInt(10_000 - bps)) / 10_000n;\n for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;\n return null;\n}\n\n/** The slippage a KyberSwap quote is held to when the request names none, in bps: 0.5 %, the provider's own default. */\nexport const KYBER_DEFAULT_SLIPPAGE_BPS = 50;\n\nconst chainIdOf = (caip2: string): number => (/^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN);\n\n/**\n * The app's own check of a KyberSwap quote (behind `remoteProvider`, or on any quote): one chain, the exact input,\n * a minimum at or under the expected output, within the slippage (default {@link KYBER_DEFAULT_SLIPPAGE_BPS}) and at or\n * above the caller's floor; an execution quote's transaction must\n * pass {@link checkKyberTransaction} against this app's request. A dry quote carries no transaction. The reason it fails, or null.\n */\nexport function kyberVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = chainIdOf(params.sourceChain);\n if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, \"unsupported_pair\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n if (quote.sourceAmount !== params.amountIn) return notes.note(\"the quote prices another amount\", \"price_check_failed\");\n const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);\n if (min <= 0n || min > out) return notes.note(\"invalid quote amounts\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && min < BigInt(params.minAmountOut)) return notes.note(\"the quote's minimum is under the floor\", \"price_check_failed\");\n // The minimum is the expected output less the requested slippage — the provider's default when the request names\n // none — never more slippage than that: without a default, a backend's minimum of one unit would pass.\n const bps = params.slippageBps ?? KYBER_DEFAULT_SLIPPAGE_BPS;\n if (!Number.isInteger(bps) || bps < 0 || bps >= 10_000) return notes.note(\"invalid slippage\", \"policy_refused\");\n if (min < kyberMinimum(out, bps)) {\n return notes.note(\"the quote's minimum allows more slippage than requested\", \"price_check_failed\");\n }\n const tx = quote.txRequest;\n if (!tx) return params.dry === false ? notes.note(\"the quote carries no router transaction\", \"policy_refused\") : null;\n if (!tx.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n if (tx.approvalAddress !== undefined && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note(\"the quote asks to approve another spender\", \"vault_mismatch\");\n checkKyberTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n minAmountOut: min,\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e);\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\nfunction routerFor(chain: string): readonly string[] {\n return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];\n}\n\n/**\n * The provider's `exactAllowanceOnly` (protocol-swap2-core): true on the chains whose router is the `generic` build —\n * `swapGeneric` behind an owner-managed executor whitelist, so the router's owner (a single key on all but Linea) could\n * make it spend an allowance left on it. The engine then approves exactly the input and revokes it when the swap does\n * not spend it, whatever the app's `allowanceReuse` / `revokeUnspentApproval` say. False on the `lite` chains; true\n * for a chain this module does not know (fail closed).\n */\nexport function kyberExactAllowanceOnly(chain: string): boolean {\n return kyberChain(chainIdOf(chain))?.build !== \"lite\";\n}\n\n/**\n * The router a KyberSwap swap calls and approves, and {@link kyberVerifyQuote}: the app's side of\n * `remoteProvider({name: \"kyberswap\", baseUrl, ...kyberPins})`, so a backend's quote is checked against the pinned\n * router and the app's own request, never against itself.\n */\nexport const kyberPins: RemotePins = Object.freeze({\n callTargets: routerFor,\n spenders: routerFor,\n exactAllowanceOnly: kyberExactAllowanceOnly,\n // As the provider: the engine dry-runs the call from the account and sends it with a limit built on that estimate\n // (the build's gas, `venueGas`, as a floor), never a gas limit the backend quoted.\n ownGasEstim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YBER_ROUTER_V2,
3
3
  KYBER_SWAP_SELECTOR,
4
4
  kyberChain
5
- } from "./chunk-D4UIDHM2.js";
5
+ } from "./chunk-CFL4E4AW.js";
6
6
 
7
7
  // src/activity.ts
8
8
  import { chainLabel, describeSwapLike, matchesCall } from "@anywalletkit/protocol-swap2-core/activity";
@@ -18,4 +18,4 @@ export {
18
18
  KYBERSWAP_MODULE,
19
19
  describeKyberActivity
20
20
  };
21
- //# sourceMappingURL=chunk-HHZEL5IJ.js.map
21
+ //# sourceMappingURL=chunk-DP4WDX4C.js.map
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  describeKyberActivity
3
- } from "./chunk-HHZEL5IJ.js";
3
+ } from "./chunk-DP4WDX4C.js";
4
4
  import {
5
+ KYBER_DEFAULT_SLIPPAGE_BPS,
5
6
  KYBER_LIMIT_ORDER_SOURCES,
6
7
  KYBER_NATIVE,
7
8
  KYBER_RFQ_SOURCES,
@@ -15,18 +16,19 @@ import {
15
16
  kyberMinimum,
16
17
  kyberNativeSwaps,
17
18
  kyberSourceKind
18
- } from "./chunk-D4UIDHM2.js";
19
+ } from "./chunk-CFL4E4AW.js";
19
20
 
20
21
  // src/provider.ts
21
22
  import { decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi } from "viem";
22
23
  import { evmRef, isEvm, timeoutSignal, sourceAssetOf } from "@anywalletkit/protocol-swap2-core/util";
24
+ import { validVenueGas } from "@anywalletkit/protocol-swap2-core/validate";
23
25
  import { httpRefusal, refusal, refusalOf, withReason } from "@anywalletkit/protocol-swap2-core/errors";
24
26
  import { ccAssetByToken } from "@anywalletkit/swap2-assets";
25
27
  import { WRAPPED_NATIVE } from "@anywalletkit/protocol-swap2-wrap/provider";
26
28
  var ZERO = "0x0000000000000000000000000000000000000000";
27
29
  var PUBLIC_BASE_URL = "https://aggregator-api.kyberswap.com";
28
30
  var GATEWAY_BASE_URL = "https://api.kyberswap.com/swap";
29
- var DEFAULT_SLIPPAGE_BPS = 50;
31
+ var DEFAULT_SLIPPAGE_BPS = KYBER_DEFAULT_SLIPPAGE_BPS;
30
32
  var DEFAULT_TTL_MS = 3e4;
31
33
  var DRY_CACHE_MS = 5e3;
32
34
  var BUILD_DEADLINE_S = 20 * 60;
@@ -61,6 +63,9 @@ function kyberGasEstimate(routeGas) {
61
63
  const gas = uint(routeGas);
62
64
  return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
63
65
  }
66
+ function kyberBuildGas(gas) {
67
+ return validVenueGas(gas) ? gas : void 0;
68
+ }
64
69
  var ERC20_READS = parseAbi(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
65
70
  function revertData(e) {
66
71
  const err = e;
@@ -255,7 +260,8 @@ function kyberswapProvider(config = {}) {
255
260
  name: "kyberswap",
256
261
  describeActivity: describeKyberActivity,
257
262
  supportsSameChain: true,
258
- // The account's own estimate of the exact call, never the API's gas model.
263
+ // The account's own estimate of the exact call, dry-run before broadcast: the limit is built on it (× 1.3 + 100 000),
264
+ // with the build's gas as a floor (`venueGas`), never the API's figure alone.
259
265
  ownGasEstimate: true,
260
266
  // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
261
267
  exactAllowanceOnly: kyberExactAllowanceOnly,
@@ -383,6 +389,8 @@ function kyberswapProvider(config = {}) {
383
389
  if (builtOut < destAmount) destAmount = builtOut;
384
390
  }
385
391
  if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse("Kyber router V3 not supported yet", "policy_refused");
392
+ const buildGas = kyberBuildGas(b.gas);
393
+ const shownGas = base.gasEstimate === void 0 && buildGas !== void 0 ? kyberGasEstimate(buildGas) : void 0;
386
394
  const value = uint(b.transactionValue ?? "0");
387
395
  if (value === null || typeof b.data !== "string") return refuse("malformed build response", "upstream_unavailable");
388
396
  const tx = { to: typeof b.routerAddress === "string" ? b.routerAddress : "", value, data: b.data };
@@ -415,6 +423,7 @@ function kyberswapProvider(config = {}) {
415
423
  }
416
424
  return {
417
425
  ...base,
426
+ ...shownGas !== void 0 ? { gasEstimate: shownGas, gasEstimateSource: "venue" } : {},
418
427
  destAmount: destAmount.toString(),
419
428
  minDestAmount: decoded.minReturnAmount.toString(),
420
429
  txRequest: {
@@ -422,6 +431,7 @@ function kyberswapProvider(config = {}) {
422
431
  data: tx.data,
423
432
  value: value.toString(),
424
433
  chainId,
434
+ ...buildGas !== void 0 ? { venueGas: buildGas } : {},
425
435
  ...tokenIn === ZERO ? {} : { approvalAddress: KYBER_ROUTER_V2 }
426
436
  },
427
437
  providerData: { ...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated }
@@ -450,7 +460,7 @@ function kyberswapProvider(config = {}) {
450
460
  async buildDeposit(quote) {
451
461
  const tx = quote.txRequest;
452
462
  if (!tx?.to || !tx.data) throw refusal("policy_refused", "swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)");
453
- return { chain: "", to: tx.to, value: tx.value ?? "0", data: tx.data, ...tx.chainId !== void 0 ? { chainId: tx.chainId } : {}, ...tx.approvalAddress ? { approvalAddress: tx.approvalAddress } : {} };
463
+ 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 } : {} };
454
464
  },
455
465
  async trackIntent(ref) {
456
466
  if (!ref.sourceTxHash) return { state: "pending" };
@@ -474,4 +484,4 @@ export {
474
484
  kyberValueLossBps,
475
485
  kyberswapProvider
476
486
  };
477
- //# sourceMappingURL=chunk-NFMHUXU6.js.map
487
+ //# sourceMappingURL=chunk-INSCVUFN.js.map