@anywalletkit/protocol-swap2-kyberswap 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.ts","../src/activity.ts","../src/router.ts"],"sourcesContent":["import {decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {httpRefusal, refusal, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {WRAPPED_NATIVE} from \"@anywalletkit/protocol-swap2-wrap/provider\";\nimport {describeKyberActivity} from \"./activity.js\";\nimport {KYBER_NATIVE, KYBER_ROUTER_ABI, KYBER_ROUTER_V2, KYBER_ROUTER_V3, checkKyberTransaction, kyberApiSlippage, kyberChain, kyberMinimum, kyberNativeSwaps} from \"./router.js\";\n\n/**\n * KyberSwap Aggregator (docs.kyberswap.com) as a same-chain swap2 provider: exact-input swaps on the chains in\n * `KYBER_CHAINS`, routed by KyberSwap and settled through MetaAggregationRouterV2.\n *\n * A dry quote is `GET /routes` only. An execution quote (the engine's, with `dry: false`) also calls\n * `POST /route/build` and returns the encoded transaction, checked field by field against the request\n * (`checkKyberTransaction`): the build endpoint encodes whatever route summary it is sent, fee entries included, so\n * nothing in its answer is taken on trust. Before the transaction is signed it is simulated from the account at the\n * latest block; with no RPC answering, the swap is refused.\n *\n * Keyless by default (the public API, 3 requests per second per IP). With `apiKey`, requests go to KyberSwap's API\n * gateway instead. No integrator fee is ever charged; KyberSwap keeps any output above the quote (positive slippage).\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst PUBLIC_BASE_URL = \"https://aggregator-api.kyberswap.com\";\nconst GATEWAY_BASE_URL = \"https://api.kyberswap.com/swap\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** How long a quote stays executable for the engine: the user's review fits, an approval mined meanwhile gets one re-quote. */\nconst DEFAULT_TTL_MS = 30_000;\n/** A dry route is reused this long for the same request (KyberSwap asks not to cache routes for more than 5–10 s). */\nconst DRY_CACHE_MS = 5_000;\n/** The executor's own deadline for a built swap (the build endpoint's default). */\nconst BUILD_DEADLINE_S = 20 * 60;\n\n/**\n * KyberSwap's error codes (docs.kyberswap.com, aggregator API errors) → refusal reasons. 4222: the route quoted\n * under KyberSwap's own estimate; 4227: its gas estimation failed.\n */\nconst ERROR_REASONS: Readonly<Record<number, Swap2RefusalReason>> = {\n 4000: \"policy_refused\", 4001: \"policy_refused\", 4002: \"policy_refused\", 4005: \"policy_refused\", 4007: \"policy_refused\", 40017: \"policy_refused\",\n 4008: \"no_route\", 40011: \"no_route\",\n 4009: \"insufficient_liquidity\", 4010: \"insufficient_liquidity\",\n 4011: \"unsupported_pair\", 4221: \"unsupported_pair\",\n 4222: \"price_check_failed\",\n 4227: \"simulation_failed\",\n};\nconst errorReason = (code: unknown): Swap2RefusalReason | undefined =>\n typeof code === \"number\" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : undefined;\n\nexport interface KyberswapProviderConfig {\n enabled?: boolean;\n /** `x-client-id` and the build's `source` (written on-chain in the swap's `clientData`). Default \"anywalletkit\". */\n clientId?: string;\n /** KyberSwap API-gateway key (`X-Api-Key`); keep it on a server. Without it the keyless public API is used. */\n apiKey?: string;\n /** Override the API base (`{baseUrl}/{chain}/api/v1/...`). */\n baseUrl?: string;\n /** JSON-RPC endpoints per chain id: required for execution (pre-broadcast simulation) and receipts. */\n rpcUrls?: Readonly<Record<number, readonly string[]>>;\n /** Chains to quote on (default: every chain in `KYBER_CHAINS`). */\n enabledChains?: readonly number[];\n defaultSlippageBps?: number;\n quoteTtlMs?: number;\n timeoutMs?: number;\n /** Leave RFQ / private-market-maker sources out of routes (short-lived quotes; default true). */\n excludeRfqSources?: boolean;\n /** KyberSwap source ids to leave out of routes. */\n excludedSources?: readonly string[];\n}\n\ninterface RouteSummary {\n tokenIn?: string;\n amountIn?: string;\n tokenOut?: string;\n amountOut?: string;\n amountInUsd?: string;\n amountOutUsd?: string;\n gas?: string;\n extraFee?: {feeAmount?: string; feeReceiver?: string; chargeFeeBy?: string; isInBps?: boolean};\n route?: {pool?: string; exchange?: string}[][];\n routeID?: string;\n [k: string]: unknown;\n}\n\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^\\d{1,78}$/.test(v) ? BigInt(v) : typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null);\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: unknown, b: string): boolean => isAddr(a) && a.toLowerCase() === b.toLowerCase();\nconst sameText = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^\\d{1,80}$/.test(a) && /^\\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);\nconst apiToken = (t: string): string => (t === ZERO ? KYBER_NATIVE : t);\n/** An API text as it may appear in a refusal: one line, at most 120 characters. */\nconst short = (s: unknown): string => String(s ?? \"\").replace(/\\s+/g, \" \").slice(0, 120);\n\nconst ERC20_READS = parseAbi([\"function balanceOf(address) view returns (uint256)\", \"function allowance(address, address) view returns (uint256)\", \"function approve(address, uint256) returns (bool)\"]);\n\n/** The revert data an RPC error carries, at most 4 KB of it. */\nfunction revertData(e: unknown): Hex | null {\n const err = e as {data?: unknown; message?: unknown};\n const nested = err.data && typeof err.data === \"object\" ? (err.data as {data?: unknown}).data : undefined;\n for (const v of [err.data, nested]) if (typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v as Hex;\n return null;\n}\n/**\n * KyberSwap's own USD value of the output against the input, as basis points lost (pool impact and pool fees together).\n * Information for the user's \"be careful\" warning, never a refusal. null when KyberSwap does not price either side\n * (\"0\" means unpriced, not worthless) or the numbers are not plain decimals.\n */\nexport function kyberValueLossBps(amountInUsd: unknown, amountOutUsd: unknown): number | null {\n const num = (v: unknown) => (typeof v === \"string\" && /^\\d{1,15}(\\.\\d{1,30})?$/.test(v) ? Number(v) : null);\n const vin = num(amountInUsd), vout = num(amountOutUsd);\n if (vin === null || vout === null || vin <= 0 || vout <= 0) return null;\n return Math.min(10_000, Math.max(0, Math.round(((vin - vout) / vin) * 10_000)));\n}\n\n/** `Error(string)` from revert data, if that is what it is. */\nfunction revertString(e: unknown): string | null {\n const data = revertData(e);\n if (data) {\n try {\n // viem knows Error(string) and Panic(uint256) without an ABI.\n const r = decodeErrorResult({abi: [], data});\n if (r.errorName === \"Error\" && typeof r.args?.[0] === \"string\") return r.args[0].slice(0, 200);\n } catch {\n // not a plain revert string\n }\n }\n const m = e instanceof Error ? /execution reverted:?\\s*([^\\n]{1,160})/.exec(e.message) : null;\n return m ? m[1]! : null;\n}\n\nexport function kyberswapProvider(config: KyberswapProviderConfig = {}): CrossChainProvider {\n const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\\/+$/, \"\");\n const clientId = config.clientId ?? \"anywalletkit\";\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? 10_000;\n const enabledChains = config.enabledChains ? new Set(config.enabledChains) : null;\n // KyberSwap asked (2026-11-25): with a key, send X-Api-Key only, without x-client-id.\n // The build's `source` still carries the client id on-chain.\n const headers: Record<string, string> = config.apiKey ? {\"x-api-key\": config.apiKey} : {\"x-client-id\": clientId};\n const dryCache = new Map<string, {at: number; value: Promise<RoutesResult>}>();\n\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return kyberChain(id) && (!enabledChains || enabledChains.has(id)) ? id : null;\n };\n\n async function rpc(chainId: number, method: string, params: unknown[]): Promise<unknown> {\n let lastErr: unknown;\n for (const url of config.rpcUrls?.[chainId] ?? []) {\n try {\n const res = await fetch(url, {method: \"POST\", headers: {\"content-type\": \"application/json\"}, body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}), signal: timeoutSignal(12_000)});\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status}`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n const body = (await res.json()) as {result?: unknown; error?: {message?: string; data?: unknown}};\n if (body.error) throw Object.assign(new Error(body.error.message ?? \"rpc error\"), {rpc: true, data: body.error.data});\n return body.result ?? null;\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw e;\n lastErr = e;\n }\n }\n throw withReason(new Error(`kyberswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr ?? \"none configured\")})`), refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n type ApiResult = {ok: true; data: Record<string, unknown>} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function api(url: string, init: RequestInit, signal?: AbortSignal): Promise<ApiResult> {\n let res: Response;\n try {\n res = await fetch(url, {...init, headers: {...headers, ...(init.body ? {\"content-type\": \"application/json\"} : {})}, signal: signal ?? timeoutSignal(timeoutMs)});\n } catch (e) {\n return {ok: false, why: `API unreachable (${e instanceof Error ? e.name : \"error\"})`, ...(signal?.aborted ? {} : {info: \"upstream_unavailable\" as const})};\n }\n type Body = {code?: unknown; message?: unknown; data?: unknown};\n let body: Body | null;\n try {\n const parsed: unknown = await res.json();\n body = parsed && typeof parsed === \"object\" ? (parsed as Body) : null;\n } catch {\n body = null;\n }\n if (res.status === 429) return {ok: false, why: \"rate limited (HTTP 429)\", info: httpRefusal(429, res.headers?.get?.(\"retry-after\")) ?? \"rate_limited\"};\n if (res.status === 401 || res.status === 403) return {ok: false, why: `API key rejected (HTTP ${res.status})`, info: httpRefusal(res.status) ?? \"policy_refused\"};\n if (res.status === 404 && !body?.code) return {ok: false, why: \"KyberSwap does not serve this chain (HTTP 404)\", info: \"unsupported_pair\"};\n if (!res.ok || body?.code !== 0) {\n const code = typeof body?.code === \"number\" ? body.code : undefined;\n const reason = errorReason(code) ?? (res.status >= 500 ? \"upstream_unavailable\" : undefined);\n return {ok: false, why: `${code !== undefined ? `error ${code}` : `HTTP ${res.status}`}${body?.message ? `: ${short(body.message)}` : \"\"}`, ...(reason ? {info: reason} : {})};\n }\n if (!body?.data || typeof body.data !== \"object\") return {ok: false, why: \"malformed API response\", info: \"upstream_unavailable\"};\n return {ok: true, data: body.data as Record<string, unknown>};\n }\n\n type RoutesResult = {ok: true; summary: RouteSummary; amountOut: bigint; sources: string[]} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function routes(chainId: number, tokenIn: string, tokenOut: string, amountIn: bigint, signal?: AbortSignal): Promise<RoutesResult> {\n const q = new URLSearchParams({tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: \"true\"});\n if (config.excludeRfqSources ?? true) q.set(\"excludeRFQSources\", \"true\");\n if (config.excludedSources?.length) q.set(\"excludedSources\", config.excludedSources.join(\",\"));\n const r = await api(`${baseUrl}/${kyberChain(chainId)!.slug}/api/v1/routes?${q}`, {method: \"GET\"}, signal);\n if (!r.ok) return r;\n const summary = r.data.routeSummary as RouteSummary | undefined;\n const router = r.data.routerAddress;\n if (!summary || typeof summary !== \"object\") return {ok: false, why: \"malformed API response (no route)\", info: \"upstream_unavailable\"};\n if (same(router, KYBER_ROUTER_V3)) return {ok: false, why: \"Kyber router V3 not supported yet\", info: \"policy_refused\"};\n if (!same(router, KYBER_ROUTER_V2)) return {ok: false, why: \"the route settles through another router than the pinned one\", info: \"vault_mismatch\"};\n if (!same(summary.tokenIn, apiToken(tokenIn)) || !same(summary.tokenOut, apiToken(tokenOut))) return {ok: false, why: \"the route swaps other tokens than requested\", info: \"policy_refused\"};\n if (uint(summary.amountIn) !== amountIn) return {ok: false, why: \"the route prices another amount\", info: \"price_check_failed\"};\n const fee = summary.extraFee;\n // No fee is ever asked for: the API answers with empty fields (\"\" amount, \"\" receiver); anything else is refused.\n if (fee !== undefined && fee !== null) {\n const amount = fee.feeAmount === \"\" || fee.feeAmount === undefined ? 0n : uint(fee.feeAmount);\n if (typeof fee !== \"object\" || amount !== 0n || (fee.feeReceiver !== undefined && fee.feeReceiver !== \"\")) return {ok: false, why: \"the route carries an integrator fee\", info: \"policy_refused\"};\n }\n const amountOut = uint(summary.amountOut);\n if (amountOut === null || amountOut <= 0n) return {ok: false, why: \"the route pays nothing\", info: \"no_route\"};\n const sources = [...new Set((summary.route ?? []).flat().map((h) => h?.exchange).filter((x): x is string => typeof x === \"string\"))].slice(0, 6).map((s) => s.slice(0, 40));\n return {ok: true, summary, amountOut, sources};\n }\n\n /** Why the swap reverts for `sender` now: the price (the router's minimum check), the wallet's input, or the revert as it is. */\n async function revertReason(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>, e: unknown): Promise<Error> {\n const text = revertString(e);\n if (text && /return amount is not enough|min return/i.test(text)) {\n return refusal(\"price_check_failed\", \"kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.\");\n }\n const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);\n if (lack) return refusal(\"simulation_failed\", lack);\n return refusal(\"simulation_failed\", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : \"revert\"))}). Nothing was sent; refresh the quote.`);\n }\n\n async function inputShortfall(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>): Promise<string | null> {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: quoted.data as Hex});\n const desc = (call.args[0] as {desc: {srcToken: string; amount: bigint}}).desc;\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n if (same(desc.srcToken, KYBER_NATIVE)) {\n const balance = word(await rpc(chainId, \"eth_getBalance\", [sender, \"latest\"]));\n return balance !== null && balance < desc.amount ? `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.` : null;\n }\n const read = (data: Hex) => rpc(chainId, \"eth_call\", [{to: desc.srcToken, data}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance != null && balance < desc.amount) return `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.`;\n if (allowance != null && allowance < desc.amount) return \"kyberswap: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.\";\n return null;\n }\n\n /**\n * A token sale is checked before the user pays for an approval: with the allowance already in place the exact call\n * runs against the latest block; without it the approval and the swap run as one simulated block (eth_simulateV1),\n * so a route that reverts never asks for an approval. A wallet without the input, or an RPC that cannot simulate a\n * block, skips the check (`null` with the reason in `skipped`) — preflightDeposit still simulates before signing.\n */\n async function tokenSwapCheck(chainId: number, sender: string, token: string, amount: bigint, data: Hex): Promise<{refusal: ReturnType<typeof refuseRevert> | null; simulated: string}> {\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n const read = (call: Hex) => rpc(chainId, \"eth_call\", [{to: token, data: call}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance == null || allowance == null) return {refusal: null, simulated: \"none\"};\n if (balance < amount) return {refusal: null, simulated: \"none\"};\n if (allowance >= amount) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}, \"latest\"]);\n return {refusal: null, simulated: \"swap\"};\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) return {refusal: refuseRevert(revertString(e)), simulated: \"swap\"};\n throw e;\n }\n }\n const approve = (n: bigint) => ({from: sender, to: token, data: encodeFunctionData({abi: ERC20_READS, functionName: \"approve\", args: [KYBER_ROUTER_V2, n]})});\n // A token that refuses to change a non-zero allowance (USDT) is reset first, as the wallet's own approval does.\n const calls = [...(allowance > 0n ? [approve(0n)] : []), approve(amount), {from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}];\n let result: unknown;\n try {\n result = await rpc(chainId, \"eth_simulateV1\", [{blockStateCalls: [{calls}], validation: false}, \"latest\"]);\n } catch {\n return {refusal: null, simulated: \"none\"};\n }\n type Call = {status?: unknown; returnData?: unknown; error?: {message?: unknown; data?: unknown}};\n const out = (Array.isArray(result) ? (result[0] as {calls?: Call[]} | undefined)?.calls : undefined) ?? [];\n if (out.length !== calls.length || out.slice(0, -1).some((c) => c.status !== \"0x1\")) return {refusal: null, simulated: \"none\"};\n const swap = out[out.length - 1]!;\n if (swap.status === \"0x1\") return {refusal: null, simulated: \"approve+swap\"};\n const err = {data: swap.error?.data ?? swap.returnData, message: typeof swap.error?.message === \"string\" ? swap.error.message : \"\"};\n return {refusal: refuseRevert(revertString(Object.assign(new Error(err.message), {data: err.data}))), simulated: \"approve+swap\"};\n }\n\n function refuseRevert(why: string | null): {why: string; reason: Swap2RefusalReason} {\n return {\n why: `the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`,\n reason: why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\",\n };\n }\n\n return {\n name: \"kyberswap\",\n describeActivity: describeKyberActivity,\n supportsSameChain: true,\n // The account's own estimate of the exact call, never the API's gas model.\n ownGasEstimate: true,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => {\n if (from.chain !== to.chain) return false;\n const id = chainIdOf(from.chain);\n if (id === null) return false;\n // Native ↔ wrapped is a wrap (the Wrap provider's), which KyberSwap does not route: no request is spent on it.\n const wrapped = Object.prototype.hasOwnProperty.call(WRAPPED_NATIVE, id) ? WRAPPED_NATIVE[id]!.address : null;\n const isNative = (t: string) => /^0x0+$/.test(t) || same(t, KYBER_NATIVE) || t === ccAssetByToken(from.chain, ZERO)?.symbol;\n const isWrapped = (t: string) => !!wrapped && (same(t, wrapped) || t === WRAPPED_NATIVE[id]!.symbol);\n return !((isNative(from.token) && isWrapped(to.token)) || (isWrapped(from.token) && isNative(to.token)));\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`kyberswap: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`KyberSwap is not enabled for ${params.sourceChain}`, \"unsupported_pair\");\n const chain = kyberChain(chainId)!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tokenIn = src.contract ? getAddress(src.contract) : ZERO;\n const nativeOut = /^0x0+$/.test(params.destToken) || same(params.destToken, KYBER_NATIVE);\n if (!nativeOut && !isAddr(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n const tokenOut = nativeOut ? ZERO : getAddress(params.destToken);\n // Refused before any request: a useless call spends the shared keyless quota.\n if (tokenIn === tokenOut) return refuse(\"same token in and out\", \"unsupported_pair\");\n if ((tokenIn === ZERO || tokenOut === ZERO) && !kyberNativeSwaps(chainId)) return refuse(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps <= 0 || bps >= 2_000) return refuse(\"invalid slippage (KyberSwap accepts under 20%)\", \"price_check_failed\");\n let floor = 0n;\n if (params.minAmountOut !== undefined) {\n const f = uint(params.minAmountOut);\n if (f === null) return refuse(\"minimum output is not an integer\");\n floor = f;\n }\n const dry = params.dry !== false;\n if (!dry && !isAddr(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n if (!dry && !config.rpcUrls?.[chainId]?.length) return refuse(`no RPC configured for ${chain.name}: a KyberSwap swap is simulated before it is signed`, \"upstream_unavailable\");\n\n // Dry quotes for the same request share one route for a few seconds; an execution quote always asks afresh.\n let r: RoutesResult;\n if (dry) {\n const key = `${chainId}|${tokenIn}|${tokenOut}|${amountIn}`;\n const hit = dryCache.get(key);\n if (hit && Date.now() - hit.at < DRY_CACHE_MS) r = await hit.value;\n else {\n const value = routes(chainId, tokenIn, tokenOut, amountIn, signal);\n dryCache.set(key, {at: Date.now(), value});\n if (dryCache.size > 64) for (const [k, v] of dryCache) if (Date.now() - v.at >= DRY_CACHE_MS) dryCache.delete(k);\n r = await value;\n if (!r.ok) dryCache.delete(key);\n }\n } else r = await routes(chainId, tokenIn, tokenOut, amountIn, signal);\n if (!r.ok) return refuse(r.why, r.info);\n // KyberSwap's minimum lands one unit under the plain floor; asking for a hair less slippage keeps it at or\n // above the engine's floor for the user's slippage (a tiny output needs more than 1 bps for that unit).\n const apiBps = kyberApiSlippage(r.amountOut, bps);\n if (apiBps === null) return refuse(\"the output is too small to carry a minimum\", \"amount_too_small\");\n const minOut = kyberMinimum(r.amountOut, apiBps);\n if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, \"price_check_failed\");\n\n const base = {\n provider: \"kyberswap\",\n intentId: `kyberswap:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n sourceAmount: amountIn.toString(),\n // KyberSwap's amountOut is the route's ceiling, not an average: the executed output came 1.5–7.4 bps under it.\n destAmount: r.amountOut.toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n etaSeconds: 15,\n reliability: 0.95,\n validUntilMs: Date.now() + ttl,\n } satisfies Partial<Quote>;\n const providerData: Record<string, string> = {\n amountOut: r.amountOut.toString(),\n minOut: minOut.toString(),\n apiSlippageBps: String(apiBps),\n ...(typeof r.summary.routeID === \"string\" ? {routeId: r.summary.routeID.slice(0, 80)} : {}),\n ...(r.sources.length ? {sources: r.sources.join(\",\")} : {}),\n };\n // The router's quoteValues reads priceImpactBps into the user's \"be careful\" warning (Unichain USDC → JUP: −78 %).\n const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);\n if (lossBps !== null) providerData.priceImpactBps = String(lossBps);\n if (dry) {\n // A token sale approves the router first; the auction's gas estimate reads the spender from here.\n return {...base, providerData: tokenIn === ZERO ? providerData : {...providerData, approvalAddress: KYBER_ROUTER_V2}};\n }\n\n const receiver = getAddress(params.destAddress);\n const signer = isAddr(params.sender) ? params.sender : isAddr(params.refundAddress) ? params.refundAddress : params.destAddress;\n const sender = getAddress(signer);\n const built = await api(`${baseUrl}/${chain.slug}/api/v1/route/build`, {\n method: \"POST\",\n body: JSON.stringify({\n routeSummary: r.summary,\n sender,\n recipient: receiver,\n slippageTolerance: apiBps,\n deadline: Math.floor(Date.now() / 1000) + BUILD_DEADLINE_S,\n source: clientId,\n }),\n }, signal);\n if (!built.ok) return refuse(`build: ${built.why}`, built.info);\n const b = built.data;\n if (uint(b.amountIn) !== amountIn) return refuse(\"the build spends another amount\", \"price_check_failed\");\n if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse(\"Kyber router V3 not supported yet\", \"policy_refused\");\n const value = uint(b.transactionValue ?? \"0\");\n if (value === null || typeof b.data !== \"string\") return refuse(\"malformed build response\", \"upstream_unavailable\");\n const tx = {to: typeof b.routerAddress === \"string\" ? b.routerAddress : \"\", value, data: b.data};\n let decoded;\n try {\n decoded = checkKyberTransaction(tx, {chainId, tokenIn, tokenOut, amountIn, receiver, minAmountOut: minOut > floor ? minOut : floor});\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e));\n }\n // Native input needs no allowance: the exact call runs against the latest block now, so a route that would revert\n // never reaches the user. Token input is checked the same way before any approval (tokenSwapCheck).\n let simulated = \"swap\";\n if (tokenIn !== ZERO) {\n try {\n const check = await tokenSwapCheck(chainId, sender, tokenIn, amountIn, tx.data as Hex);\n if (check.refusal) return refuse(check.refusal.why, check.refusal.reason);\n simulated = check.simulated;\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n if (tokenIn === ZERO) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data: tx.data, value: `0x${value.toString(16)}`}, \"latest\", {[sender]: {balance: `0x${(value + 10n ** 18n).toString(16)}`}}]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) {\n const why = revertString(e);\n return refuse(`the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`, why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\");\n }\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n return {\n ...base,\n minDestAmount: decoded.minReturnAmount.toString(),\n txRequest: {\n to: KYBER_ROUTER_V2,\n data: tx.data,\n value: value.toString(),\n chainId,\n ...(tokenIn === ZERO ? {} : {approvalAddress: KYBER_ROUTER_V2}),\n },\n providerData: {...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated},\n };\n },\n\n /**\n * Simulate the exact quoted transaction from the account at the latest block (approval in place) and refuse when\n * it would revert or when no RPC answers — the API is not trusted, so an unsimulated swap is not sent.\n * Only the quote's own transaction is simulated, never a caller's.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const sender = quote.providerData?.sender;\n const quoted = quote.txRequest;\n if (!kyberChain(chainId) || !isAddr(sender)) throw refusal(\"policy_refused\", \"kyberswap: the quote is not an execution quote. Nothing was sent; refresh the quote.\");\n if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data ?? \"\", quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\")) {\n throw refusal(\"policy_refused\", \"kyberswap: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? \"0\").toString(16)}`}, \"latest\"]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw await revertReason(chainId, sender, quoted, e);\n throw withReason(new Error(\"kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again.\"), refusalOf(e) ?? \"upstream_unavailable\");\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!kyberChain(chainId) || !config.rpcUrls?.[chainId]?.length) return {state: \"pending\"};\n try {\n const receipt = (await rpc(chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash])) as {status?: string} | null;\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\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/** 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 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 verifyQuote: kyberVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAwG;AACxG,IAAAC,eAA0D;AAC1D,IAAAC,iBAA0G;AAE1G,IAAA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,YAAK,EAAsB,IAAK,OAAM,MAAM,aAAa,SAAS,QAAQ,QAAQ,CAAC;AACnF,kBAAM,2BAAW,IAAI,MAAM,yFAAyF,OAAG,0BAAU,CAAC,KAAK,sBAAsB;AAAA,MAC/J;AAAA,IACF;AAAA,IAEA,MAAM,aAAa,OAAmC;AACpD,YAAM,KAAK,MAAM;AACjB,UAAI,CAAC,IAAI,MAAM,CAAC,GAAG,KAAM,WAAM,wBAAQ,kBAAkB,oFAAoF;AAC7I,aAAO,EAAC,OAAO,IAAI,IAAI,GAAG,IAAI,OAAO,GAAG,SAAS,KAAK,MAAM,GAAG,MAAM,GAAI,GAAG,YAAY,SAAY,EAAC,SAAS,GAAG,QAAO,IAAI,CAAC,GAAI,GAAI,GAAG,kBAAkB,EAAC,iBAAiB,GAAG,gBAAe,IAAI,CAAC,EAAE;AAAA,IACvM;AAAA,IAEA,MAAM,YAAY,KAAuC;AACvD,UAAI,CAAC,IAAI,aAAc,QAAO,EAAC,OAAO,UAAS;AAC/C,YAAM,UAAU,OAAO,IAAI,SAAS,MAAM,GAAG,EAAE,CAAC,CAAC;AACjD,UAAI,CAAC,WAAW,OAAO,KAAK,CAAC,OAAO,UAAU,OAAO,GAAG,OAAQ,QAAO,EAAC,OAAO,UAAS;AACxF,UAAI;AACF,cAAM,UAAW,MAAM,IAAI,SAAS,6BAA6B,CAAC,IAAI,YAAY,CAAC;AACnF,YAAI,CAAC,QAAS,QAAO,EAAC,OAAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;","names":["import_viem","import_util","import_errors","import_swap2_assets","import_util","refusal","ZERO","isAddr","same","chainIdOf","balance","value"]}
1
+ {"version":3,"sources":["../src/provider.ts","../src/activity.ts","../src/router.ts"],"sourcesContent":["import {decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {httpRefusal, refusal, refusalOf, withReason, type Swap2RefusalInfo, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {WRAPPED_NATIVE} from \"@anywalletkit/protocol-swap2-wrap/provider\";\nimport {describeKyberActivity} from \"./activity.js\";\nimport {KYBER_LIMIT_ORDER_SOURCES, KYBER_NATIVE, KYBER_RFQ_SOURCES, KYBER_ROUTER_ABI, KYBER_ROUTER_V2, KYBER_ROUTER_V3, checkKyberTransaction, kyberApiSlippage, kyberChain, kyberExactAllowanceOnly, kyberMinimum, kyberNativeSwaps, kyberSourceKind} from \"./router.js\";\n\n/**\n * KyberSwap Aggregator (docs.kyberswap.com) as a same-chain swap2 provider: exact-input swaps on the chains in\n * `KYBER_CHAINS`, routed by KyberSwap and settled through MetaAggregationRouterV2.\n *\n * A dry quote is `GET /routes` only. An execution quote (the engine's, with `dry: false`) also calls\n * `POST /route/build` and returns the encoded transaction, checked field by field against the request\n * (`checkKyberTransaction`): the build endpoint encodes whatever route summary it is sent, fee entries included, so\n * nothing in its answer is taken on trust. Before the transaction is signed it is simulated from the account at the\n * latest block; with no RPC answering, the swap is refused.\n *\n * Keyless by default (the public API, 3 requests per second per IP). With `apiKey`, requests go to KyberSwap's API\n * gateway instead. No integrator fee is ever charged; KyberSwap keeps any output above the quote (positive slippage).\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst PUBLIC_BASE_URL = \"https://aggregator-api.kyberswap.com\";\nconst GATEWAY_BASE_URL = \"https://api.kyberswap.com/swap\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** How long a quote stays executable for the engine: the user's review fits, an approval mined meanwhile gets one re-quote. */\nconst DEFAULT_TTL_MS = 30_000;\n/** A dry route is reused this long for the same request (KyberSwap asks not to cache routes for more than 5–10 s). */\nconst DRY_CACHE_MS = 5_000;\n/** The executor's own deadline for a built swap (the build endpoint's default). */\nconst BUILD_DEADLINE_S = 20 * 60;\n\n/**\n * KyberSwap's error codes (docs.kyberswap.com, aggregator API errors) → refusal reasons. 4222: the route quoted\n * under KyberSwap's own estimate; 4227: its gas estimation failed.\n */\nconst ERROR_REASONS: Readonly<Record<number, Swap2RefusalReason>> = {\n 4000: \"policy_refused\", 4001: \"policy_refused\", 4002: \"policy_refused\", 4005: \"policy_refused\", 4007: \"policy_refused\", 40017: \"policy_refused\",\n 4008: \"no_route\", 40011: \"no_route\",\n 4009: \"insufficient_liquidity\", 4010: \"insufficient_liquidity\",\n 4011: \"unsupported_pair\", 4221: \"unsupported_pair\",\n 4222: \"price_check_failed\",\n 4227: \"simulation_failed\",\n};\nconst errorReason = (code: unknown): Swap2RefusalReason | undefined =>\n typeof code === \"number\" && Object.prototype.hasOwnProperty.call(ERROR_REASONS, code) ? ERROR_REASONS[code] : undefined;\n\nexport interface KyberswapProviderConfig {\n enabled?: boolean;\n /** `x-client-id` and the build's `source` (written on-chain in the swap's `clientData`). Default \"anywalletkit\". */\n clientId?: string;\n /** KyberSwap API-gateway key (`X-Api-Key`); keep it on a server. Without it the keyless public API is used. */\n apiKey?: string;\n /** Override the API base (`{baseUrl}/{chain}/api/v1/...`). */\n baseUrl?: string;\n /** JSON-RPC endpoints per chain id: required for execution (pre-broadcast simulation) and receipts. */\n rpcUrls?: Readonly<Record<number, readonly string[]>>;\n /** Chains to quote on (default: every chain in `KYBER_CHAINS`). */\n enabledChains?: readonly number[];\n defaultSlippageBps?: number;\n quoteTtlMs?: number;\n timeoutMs?: number;\n /**\n * RFQ market makers (KyberSwap's \"RFQ sources\": `pmm-N`, Bebop, Native, Hashflow, …), whose firm quote is signed\n * when the route is built. Default \"exclude\". See the README (\"RFQ and limit orders\") for what including them costs.\n */\n rfq?: KyberSourceSetting;\n /** KyberSwap's own limit orders (`kyberswap-limit-order-v2`), filled from an off-chain order book. Default \"exclude\". */\n limitOrders?: KyberSourceSetting;\n /**\n * @deprecated Use `rfq` and `limitOrders`. `false` includes both (KyberSwap's `excludeRFQSources` leaves out RFQ\n * makers and limit orders together); each of `rfq` / `limitOrders` overrides it for its own sources.\n */\n excludeRfqSources?: boolean;\n /** KyberSwap source ids to leave out of routes. */\n excludedSources?: readonly string[];\n}\n\n/** Whether a kind of off-chain liquidity may be in a route. */\nexport type KyberSourceSetting = \"exclude\" | \"include\";\n\n/**\n * How long a quote whose route uses an RFQ maker stays executable, at most. The API states no expiry; measured\n * 2026-11-30 (README, \"RFQ and limit orders\"): one of seven RFQ routes built at the quote ran at 11 s and reverted at\n * 30 s. The module's `quoteTtlMs` still caps it.\n */\nexport const KYBER_RFQ_TTL_MS = 10_000;\n/**\n * The same for a route through a KyberSwap limit order: every limit-order route built at the quote still ran at 60 s\n * (the one followed further: at 91 s, reverting from 121 s). The module's `quoteTtlMs` (default 30 s) still caps it.\n */\nexport const KYBER_LIMIT_ORDER_TTL_MS = 30_000;\n\ninterface RouteSummary {\n tokenIn?: string;\n amountIn?: string;\n tokenOut?: string;\n amountOut?: string;\n amountInUsd?: string;\n amountOutUsd?: string;\n gas?: string;\n extraFee?: {feeAmount?: string; feeReceiver?: string; chargeFeeBy?: string; isInBps?: boolean};\n route?: {pool?: string; exchange?: string; poolType?: string}[][];\n routeID?: string;\n [k: string]: unknown;\n}\n\nconst uint = (v: unknown): bigint | null => (typeof v === \"string\" && /^\\d{1,78}$/.test(v) ? BigInt(v) : typeof v === \"number\" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : null);\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: unknown, b: string): boolean => isAddr(a) && a.toLowerCase() === b.toLowerCase();\nconst sameText = (a: string, b: string): boolean => a.length === b.length && a.toLowerCase() === b.toLowerCase();\nconst sameAmount = (a: string, b: string): boolean => /^\\d{1,80}$/.test(a) && /^\\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);\nconst apiToken = (t: string): string => (t === ZERO ? KYBER_NATIVE : t);\n/** \"rfq\" / \"limit-order\" / both, as a refusal names them. */\nconst offchainName = (offchain: string): string =>\n offchain.includes(\"rfq\") && offchain.includes(\"limit-order\") ? \"market maker's quote or limit order\" : offchain.includes(\"rfq\") ? \"market maker's quote\" : \"limit order\";\n/** An API text as it may appear in a refusal: one line, at most 120 characters. */\nconst short = (s: unknown): string => String(s ?? \"\").replace(/\\s+/g, \" \").slice(0, 120);\n\n/**\n * A quote's `gasEstimate`: KyberSwap's `routeSummary.gas` from `GET /routes` (asked with `gasInclude=true`) as canonical\n * digits, the same figure on a dry quote and on the execution quote built from that route. Undefined when the route\n * states none, zero, or a figure past the contract's ten digits: no figure is made up. See the README for how it\n * compares with the gas the built call used.\n */\nexport function kyberGasEstimate(routeGas: unknown): string | undefined {\n const gas = uint(routeGas);\n return gas !== null && gas > 0n && gas < 10_000_000_000n ? gas.toString() : undefined;\n}\n\nconst ERC20_READS = parseAbi([\"function balanceOf(address) view returns (uint256)\", \"function allowance(address, address) view returns (uint256)\", \"function approve(address, uint256) returns (bool)\"]);\n\n/** The revert data an RPC error carries, at most 4 KB of it. */\nfunction revertData(e: unknown): Hex | null {\n const err = e as {data?: unknown; message?: unknown};\n const nested = err.data && typeof err.data === \"object\" ? (err.data as {data?: unknown}).data : undefined;\n for (const v of [err.data, nested]) if (typeof v === \"string\" && /^0x(?:[0-9a-fA-F]{2}){4,4096}$/.test(v)) return v as Hex;\n return null;\n}\n/**\n * KyberSwap's own USD value of the output against the input, as basis points lost (pool impact and pool fees together).\n * Information for the user's \"be careful\" warning, never a refusal. null when KyberSwap does not price either side\n * (\"0\" means unpriced, not worthless) or the numbers are not plain decimals.\n */\nexport function kyberValueLossBps(amountInUsd: unknown, amountOutUsd: unknown): number | null {\n const num = (v: unknown) => (typeof v === \"string\" && /^\\d{1,15}(\\.\\d{1,30})?$/.test(v) ? Number(v) : null);\n const vin = num(amountInUsd), vout = num(amountOutUsd);\n if (vin === null || vout === null || vin <= 0 || vout <= 0) return null;\n return Math.min(10_000, Math.max(0, Math.round(((vin - vout) / vin) * 10_000)));\n}\n\n/** `Error(string)` from revert data, if that is what it is. */\nfunction revertString(e: unknown): string | null {\n const data = revertData(e);\n if (data) {\n try {\n // viem knows Error(string) and Panic(uint256) without an ABI.\n const r = decodeErrorResult({abi: [], data});\n if (r.errorName === \"Error\" && typeof r.args?.[0] === \"string\") return r.args[0].slice(0, 200);\n } catch {\n // not a plain revert string\n }\n }\n const m = e instanceof Error ? /execution reverted:?\\s*([^\\n]{1,160})/.exec(e.message) : null;\n return m ? m[1]! : null;\n}\n\nexport function kyberswapProvider(config: KyberswapProviderConfig = {}): CrossChainProvider {\n const legacy: KyberSourceSetting = config.excludeRfqSources === false ? \"include\" : \"exclude\";\n const setting = (v: unknown, name: string): KyberSourceSetting => {\n if (v === undefined) return legacy;\n if (v !== \"exclude\" && v !== \"include\") throw new TypeError(`kyberswap: ${name} must be \"exclude\" or \"include\"`);\n return v;\n };\n const rfqSetting = setting(config.rfq, \"rfq\");\n const limitOrderSetting = setting(config.limitOrders, \"limitOrders\");\n const baseUrl = (config.baseUrl ?? (config.apiKey ? GATEWAY_BASE_URL : PUBLIC_BASE_URL)).replace(/\\/+$/, \"\");\n const clientId = config.clientId ?? \"anywalletkit\";\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const timeoutMs = config.timeoutMs ?? 10_000;\n const enabledChains = config.enabledChains ? new Set(config.enabledChains) : null;\n // KyberSwap asked (2026-11-25): with a key, send X-Api-Key only, without x-client-id.\n // The build's `source` still carries the client id on-chain.\n const headers: Record<string, string> = config.apiKey ? {\"x-api-key\": config.apiKey} : {\"x-client-id\": clientId};\n const dryCache = new Map<string, {at: number; value: Promise<RoutesResult>}>();\n\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return kyberChain(id) && (!enabledChains || enabledChains.has(id)) ? id : null;\n };\n\n async function rpc(chainId: number, method: string, params: unknown[]): Promise<unknown> {\n let lastErr: unknown;\n for (const url of config.rpcUrls?.[chainId] ?? []) {\n try {\n const res = await fetch(url, {method: \"POST\", headers: {\"content-type\": \"application/json\"}, body: JSON.stringify({jsonrpc: \"2.0\", id: 1, method, params}), signal: timeoutSignal(12_000)});\n if (!res.ok) {\n const error = new Error(`HTTP ${res.status}`);\n const info = httpRefusal(res.status, res.headers?.get?.(\"retry-after\"));\n throw info ? withReason(error, info) : error;\n }\n const body = (await res.json()) as {result?: unknown; error?: {message?: string; data?: unknown}};\n if (body.error) throw Object.assign(new Error(body.error.message ?? \"rpc error\"), {rpc: true, data: body.error.data});\n return body.result ?? null;\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw e;\n lastErr = e;\n }\n }\n throw withReason(new Error(`kyberswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr ?? \"none configured\")})`), refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n type ApiResult = {ok: true; data: Record<string, unknown>} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function api(url: string, init: RequestInit, signal?: AbortSignal): Promise<ApiResult> {\n let res: Response;\n try {\n res = await fetch(url, {...init, headers: {...headers, ...(init.body ? {\"content-type\": \"application/json\"} : {})}, signal: signal ?? timeoutSignal(timeoutMs)});\n } catch (e) {\n return {ok: false, why: `API unreachable (${e instanceof Error ? e.name : \"error\"})`, ...(signal?.aborted ? {} : {info: \"upstream_unavailable\" as const})};\n }\n type Body = {code?: unknown; message?: unknown; data?: unknown};\n let body: Body | null;\n try {\n const parsed: unknown = await res.json();\n body = parsed && typeof parsed === \"object\" ? (parsed as Body) : null;\n } catch {\n body = null;\n }\n if (res.status === 429) return {ok: false, why: \"rate limited (HTTP 429)\", info: httpRefusal(429, res.headers?.get?.(\"retry-after\")) ?? \"rate_limited\"};\n if (res.status === 401 || res.status === 403) return {ok: false, why: `API key rejected (HTTP ${res.status})`, info: httpRefusal(res.status) ?? \"policy_refused\"};\n if (res.status === 404 && !body?.code) return {ok: false, why: \"KyberSwap does not serve this chain (HTTP 404)\", info: \"unsupported_pair\"};\n if (!res.ok || body?.code !== 0) {\n const code = typeof body?.code === \"number\" ? body.code : undefined;\n const reason = errorReason(code) ?? (res.status >= 500 ? \"upstream_unavailable\" : undefined);\n return {ok: false, why: `${code !== undefined ? `error ${code}` : `HTTP ${res.status}`}${body?.message ? `: ${short(body.message)}` : \"\"}`, ...(reason ? {info: reason} : {})};\n }\n if (!body?.data || typeof body.data !== \"object\") return {ok: false, why: \"malformed API response\", info: \"upstream_unavailable\"};\n return {ok: true, data: body.data as Record<string, unknown>};\n }\n\n /**\n * The source filters of every `GET /routes`, dry or for execution, so the route reviewed and the route built draw on\n * the same liquidity. Both excluded (the default): `excludeRFQSources=true`, as in 0.2.0. Limit orders without RFQ:\n * the chain's RFQ sources (`KYBER_RFQ_SOURCES`) in `excludedSources`; RFQ without limit orders: the limit-order source\n * there instead; both included: no filter.\n */\n function sourceFilters(q: URLSearchParams, chainId: number): void {\n const excluded: string[] = [];\n if (rfqSetting === \"exclude\" && limitOrderSetting === \"exclude\") q.set(\"excludeRFQSources\", \"true\");\n else if (rfqSetting === \"exclude\") excluded.push(...(Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId]! : []));\n else if (limitOrderSetting === \"exclude\") excluded.push(...KYBER_LIMIT_ORDER_SOURCES);\n for (const s of config.excludedSources ?? []) if (!excluded.includes(s)) excluded.push(s);\n if (excluded.length) q.set(\"excludedSources\", excluded.join(\",\"));\n }\n\n type Offchain = {rfq: boolean; limitOrder: boolean};\n type RoutesResult = {ok: true; summary: RouteSummary; amountOut: bigint; sources: string[]; offchain: Offchain} | {ok: false; why: string; info?: Swap2RefusalReason | Swap2RefusalInfo};\n async function routes(chainId: number, tokenIn: string, tokenOut: string, amountIn: bigint, signal?: AbortSignal): Promise<RoutesResult> {\n const q = new URLSearchParams({tokenIn: apiToken(tokenIn), tokenOut: apiToken(tokenOut), amountIn: amountIn.toString(), gasInclude: \"true\"});\n sourceFilters(q, chainId);\n const r = await api(`${baseUrl}/${kyberChain(chainId)!.slug}/api/v1/routes?${q}`, {method: \"GET\"}, signal);\n if (!r.ok) return r;\n const summary = r.data.routeSummary as RouteSummary | undefined;\n const router = r.data.routerAddress;\n if (!summary || typeof summary !== \"object\") return {ok: false, why: \"malformed API response (no route)\", info: \"upstream_unavailable\"};\n if (same(router, KYBER_ROUTER_V3)) return {ok: false, why: \"Kyber router V3 not supported yet\", info: \"policy_refused\"};\n if (!same(router, KYBER_ROUTER_V2)) return {ok: false, why: \"the route settles through another router than the pinned one\", info: \"vault_mismatch\"};\n if (!same(summary.tokenIn, apiToken(tokenIn)) || !same(summary.tokenOut, apiToken(tokenOut))) return {ok: false, why: \"the route swaps other tokens than requested\", info: \"policy_refused\"};\n if (uint(summary.amountIn) !== amountIn) return {ok: false, why: \"the route prices another amount\", info: \"price_check_failed\"};\n const fee = summary.extraFee;\n // No fee is ever asked for: the API answers with empty fields (\"\" amount, \"\" receiver); anything else is refused.\n if (fee !== undefined && fee !== null) {\n const amount = fee.feeAmount === \"\" || fee.feeAmount === undefined ? 0n : uint(fee.feeAmount);\n if (typeof fee !== \"object\" || amount !== 0n || (fee.feeReceiver !== undefined && fee.feeReceiver !== \"\")) return {ok: false, why: \"the route carries an integrator fee\", info: \"policy_refused\"};\n }\n const amountOut = uint(summary.amountOut);\n if (amountOut === null || amountOut <= 0n) return {ok: false, why: \"the route pays nothing\", info: \"no_route\"};\n const hops = Array.isArray(summary.route) ? summary.route.flat().filter((h) => h && typeof h === \"object\") : [];\n const sources = [...new Set(hops.map((h) => h.exchange).filter((x): x is string => typeof x === \"string\"))].slice(0, 6).map((s) => s.slice(0, 40));\n const kinds = new Set(hops.map((h) => kyberSourceKind(chainId, h.exchange, h.poolType)));\n return {ok: true, summary, amountOut, sources, offchain: {rfq: kinds.has(\"rfq\"), limitOrder: kinds.has(\"limit-order\")}};\n }\n\n /**\n * Why the swap reverts for `sender` now: the price (the router's minimum check), the wallet's input, an RFQ quote or\n * limit order in the route that no longer fills, or the revert as it is.\n */\n async function revertReason(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>, e: unknown, offchain?: string): Promise<Error> {\n const text = revertString(e);\n if (text && /return amount is not enough|min return/i.test(text)) {\n return refusal(\"price_check_failed\", \"kyberswap: the price moved past your minimum. Nothing was sent; refresh the quote.\");\n }\n const lack = await inputShortfall(chainId, sender, quoted).catch(() => null);\n if (lack) return refusal(\"simulation_failed\", lack);\n if (offchain) return refusal(\"quote_expired\", `kyberswap: the ${offchainName(offchain)} in this route no longer fills (expired or taken). Nothing was sent; refresh the quote.`);\n return refusal(\"simulation_failed\", `kyberswap: the swap would revert now (${short(text ?? (e instanceof Error ? e.message : \"revert\"))}). Nothing was sent; refresh the quote.`);\n }\n\n async function inputShortfall(chainId: number, sender: string, quoted: NonNullable<Quote[\"txRequest\"]>): Promise<string | null> {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: quoted.data as Hex});\n const desc = (call.args[0] as {desc: {srcToken: string; amount: bigint}}).desc;\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n if (same(desc.srcToken, KYBER_NATIVE)) {\n const balance = word(await rpc(chainId, \"eth_getBalance\", [sender, \"latest\"]));\n return balance !== null && balance < desc.amount ? `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.` : null;\n }\n const read = (data: Hex) => rpc(chainId, \"eth_call\", [{to: desc.srcToken, data}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance != null && balance < desc.amount) return `kyberswap: the wallet's balance is below the amount (${balance} < ${desc.amount}). Nothing was sent.`;\n if (allowance != null && allowance < desc.amount) return \"kyberswap: the token approval is not visible on-chain yet. Nothing was sent; try again in a moment.\";\n return null;\n }\n\n /**\n * A token sale is checked before the user pays for an approval: with the allowance already in place the exact call\n * runs against the latest block; without it the approval and the swap run as one simulated block (eth_simulateV1),\n * so a route that reverts never asks for an approval. A wallet without the input, or an RPC that cannot simulate a\n * block, skips the check (`null` with the reason in `skipped`) — preflightDeposit still simulates before signing.\n */\n async function tokenSwapCheck(chainId: number, sender: string, token: string, amount: bigint, data: Hex): Promise<{refusal: ReturnType<typeof refuseRevert> | null; simulated: string}> {\n const word = (v: unknown): bigint | null => (typeof v === \"string\" && /^0x[0-9a-fA-F]{1,64}$/.test(v) ? BigInt(v) : null);\n const read = (call: Hex) => rpc(chainId, \"eth_call\", [{to: token, data: call}, \"latest\"]);\n const [balance, allowance] = (await Promise.all([\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"balanceOf\", args: [sender as Hex]})),\n read(encodeFunctionData({abi: ERC20_READS, functionName: \"allowance\", args: [sender as Hex, KYBER_ROUTER_V2]})),\n ])).map(word);\n if (balance == null || allowance == null) return {refusal: null, simulated: \"none\"};\n if (balance < amount) return {refusal: null, simulated: \"none\"};\n if (allowance >= amount) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}, \"latest\"]);\n return {refusal: null, simulated: \"swap\"};\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) return {refusal: refuseRevert(revertString(e)), simulated: \"swap\"};\n throw e;\n }\n }\n const approve = (n: bigint) => ({from: sender, to: token, data: encodeFunctionData({abi: ERC20_READS, functionName: \"approve\", args: [KYBER_ROUTER_V2, n]})});\n // A token that refuses to change a non-zero allowance (USDT) is reset first, as the wallet's own approval does.\n const calls = [...(allowance > 0n ? [approve(0n)] : []), approve(amount), {from: sender, to: KYBER_ROUTER_V2, data, value: \"0x0\"}];\n let result: unknown;\n try {\n result = await rpc(chainId, \"eth_simulateV1\", [{blockStateCalls: [{calls}], validation: false}, \"latest\"]);\n } catch {\n return {refusal: null, simulated: \"none\"};\n }\n type Call = {status?: unknown; returnData?: unknown; error?: {message?: unknown; data?: unknown}};\n const out = (Array.isArray(result) ? (result[0] as {calls?: Call[]} | undefined)?.calls : undefined) ?? [];\n if (out.length !== calls.length || out.slice(0, -1).some((c) => c.status !== \"0x1\")) return {refusal: null, simulated: \"none\"};\n const swap = out[out.length - 1]!;\n if (swap.status === \"0x1\") return {refusal: null, simulated: \"approve+swap\"};\n const err = {data: swap.error?.data ?? swap.returnData, message: typeof swap.error?.message === \"string\" ? swap.error.message : \"\"};\n return {refusal: refuseRevert(revertString(Object.assign(new Error(err.message), {data: err.data}))), simulated: \"approve+swap\"};\n }\n\n function refuseRevert(why: string | null): {why: string; reason: Swap2RefusalReason} {\n return {\n why: `the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`,\n reason: why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\",\n };\n }\n\n return {\n name: \"kyberswap\",\n describeActivity: describeKyberActivity,\n supportsSameChain: true,\n // The account's own estimate of the exact call, never the API's gas model.\n ownGasEstimate: true,\n // On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.\n exactAllowanceOnly: kyberExactAllowanceOnly,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute: (from: Asset, to: Asset) => {\n if (from.chain !== to.chain) return false;\n const id = chainIdOf(from.chain);\n if (id === null) return false;\n // Native ↔ wrapped is a wrap (the Wrap provider's), which KyberSwap does not route: no request is spent on it.\n const wrapped = Object.prototype.hasOwnProperty.call(WRAPPED_NATIVE, id) ? WRAPPED_NATIVE[id]!.address : null;\n const isNative = (t: string) => /^0x0+$/.test(t) || same(t, KYBER_NATIVE) || t === ccAssetByToken(from.chain, ZERO)?.symbol;\n const isWrapped = (t: string) => !!wrapped && (same(t, wrapped) || t === WRAPPED_NATIVE[id]!.symbol);\n return !((isNative(from.token) && isWrapped(to.token)) || (isWrapped(from.token) && isNative(to.token)));\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`kyberswap: ${why}`, typeof info === \"string\" ? {reason: info} : info);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\", \"unsupported_pair\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\", \"unsupported_pair\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`KyberSwap is not enabled for ${params.sourceChain}`, \"unsupported_pair\");\n const chain = kyberChain(chainId)!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const tokenIn = src.contract ? getAddress(src.contract) : ZERO;\n const nativeOut = /^0x0+$/.test(params.destToken) || same(params.destToken, KYBER_NATIVE);\n if (!nativeOut && !isAddr(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n const tokenOut = nativeOut ? ZERO : getAddress(params.destToken);\n // Refused before any request: a useless call spends the shared keyless quota.\n if (tokenIn === tokenOut) return refuse(\"same token in and out\", \"unsupported_pair\");\n if ((tokenIn === ZERO || tokenOut === ZERO) && !kyberNativeSwaps(chainId)) return refuse(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n let amountIn: bigint;\n try {\n amountIn = BigInt(params.amountIn);\n } catch {\n return refuse(\"amount is not an integer\");\n }\n if (amountIn <= 0n) return refuse(\"amount must be positive\");\n const bps = params.slippageBps ?? slippageDefault;\n if (!Number.isInteger(bps) || bps <= 0 || bps >= 2_000) return refuse(\"invalid slippage (KyberSwap accepts under 20%)\", \"price_check_failed\");\n let floor = 0n;\n if (params.minAmountOut !== undefined) {\n const f = uint(params.minAmountOut);\n if (f === null) return refuse(\"minimum output is not an integer\");\n floor = f;\n }\n const dry = params.dry !== false;\n if (!dry && !isAddr(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\n if (!dry && !config.rpcUrls?.[chainId]?.length) return refuse(`no RPC configured for ${chain.name}: a KyberSwap swap is simulated before it is signed`, \"upstream_unavailable\");\n\n // Dry quotes for the same request share one route for a few seconds; an execution quote always asks afresh.\n let r: RoutesResult;\n if (dry) {\n const key = `${chainId}|${tokenIn}|${tokenOut}|${amountIn}`;\n const hit = dryCache.get(key);\n if (hit && Date.now() - hit.at < DRY_CACHE_MS) r = await hit.value;\n else {\n const value = routes(chainId, tokenIn, tokenOut, amountIn, signal);\n dryCache.set(key, {at: Date.now(), value});\n if (dryCache.size > 64) for (const [k, v] of dryCache) if (Date.now() - v.at >= DRY_CACHE_MS) dryCache.delete(k);\n r = await value;\n if (!r.ok) dryCache.delete(key);\n }\n } else r = await routes(chainId, tokenIn, tokenOut, amountIn, signal);\n if (!r.ok) return refuse(r.why, r.info);\n // KyberSwap's minimum lands one unit under the plain floor; asking for a hair less slippage keeps it at or\n // above the engine's floor for the user's slippage (a tiny output needs more than 1 bps for that unit).\n const apiBps = kyberApiSlippage(r.amountOut, bps);\n if (apiBps === null) return refuse(\"the output is too small to carry a minimum\", \"amount_too_small\");\n const minOut = kyberMinimum(r.amountOut, apiBps);\n if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, \"price_check_failed\");\n\n // The route's own gas figure, for comparing routes; execution still sends the account's own estimate.\n const gasEstimate = kyberGasEstimate(r.summary.gas);\n // A route through an RFQ maker or a limit order lives no longer than that liquidity (KYBER_RFQ_TTL_MS, KYBER_LIMIT_ORDER_TTL_MS).\n const offchain = [...(r.offchain.rfq ? [\"rfq\"] : []), ...(r.offchain.limitOrder ? [\"limit-order\"] : [])].join(\",\");\n const life = Math.min(ttl, ...(r.offchain.rfq ? [KYBER_RFQ_TTL_MS] : []), ...(r.offchain.limitOrder ? [KYBER_LIMIT_ORDER_TTL_MS] : []));\n const base = {\n provider: \"kyberswap\",\n intentId: `kyberswap:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n sourceAmount: amountIn.toString(),\n // KyberSwap's amountOut is the route's ceiling, not an average: the executed output came 1.5–7.4 bps under it.\n destAmount: r.amountOut.toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n ...(gasEstimate !== undefined ? {gasEstimate, gasEstimateSource: \"venue\" as const} : {}),\n etaSeconds: 15,\n reliability: 0.95,\n validUntilMs: Date.now() + life,\n } satisfies Partial<Quote>;\n const providerData: Record<string, string> = {\n amountOut: r.amountOut.toString(),\n minOut: minOut.toString(),\n apiSlippageBps: String(apiBps),\n ...(typeof r.summary.routeID === \"string\" ? {routeId: r.summary.routeID.slice(0, 80)} : {}),\n ...(r.sources.length ? {sources: r.sources.join(\",\")} : {}),\n ...(offchain ? {offchain} : {}),\n };\n // The router's quoteValues reads priceImpactBps into the user's \"be careful\" warning (Unichain USDC → JUP: −78 %).\n const lossBps = kyberValueLossBps(r.summary.amountInUsd, r.summary.amountOutUsd);\n if (lossBps !== null) providerData.priceImpactBps = String(lossBps);\n if (dry) {\n // A token sale approves the router first; the auction's gas estimate reads the spender from here.\n return {...base, providerData: tokenIn === ZERO ? providerData : {...providerData, approvalAddress: KYBER_ROUTER_V2}};\n }\n\n const receiver = getAddress(params.destAddress);\n const signer = isAddr(params.sender) ? params.sender : isAddr(params.refundAddress) ? params.refundAddress : params.destAddress;\n const sender = getAddress(signer);\n const built = await api(`${baseUrl}/${chain.slug}/api/v1/route/build`, {\n method: \"POST\",\n body: JSON.stringify({\n routeSummary: r.summary,\n sender,\n recipient: receiver,\n slippageTolerance: apiBps,\n deadline: Math.floor(Date.now() / 1000) + BUILD_DEADLINE_S,\n source: clientId,\n }),\n }, signal);\n if (!built.ok) return refuse(`build: ${built.why}`, built.info);\n const b = built.data;\n if (uint(b.amountIn) !== amountIn) return refuse(\"the build spends another amount\", \"price_check_failed\");\n // An RFQ maker signs (or the route falls back to the pool KyberSwap named after it) only now, and a limit order is\n // picked now: the build's amountOut is what this route pays, never more than the quote shown.\n let destAmount = r.amountOut;\n if (offchain) {\n const builtOut = uint(b.amountOut);\n if (builtOut === null) return refuse(\"malformed build response\", \"upstream_unavailable\");\n if (builtOut < minOut || builtOut < floor) return refuse(`the ${offchainName(offchain)} came in under the minimum when the route was built (${builtOut} < ${minOut}); refresh the quote`, \"price_check_failed\");\n if (builtOut < destAmount) destAmount = builtOut;\n }\n if (same(b.routerAddress, KYBER_ROUTER_V3)) return refuse(\"Kyber router V3 not supported yet\", \"policy_refused\");\n const value = uint(b.transactionValue ?? \"0\");\n if (value === null || typeof b.data !== \"string\") return refuse(\"malformed build response\", \"upstream_unavailable\");\n const tx = {to: typeof b.routerAddress === \"string\" ? b.routerAddress : \"\", value, data: b.data};\n let decoded;\n try {\n decoded = checkKyberTransaction(tx, {chainId, tokenIn, tokenOut, amountIn, receiver, minAmountOut: minOut > floor ? minOut : floor});\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e));\n }\n // Native input needs no allowance: the exact call runs against the latest block now, so a route that would revert\n // never reaches the user. Token input is checked the same way before any approval (tokenSwapCheck).\n let simulated = \"swap\";\n if (tokenIn !== ZERO) {\n try {\n const check = await tokenSwapCheck(chainId, sender, tokenIn, amountIn, tx.data as Hex);\n if (check.refusal) return refuse(check.refusal.why, check.refusal.reason);\n simulated = check.simulated;\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n if (tokenIn === ZERO) {\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: KYBER_ROUTER_V2, data: tx.data, value: `0x${value.toString(16)}`}, \"latest\", {[sender]: {balance: `0x${(value + 10n ** 18n).toString(16)}`}}]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) {\n const why = revertString(e);\n return refuse(`the route does not execute on-chain right now${why ? ` (${short(why)})` : \"\"}`, why && /return amount is not enough/i.test(why) ? \"price_check_failed\" : \"simulation_failed\");\n }\n return refuse(e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e), refusalOf(e) ?? \"upstream_unavailable\");\n }\n }\n return {\n ...base,\n destAmount: destAmount.toString(),\n minDestAmount: decoded.minReturnAmount.toString(),\n txRequest: {\n to: KYBER_ROUTER_V2,\n data: tx.data,\n value: value.toString(),\n chainId,\n ...(tokenIn === ZERO ? {} : {approvalAddress: KYBER_ROUTER_V2}),\n },\n providerData: {...providerData, sender, minOut: decoded.minReturnAmount.toString(), simulated},\n };\n },\n\n /**\n * Simulate the exact quoted transaction from the account at the latest block (approval in place) and refuse when\n * it would revert or when no RPC answers — the API is not trusted, so an unsimulated swap is not sent.\n * Only the quote's own transaction is simulated, never a caller's.\n */\n async preflightDeposit(quote: Quote, tx: UnsignedTx): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const sender = quote.providerData?.sender;\n const quoted = quote.txRequest;\n if (!kyberChain(chainId) || !isAddr(sender)) throw refusal(\"policy_refused\", \"kyberswap: the quote is not an execution quote. Nothing was sent; refresh the quote.\");\n if (!quoted?.to || !quoted.data || !sameText(tx.to, quoted.to) || !sameText(tx.data ?? \"\", quoted.data) || !sameAmount(tx.value || \"0\", quoted.value ?? \"0\")) {\n throw refusal(\"policy_refused\", \"kyberswap: the transaction is not the quoted swap. Nothing was sent; refresh the quote.\");\n }\n try {\n await rpc(chainId, \"eth_call\", [{from: sender, to: quoted.to, data: quoted.data, value: `0x${BigInt(quoted.value ?? \"0\").toString(16)}`}, \"latest\"]);\n } catch (e) {\n if ((e as {rpc?: boolean}).rpc) throw await revertReason(chainId, sender, quoted, e, typeof quote.providerData?.offchain === \"string\" ? quote.providerData.offchain : undefined);\n throw withReason(new Error(\"kyberswap: the swap cannot be simulated (no RPC answered). Nothing was sent; try again.\"), refusalOf(e) ?? \"upstream_unavailable\");\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw refusal(\"policy_refused\", \"swap2: KyberSwap quote has no transaction request (a dry quote cannot be executed)\");\n return {chain: \"\", to: tx.to, value: tx.value ?? \"0\", data: tx.data, ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}), ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {})};\n },\n\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!kyberChain(chainId) || !config.rpcUrls?.[chainId]?.length) return {state: \"pending\"};\n try {\n const receipt = (await rpc(chainId, \"eth_getTransactionReceipt\", [ref.sourceTxHash])) as {status?: string} | null;\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\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;AAAA;AAAA;AAAA;AAAA,IAAAA,eAAwG;AACxG,IAAAC,eAA0D;AAC1D,IAAAC,iBAA0G;AAE1G,IAAAC,uBAA6B;AAC7B,sBAA6B;;;ACA7B,sBAAwD;AACxD,IAAAC,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,MAAM,YAAY,OAAO,UAAS;AAAA,EACxD,MAAM,EAAC,MAA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AAC,OAAO,IAAI,IAAI,GAAG,IAAI,OAAO,GAAG,SAAS,KAAK,MAAM,GAAG,MAAM,GAAI,GAAG,YAAY,SAAY,EAAC,SAAS,GAAG,QAAO,IAAI,CAAC,GAAI,GAAI,GAAG,kBAAkB,EAAC,iBAAiB,GAAG,gBAAe,IAAI,CAAC,EAAE;AAAA,IACvM;AAAA,IAEA,MAAM,YAAY,KAAuC;AACvD,UAAI,CAAC,IAAI,aAAc,QAAO,EAAC,OAAO,UAAS;AAC/C,YAAM,UAAU,OAAO,IAAI,SAAS,MAAM,GAAG,EAAE,CAAC,CAAC;AACjD,UAAI,CAAC,WAAW,OAAO,KAAK,CAAC,OAAO,UAAU,OAAO,GAAG,OAAQ,QAAO,EAAC,OAAO,UAAS;AACxF,UAAI;AACF,cAAM,UAAW,MAAM,IAAI,SAAS,6BAA6B,CAAC,IAAI,YAAY,CAAC;AACnF,YAAI,CAAC,QAAS,QAAO,EAAC,OAAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;","names":["import_viem","import_util","import_errors","import_swap2_assets","import_util","refusal","ZERO","isAddr","same","chainIdOf","balance","value"]}
@@ -15,11 +15,41 @@ interface KyberswapProviderConfig {
15
15
  defaultSlippageBps?: number;
16
16
  quoteTtlMs?: number;
17
17
  timeoutMs?: number;
18
- /** Leave RFQ / private-market-maker sources out of routes (short-lived quotes; default true). */
18
+ /**
19
+ * RFQ market makers (KyberSwap's "RFQ sources": `pmm-N`, Bebop, Native, Hashflow, …), whose firm quote is signed
20
+ * when the route is built. Default "exclude". See the README ("RFQ and limit orders") for what including them costs.
21
+ */
22
+ rfq?: KyberSourceSetting;
23
+ /** KyberSwap's own limit orders (`kyberswap-limit-order-v2`), filled from an off-chain order book. Default "exclude". */
24
+ limitOrders?: KyberSourceSetting;
25
+ /**
26
+ * @deprecated Use `rfq` and `limitOrders`. `false` includes both (KyberSwap's `excludeRFQSources` leaves out RFQ
27
+ * makers and limit orders together); each of `rfq` / `limitOrders` overrides it for its own sources.
28
+ */
19
29
  excludeRfqSources?: boolean;
20
30
  /** KyberSwap source ids to leave out of routes. */
21
31
  excludedSources?: readonly string[];
22
32
  }
33
+ /** Whether a kind of off-chain liquidity may be in a route. */
34
+ type KyberSourceSetting = "exclude" | "include";
35
+ /**
36
+ * How long a quote whose route uses an RFQ maker stays executable, at most. The API states no expiry; measured
37
+ * 2026-11-30 (README, "RFQ and limit orders"): one of seven RFQ routes built at the quote ran at 11 s and reverted at
38
+ * 30 s. The module's `quoteTtlMs` still caps it.
39
+ */
40
+ declare const KYBER_RFQ_TTL_MS = 10000;
41
+ /**
42
+ * The same for a route through a KyberSwap limit order: every limit-order route built at the quote still ran at 60 s
43
+ * (the one followed further: at 91 s, reverting from 121 s). The module's `quoteTtlMs` (default 30 s) still caps it.
44
+ */
45
+ declare const KYBER_LIMIT_ORDER_TTL_MS = 30000;
46
+ /**
47
+ * A quote's `gasEstimate`: KyberSwap's `routeSummary.gas` from `GET /routes` (asked with `gasInclude=true`) as canonical
48
+ * digits, the same figure on a dry quote and on the execution quote built from that route. Undefined when the route
49
+ * states none, zero, or a figure past the contract's ten digits: no figure is made up. See the README for how it
50
+ * compares with the gas the built call used.
51
+ */
52
+ declare function kyberGasEstimate(routeGas: unknown): string | undefined;
23
53
  /**
24
54
  * KyberSwap's own USD value of the output against the input, as basis points lost (pool impact and pool fees together).
25
55
  * Information for the user's "be careful" warning, never a refusal. null when KyberSwap does not price either side
@@ -28,4 +58,4 @@ interface KyberswapProviderConfig {
28
58
  declare function kyberValueLossBps(amountInUsd: unknown, amountOutUsd: unknown): number | null;
29
59
  declare function kyberswapProvider(config?: KyberswapProviderConfig): CrossChainProvider;
30
60
 
31
- export { type KyberswapProviderConfig, kyberValueLossBps, kyberswapProvider };
61
+ export { KYBER_LIMIT_ORDER_TTL_MS, KYBER_RFQ_TTL_MS, type KyberSourceSetting, type KyberswapProviderConfig, kyberGasEstimate, kyberValueLossBps, kyberswapProvider };
@@ -15,11 +15,41 @@ interface KyberswapProviderConfig {
15
15
  defaultSlippageBps?: number;
16
16
  quoteTtlMs?: number;
17
17
  timeoutMs?: number;
18
- /** Leave RFQ / private-market-maker sources out of routes (short-lived quotes; default true). */
18
+ /**
19
+ * RFQ market makers (KyberSwap's "RFQ sources": `pmm-N`, Bebop, Native, Hashflow, …), whose firm quote is signed
20
+ * when the route is built. Default "exclude". See the README ("RFQ and limit orders") for what including them costs.
21
+ */
22
+ rfq?: KyberSourceSetting;
23
+ /** KyberSwap's own limit orders (`kyberswap-limit-order-v2`), filled from an off-chain order book. Default "exclude". */
24
+ limitOrders?: KyberSourceSetting;
25
+ /**
26
+ * @deprecated Use `rfq` and `limitOrders`. `false` includes both (KyberSwap's `excludeRFQSources` leaves out RFQ
27
+ * makers and limit orders together); each of `rfq` / `limitOrders` overrides it for its own sources.
28
+ */
19
29
  excludeRfqSources?: boolean;
20
30
  /** KyberSwap source ids to leave out of routes. */
21
31
  excludedSources?: readonly string[];
22
32
  }
33
+ /** Whether a kind of off-chain liquidity may be in a route. */
34
+ type KyberSourceSetting = "exclude" | "include";
35
+ /**
36
+ * How long a quote whose route uses an RFQ maker stays executable, at most. The API states no expiry; measured
37
+ * 2026-11-30 (README, "RFQ and limit orders"): one of seven RFQ routes built at the quote ran at 11 s and reverted at
38
+ * 30 s. The module's `quoteTtlMs` still caps it.
39
+ */
40
+ declare const KYBER_RFQ_TTL_MS = 10000;
41
+ /**
42
+ * The same for a route through a KyberSwap limit order: every limit-order route built at the quote still ran at 60 s
43
+ * (the one followed further: at 91 s, reverting from 121 s). The module's `quoteTtlMs` (default 30 s) still caps it.
44
+ */
45
+ declare const KYBER_LIMIT_ORDER_TTL_MS = 30000;
46
+ /**
47
+ * A quote's `gasEstimate`: KyberSwap's `routeSummary.gas` from `GET /routes` (asked with `gasInclude=true`) as canonical
48
+ * digits, the same figure on a dry quote and on the execution quote built from that route. Undefined when the route
49
+ * states none, zero, or a figure past the contract's ten digits: no figure is made up. See the README for how it
50
+ * compares with the gas the built call used.
51
+ */
52
+ declare function kyberGasEstimate(routeGas: unknown): string | undefined;
23
53
  /**
24
54
  * KyberSwap's own USD value of the output against the input, as basis points lost (pool impact and pool fees together).
25
55
  * Information for the user's "be careful" warning, never a refusal. null when KyberSwap does not price either side
@@ -28,4 +58,4 @@ interface KyberswapProviderConfig {
28
58
  declare function kyberValueLossBps(amountInUsd: unknown, amountOutUsd: unknown): number | null;
29
59
  declare function kyberswapProvider(config?: KyberswapProviderConfig): CrossChainProvider;
30
60
 
31
- export { type KyberswapProviderConfig, kyberValueLossBps, kyberswapProvider };
61
+ export { KYBER_LIMIT_ORDER_TTL_MS, KYBER_RFQ_TTL_MS, type KyberSourceSetting, type KyberswapProviderConfig, kyberGasEstimate, kyberValueLossBps, kyberswapProvider };
package/dist/provider.js CHANGED
@@ -1,10 +1,16 @@
1
1
  import {
2
+ KYBER_LIMIT_ORDER_TTL_MS,
3
+ KYBER_RFQ_TTL_MS,
4
+ kyberGasEstimate,
2
5
  kyberValueLossBps,
3
6
  kyberswapProvider
4
- } from "./chunk-DEWODPQQ.js";
5
- import "./chunk-FWC6K553.js";
6
- import "./chunk-WOVGN3FL.js";
7
+ } from "./chunk-NFMHUXU6.js";
8
+ import "./chunk-HHZEL5IJ.js";
9
+ import "./chunk-D4UIDHM2.js";
7
10
  export {
11
+ KYBER_LIMIT_ORDER_TTL_MS,
12
+ KYBER_RFQ_TTL_MS,
13
+ kyberGasEstimate,
8
14
  kyberValueLossBps,
9
15
  kyberswapProvider
10
16
  };
package/dist/router.cjs CHANGED
@@ -23,8 +23,10 @@ __export(router_exports, {
23
23
  KYBER_CHAINS: () => KYBER_CHAINS,
24
24
  KYBER_EXECUTOR: () => KYBER_EXECUTOR,
25
25
  KYBER_FLAGS_ALLOWED: () => KYBER_FLAGS_ALLOWED,
26
+ KYBER_LIMIT_ORDER_SOURCES: () => KYBER_LIMIT_ORDER_SOURCES,
26
27
  KYBER_NATIVE: () => KYBER_NATIVE,
27
28
  KYBER_REFUSED_SELECTORS: () => KYBER_REFUSED_SELECTORS,
29
+ KYBER_RFQ_SOURCES: () => KYBER_RFQ_SOURCES,
28
30
  KYBER_ROUTER_ABI: () => KYBER_ROUTER_ABI,
29
31
  KYBER_ROUTER_V2: () => KYBER_ROUTER_V2,
30
32
  KYBER_ROUTER_V3: () => KYBER_ROUTER_V3,
@@ -33,9 +35,11 @@ __export(router_exports, {
33
35
  checkKyberTransaction: () => checkKyberTransaction,
34
36
  kyberApiSlippage: () => kyberApiSlippage,
35
37
  kyberChain: () => kyberChain,
38
+ kyberExactAllowanceOnly: () => kyberExactAllowanceOnly,
36
39
  kyberMinimum: () => kyberMinimum,
37
40
  kyberNativeSwaps: () => kyberNativeSwaps,
38
41
  kyberPins: () => kyberPins,
42
+ kyberSourceKind: () => kyberSourceKind,
39
43
  kyberVerifyQuote: () => kyberVerifyQuote
40
44
  });
41
45
  module.exports = __toCommonJS(router_exports);
@@ -68,6 +72,34 @@ var KYBER_CHAINS = Object.freeze({
68
72
  5042: { slug: "arc", name: "Arc", build: "lite" },
69
73
  99901: { slug: "elysium", name: "Elysium", build: "lite" }
70
74
  });
75
+ var KYBER_LIMIT_ORDER_SOURCES = Object.freeze(["kyberswap-limit-order-v2"]);
76
+ var KYBER_RFQ_SOURCES = Object.freeze({
77
+ 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"],
78
+ 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"],
79
+ 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"],
80
+ 42161: ["bebop", "hashflow-v3", "native-v1", "native-v2", "pmm-13", "pmm-2", "pmm-21", "pmm-5", "pmm-6", "pmm-7", "pmm-8", "swaap-v2"],
81
+ 10: ["bebop", "pmm-13", "swaap-v2"],
82
+ 137: ["bebop", "native-v1", "pmm-5", "pmm-8", "swaap-v2"],
83
+ 43114: ["bebop", "dexalot", "hashflow-v3", "native-v1", "pmm-4", "swaap-v2"],
84
+ 59144: ["native-v1", "swaap-v2"],
85
+ 146: ["swaap-v2"],
86
+ 80094: ["bebop"],
87
+ 130: [],
88
+ 999: ["bebop"],
89
+ 9745: [],
90
+ 143: ["native-v2", "swaap-v2"],
91
+ 4326: [],
92
+ 4663: ["bebop", "native-v2", "pmm-18", "pmm-19", "pmm-20", "swaap-v2"],
93
+ 5042: ["pmm-13"],
94
+ 99901: []
95
+ });
96
+ var RFQ_LIKE = /^(?:pmm-\d+|kyber-pmm|native-v\d+|bebop|hashflow(?:-v\d+)?|swaap-v\d+|clipper|dexalot|mx-trading|[a-z0-9-]*-rfq|rfq-[a-z0-9-]*)$/;
97
+ function kyberSourceKind(chainId, exchange, poolType) {
98
+ const id = typeof exchange === "string" ? exchange.split("/")[0] : "";
99
+ if (poolType === "limit-order" || /^kyberswap-limit-order(?:-v\d+)?$/.test(id)) return "limit-order";
100
+ const listed = Object.prototype.hasOwnProperty.call(KYBER_RFQ_SOURCES, chainId) ? KYBER_RFQ_SOURCES[chainId] : [];
101
+ return poolType === "orderbook" || listed.includes(id) || RFQ_LIKE.test(id) ? "rfq" : "pool";
102
+ }
71
103
  function kyberChain(chainId) {
72
104
  return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : void 0;
73
105
  }
@@ -195,9 +227,13 @@ function kyberVerifyQuote(params, quote) {
195
227
  function routerFor(chain) {
196
228
  return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
197
229
  }
230
+ function kyberExactAllowanceOnly(chain) {
231
+ return kyberChain(chainIdOf(chain))?.build !== "lite";
232
+ }
198
233
  var kyberPins = Object.freeze({
199
234
  callTargets: routerFor,
200
235
  spenders: routerFor,
236
+ exactAllowanceOnly: kyberExactAllowanceOnly,
201
237
  verifyQuote: kyberVerifyQuote,
202
238
  reasonOf: (refusal) => notes.reasonOf(refusal)
203
239
  });