@anywalletkit/protocol-swap2-kyberswap 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -2
- package/dist/activity.cjs +4 -0
- package/dist/activity.cjs.map +1 -1
- package/dist/activity.js +2 -2
- package/dist/{chunk-FWC6K553.js → chunk-5ZMVXS7P.js} +2 -2
- package/dist/{chunk-PIC4PYGN.js → chunk-LO4G4NX7.js} +3 -3
- package/dist/{chunk-WOVGN3FL.js → chunk-OHBN7OQI.js} +6 -1
- package/dist/{chunk-WOVGN3FL.js.map → chunk-OHBN7OQI.js.map} +1 -1
- package/dist/{chunk-DEWODPQQ.js → chunk-RZ2CCM34.js} +13 -3
- package/dist/chunk-RZ2CCM34.js.map +1 -0
- package/dist/index.cjs +14 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +8 -4
- package/dist/protocol.cjs +12 -0
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.js +4 -4
- package/dist/provider.cjs +13 -0
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +8 -1
- package/dist/provider.d.ts +8 -1
- package/dist/provider.js +5 -3
- package/dist/router.cjs +5 -0
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts +9 -1
- package/dist/router.d.ts +9 -1
- package/dist/router.js +3 -1
- package/package.json +5 -5
- package/dist/chunk-DEWODPQQ.js.map +0 -1
- /package/dist/{chunk-FWC6K553.js.map → chunk-5ZMVXS7P.js.map} +0 -0
- /package/dist/{chunk-PIC4PYGN.js.map → chunk-LO4G4NX7.js.map} +0 -0
package/README.md
CHANGED
|
@@ -68,14 +68,47 @@ returns is checked on the device against the pinned router and the app's own req
|
|
|
68
68
|
gets the "be careful" warning even when the app has no price for the token (2026-11-25 Unichain USDC → JUP: 7 824 bps).
|
|
69
69
|
Information only, never a refusal; a token KyberSwap does not price carries none.
|
|
70
70
|
|
|
71
|
+
## Gas: `gasEstimate`
|
|
72
|
+
|
|
73
|
+
Every quote, dry or for execution, carries `gasEstimate` = KyberSwap's `routeSummary.gas` from `GET /routes` (asked
|
|
74
|
+
with `gasInclude=true`), `gasEstimateSource: "venue"`. It is there to compare routes (see protocol-swap2-core, "Gas:
|
|
75
|
+
`gasEstimate` vs `gasLimit`"): a dry quote has no transaction, so before this the router could only assume a gas limit
|
|
76
|
+
for it. Nothing in execution reads it: the swap still goes out with the account's own estimate of the exact call
|
|
77
|
+
(`ownGasEstimate`), and the transaction carries no gas limit. It counts the swap call only, no approval. A route that
|
|
78
|
+
states no gas (or 0) gives a quote without one.
|
|
79
|
+
|
|
80
|
+
What KyberSwap's figure is: its own model of the route's gas, not a simulation. The build answers the same number
|
|
81
|
+
(`gas` of `POST /route/build` equalled `routeSummary.gas` in all 16 recordings), and routine routes land on round model
|
|
82
|
+
values (330 498 for one Uniswap v3 or PancakeSwap v3 pool, 956 331 on two different chains). Against the gas the built
|
|
83
|
+
call used — 16 live routes recorded 2026-11-28 (`fixtures/quotes`) on Ethereum, Base, Arbitrum, Optimism, Polygon, BNB
|
|
84
|
+
Smart Chain, Linea, Sonic and Unichain for a throwaway sender = recipient, each built call run with `eth_simulateV1`
|
|
85
|
+
right after, at the chain's gas price (sender funded by a state override, a token input approved exactly in the same
|
|
86
|
+
simulated block; nothing sent):
|
|
87
|
+
|
|
88
|
+
| | Gas used ÷ `routeSummary.gas` |
|
|
89
|
+
|---|---|
|
|
90
|
+
| 16 routes | 0.58–1.85, median 0.73 |
|
|
91
|
+
| above the figure | 4 of 16: Linea Etherex CL 1.01, Polygon Ramses v3 + DODO 1.07, Sonic Metropolis LB 1.44, Base `kipseli-prop` 1.85 |
|
|
92
|
+
|
|
93
|
+
So it mostly runs high (the call used about three quarters of it at the median), and a proprietary-AMM route can run well over (how much gas such a pool
|
|
94
|
+
burns in a simulation need not be what it burns on-chain). The receiver held none of the output, so writing its first
|
|
95
|
+
balance is in these figures. On Arbitrum they are L2 execution gas without the L1 data component, which the router
|
|
96
|
+
leaves out too.
|
|
97
|
+
|
|
71
98
|
## Router owner
|
|
72
99
|
|
|
73
100
|
`KYBER_CHAINS[id].build` names the router build on each chain, read on-chain:
|
|
74
101
|
|
|
75
102
|
- `generic` (Ethereum, Base, BNB Smart Chain, Arbitrum, Optimism, Polygon, Avalanche, Linea): the router has
|
|
76
103
|
`swapGeneric` and an owner-managed whitelist, so its owner (a single key on all but Linea) could make it spend an
|
|
77
|
-
allowance left on it.
|
|
78
|
-
|
|
104
|
+
allowance left on it. None is left: the approval is exact and spent by the swap itself, and revoked if the swap
|
|
105
|
+
does not go out. The engine's two approval options (protocol-swap2-core, "Approvals") would change that —
|
|
106
|
+
`revokeUnspentApproval: false` leaves an unspent approval in place, `allowanceReuse: "sufficient"` swaps from a
|
|
107
|
+
larger allowance the account already gave the router, which then stays — so the provider declares
|
|
108
|
+
`exactAllowanceOnly` for these chains (`kyberExactAllowanceOnly`, also in `kyberPins` for a remote stub): the
|
|
109
|
+
engine holds KyberSwap routes here to the defaults whatever the app set, the allowance exact and revoked when
|
|
110
|
+
unspent. A chain this module does not list counts as `generic` (fail closed).
|
|
111
|
+
- `lite` (every other chain): no `swapGeneric`, no whitelist. The approval options apply there as on any provider.
|
|
79
112
|
|
|
80
113
|
## Limits
|
|
81
114
|
|
|
@@ -97,3 +130,7 @@ Base, 2026-11-24, one test wallet, through the engine (review → approval → p
|
|
|
97
130
|
The router's USDC allowance was 0 after the token swap. `scripts/verify-mainnet.mjs` repeats it (`--send native|token`).
|
|
98
131
|
|
|
99
132
|
`scripts/verify-live.mjs` checks the contracts on every chain and builds (unsigned) one corridor each way per chain.
|
|
133
|
+
|
|
134
|
+
## `blockNumber`
|
|
135
|
+
|
|
136
|
+
`QuoteParams.blockNumber` (one block for a comparison round) is not supported: the price comes from the KyberSwap Aggregator API, so the quote names no block (`Quote.blockNumber` absent).
|
package/dist/activity.cjs
CHANGED
|
@@ -179,9 +179,13 @@ function kyberVerifyQuote(params, quote) {
|
|
|
179
179
|
function routerFor(chain) {
|
|
180
180
|
return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
|
|
181
181
|
}
|
|
182
|
+
function kyberExactAllowanceOnly(chain) {
|
|
183
|
+
return kyberChain(chainIdOf(chain))?.build !== "lite";
|
|
184
|
+
}
|
|
182
185
|
var kyberPins = Object.freeze({
|
|
183
186
|
callTargets: routerFor,
|
|
184
187
|
spenders: routerFor,
|
|
188
|
+
exactAllowanceOnly: kyberExactAllowanceOnly,
|
|
185
189
|
verifyQuote: kyberVerifyQuote,
|
|
186
190
|
reasonOf: (refusal) => notes.reasonOf(refusal)
|
|
187
191
|
});
|
package/dist/activity.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/activity.ts","../src/router.ts"],"sourcesContent":["/**\n * Activity recognition for KyberSwap: a `swap()` call to MetaAggregationRouterV2 on a chain the module serves →\n * `swap`, \"Swapped A → B\" from the owner's net transfers.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {KYBER_ROUTER_V2, KYBER_SWAP_SELECTOR, kyberChain} from \"./router.js\";\n\nexport const KYBERSWAP_MODULE = \"@anywalletkit/protocol-swap2-kyberswap\";\n\nexport function describeKyberActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain) || !kyberChain(evmRef(tx.chain))) return null;\n if (!matchesCall(tx, [KYBER_ROUTER_V2], [KYBER_SWAP_SELECTOR])) return null;\n return describeSwapLike(tx, ctx, {protocol: KYBERSWAP_MODULE, subtitle: `KyberSwap · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** 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 verifyQ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O,SAAS,IAAI,WAAO,wBAAW,OAAO,SAAS;AAAA,MAC9E,UAAU,OAAO,OAAO,QAAQ;AAAA,MAChC,cAAU,wBAAW,OAAO,WAAW;AAAA,MACvC,cAAc;AAAA,IAChB,CAAC;AACD,WAAO;AAAA,EACT,SAAS,GAAG;AACV,UAAM,OAAO,aAAa,QAAQ,EAAE,QAAQ,QAAQ,gBAAgB,EAAE,IAAI,OAAO,CAAC;AAClF,UAAM,WAAO,yBAAU,CAAC;AACxB,WAAO,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,EACzC;AACF;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;;;ADvQM,IAAM,mBAAmB;AAEzB,SAAS,sBAAsB,IAAa,KAAmD;AACpG,MAAI,KAAC,oBAAM,GAAG,KAAK,KAAK,CAAC,eAAW,qBAAO,GAAG,KAAK,CAAC,EAAG,QAAO;AAC9D,MAAI,KAAC,6BAAY,IAAI,CAAC,eAAe,GAAG,CAAC,mBAAmB,CAAC,EAAG,QAAO;AACvE,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,kBAAkB,UAAU,sBAAe,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AAC9H;","names":["import_util"]}
|
|
1
|
+
{"version":3,"sources":["../src/activity.ts","../src/router.ts"],"sourcesContent":["/**\n * Activity recognition for KyberSwap: a `swap()` call to MetaAggregationRouterV2 on a chain the module serves →\n * `swap`, \"Swapped A → B\" from the owner's net transfers.\n */\nimport type {ActivityItem, ChainTx, DescribeActivityContext} from \"@anywalletkit/core\";\nimport {chainLabel, describeSwapLike, matchesCall} from \"@anywalletkit/protocol-swap2-core/activity\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {KYBER_ROUTER_V2, KYBER_SWAP_SELECTOR, kyberChain} from \"./router.js\";\n\nexport const KYBERSWAP_MODULE = \"@anywalletkit/protocol-swap2-kyberswap\";\n\nexport function describeKyberActivity(tx: ChainTx, ctx: DescribeActivityContext): ActivityItem | null {\n if (!isEvm(tx.chain) || !kyberChain(evmRef(tx.chain))) return null;\n if (!matchesCall(tx, [KYBER_ROUTER_V2], [KYBER_SWAP_SELECTOR])) return null;\n return describeSwapLike(tx, ctx, {protocol: KYBERSWAP_MODULE, subtitle: `KyberSwap · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** The chain entry for an id, never an inherited property. */\nexport function kyberChain(chainId: number): (typeof KYBER_CHAINS)[number] | undefined {\n return Object.prototype.hasOwnProperty.call(KYBER_CHAINS, chainId) ? KYBER_CHAINS[chainId] : undefined;\n}\n\n/**\n * Whether a swap may take or pay the chain's native coin: only where the token catalog lists one. Arc's gas token is\n * USDC with 18-decimal native accounting, listed only through its 6-decimal ERC-20 interface, so a native leg there\n * would carry amounts 10^12 off the catalog's USDC; it is refused and the ERC-20 swaps instead.\n */\nexport function kyberNativeSwaps(chainId: number): boolean {\n return !!ccAssetByToken(`eip155:${chainId}`, ZERO);\n}\n\n/** `swap(SwapExecutionParams)` — the one router entry point this module accepts. */\nexport const KYBER_ROUTER_ABI = parseAbi([\n \"struct SwapDescriptionV2 { address srcToken; address dstToken; address[] srcReceivers; uint256[] srcAmounts; address[] feeReceivers; uint256[] feeAmounts; address dstReceiver; uint256 amount; uint256 minReturnAmount; uint256 flags; bytes permit; }\",\n \"struct SwapExecutionParams { address callTarget; address approveTarget; bytes targetData; SwapDescriptionV2 desc; bytes clientData; }\",\n \"function swap(SwapExecutionParams execution) payable returns (uint256 returnAmount, uint256 gasUsed)\",\n]);\nexport const KYBER_SWAP_SELECTOR = \"0xe21fd0e9\";\n/** Router entry points that are refused by name: `swapGeneric` (owner-whitelisted arbitrary call) and `swapSimpleMode` (no minimum check). */\nexport const KYBER_REFUSED_SELECTORS: Readonly<Record<string, string>> = Object.freeze({\n \"0x59e50fed\": \"swapGeneric\",\n \"0x8af033fb\": \"swapSimpleMode\",\n});\n/**\n * The only flag bit accepted: `0x200`, set on every swap the build endpoint encodes (not one of the V2 source's named\n * flags; its meaning is not documented). Partial fill (0x01), extra value (0x02), claim (0x04), burns (0x08/0x10),\n * simple mode (0x20), fee on output (0x40), fee in bps (0x80) and approve-fund (0x100) are refused, as is any other bit.\n */\nexport const KYBER_FLAGS_ALLOWED = 0x200n;\n\nexport class KyberTransactionError extends Error {\n constructor(message: string) {\n super(`kyberswap: ${message}`);\n this.name = \"KyberTransactionError\";\n }\n}\nconst fail = (message: string, reason: Swap2RefusalReason): KyberTransactionError => withReason(new KyberTransactionError(message), reason);\nconst notes = refusalNotes();\n\nexport interface ExpectedKyberSwap {\n chainId: number;\n /** ERC-20 address, or the zero address for the native coin. */\n tokenIn: string;\n tokenOut: string;\n amountIn: bigint;\n /** Who must receive the output (the request's recipient). */\n receiver: string;\n /** The least `minReturnAmount` the calldata may name: the quote's minimum (and the caller's floor). */\n minAmountOut: bigint;\n}\n\nexport interface EncodedTx {\n to: string;\n value: bigint;\n data: string;\n}\n\nexport interface DecodedKyberSwap {\n srcToken: string;\n dstToken: string;\n dstReceiver: string;\n amount: bigint;\n minReturnAmount: bigint;\n flags: bigint;\n}\n\nconst isAddr = (a: unknown): a is string => typeof a === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(a);\nconst same = (a: string, b: string): boolean => isAddr(a) && isAddr(b) && a.toLowerCase() === b.toLowerCase();\nconst routerToken = (t: string): string => (same(t, ZERO) ? KYBER_NATIVE : t);\n/** The calldata may be a megabyte from an untrusted source: names in refusals are addresses only. */\nconst named = (a: unknown): string => (isAddr(a) ? a : \"something that is not an address\");\n/** At most this much calldata is decoded (a routed swap is a few KB). */\nconst MAX_CALLDATA_BYTES = 64 * 1024;\n\n/** Refuses (throws {@link KyberTransactionError}) unless `tx` is exactly the swap the wallet asked for. */\nexport function checkKyberTransaction(tx: EncodedTx, expected: ExpectedKyberSwap): DecodedKyberSwap {\n const chain = kyberChain(expected.chainId);\n if (!chain) throw fail(`chain ${expected.chainId} has no pinned KyberSwap router`, \"unsupported_pair\");\n if (same(tx.to, KYBER_ROUTER_V3)) throw fail(\"Kyber router V3 not supported yet\", \"policy_refused\");\n if (!same(tx.to, KYBER_ROUTER_V2)) throw fail(`the transaction targets ${named(tx.to)}, not the KyberSwap router on ${chain.name}`, \"vault_mismatch\");\n if (!isAddr(expected.receiver) || same(expected.receiver, ZERO) || same(expected.receiver, KYBER_ROUTER_V2) || same(expected.receiver, KYBER_EXECUTOR)) {\n throw fail(\"invalid receiver\", \"recipient_mismatch\");\n }\n const nativeIn = same(expected.tokenIn, ZERO), nativeOut = same(expected.tokenOut, ZERO);\n if ((nativeIn || nativeOut) && !kyberNativeSwaps(expected.chainId)) throw fail(`the native coin on ${chain.name} is not a catalog asset here; swap its ERC-20 instead`, \"unsupported_pair\");\n if (same(expected.tokenIn, expected.tokenOut)) throw fail(\"same token in and out\", \"unsupported_pair\");\n if (expected.amountIn <= 0n || expected.minAmountOut <= 0n) throw fail(\"invalid quote amounts\", \"price_check_failed\");\n if (typeof tx.data !== \"string\" || !/^0x(?:[0-9a-fA-F]{2}){4,}$/.test(tx.data)) throw fail(\"malformed calldata\", \"policy_refused\");\n if (tx.data.length > 2 + 2 * MAX_CALLDATA_BYTES) throw fail(\"calldata is larger than any routed swap\", \"policy_refused\");\n const selector = tx.data.slice(0, 10).toLowerCase();\n const refused = Object.prototype.hasOwnProperty.call(KYBER_REFUSED_SELECTORS, selector) ? KYBER_REFUSED_SELECTORS[selector] : undefined;\n if (refused) throw fail(`the transaction calls ${refused}, which this module never uses`, \"policy_refused\");\n if (selector !== KYBER_SWAP_SELECTOR) throw fail(\"not a router swap() call\", \"policy_refused\");\n\n let x: {callTarget: string; approveTarget: string; targetData: Hex; desc: {srcToken: string; dstToken: string; srcReceivers: readonly string[]; srcAmounts: readonly bigint[]; feeReceivers: readonly string[]; feeAmounts: readonly bigint[]; dstReceiver: string; amount: bigint; minReturnAmount: bigint; flags: bigint; permit: Hex}; clientData: Hex};\n try {\n const call = decodeFunctionData({abi: KYBER_ROUTER_ABI, data: tx.data as Hex});\n x = call.args[0] as typeof x;\n // Strict: the calldata must be exactly the canonical encoding of what was decoded (no trailing bytes, no odd offsets or padding).\n const again = encodeFunctionData({abi: KYBER_ROUTER_ABI, functionName: \"swap\", args: [x as never]});\n if (again.toLowerCase() !== tx.data.toLowerCase()) throw new Error(\"non-canonical\");\n } catch {\n throw fail(\"the calldata is not a canonical router swap() encoding\", \"policy_refused\");\n }\n const d = x.desc;\n if (!same(x.callTarget, KYBER_EXECUTOR)) throw fail(`the swap runs through ${named(x.callTarget)}, not the pinned KyberSwap executor`, \"vault_mismatch\");\n if (!same(x.approveTarget, ZERO)) throw fail(\"the swap asks the router to approve another contract\", \"policy_refused\");\n if (!same(d.srcToken, routerToken(expected.tokenIn)) || !same(d.dstToken, routerToken(expected.tokenOut))) throw fail(\"calldata swaps other tokens than requested\", \"policy_refused\");\n if (d.amount !== expected.amountIn) throw fail(`calldata spends ${d.amount}, not ${expected.amountIn}`, \"price_check_failed\");\n if (d.srcReceivers.length !== d.srcAmounts.length) throw fail(\"malformed input split\", \"policy_refused\");\n if (nativeIn) {\n if (d.srcReceivers.length !== 0) throw fail(\"a native-coin swap must not split the input\", \"policy_refused\");\n if (tx.value !== expected.amountIn) throw fail(\"native value does not match the input\", \"price_check_failed\");\n } else {\n if (tx.value !== 0n) throw fail(\"a token swap must not send the native coin\", \"price_check_failed\");\n const total = d.srcAmounts.reduce((s, a) => s + a, 0n);\n if (total !== expected.amountIn) throw fail(`the input split adds up to ${total}, not ${expected.amountIn}`, \"price_check_failed\");\n }\n if (same(d.dstReceiver, ZERO)) throw fail(\"the swap names no receiver\", \"recipient_mismatch\");\n if (!same(d.dstReceiver, expected.receiver)) throw fail(`calldata pays ${named(d.dstReceiver)}, not ${expected.receiver}`, \"recipient_mismatch\");\n if (d.minReturnAmount <= 0n) throw fail(\"the swap names no minimum\", \"price_check_failed\");\n if (d.minReturnAmount < expected.minAmountOut) throw fail(`calldata guarantees ${d.minReturnAmount}, under the quoted minimum ${expected.minAmountOut}`, \"price_check_failed\");\n if (d.feeReceivers.length !== 0 || d.feeAmounts.length !== 0) throw fail(\"calldata pays a fee receiver — this module charges none\", \"policy_refused\");\n if ((d.flags & ~KYBER_FLAGS_ALLOWED) !== 0n) throw fail(`calldata sets router flags ${d.flags.toString(16).slice(0, 16)} (only 0x200 is accepted)`, \"policy_refused\");\n if (d.permit !== \"0x\") throw fail(\"calldata carries a permit\", \"policy_refused\");\n return {srcToken: d.srcToken, dstToken: d.dstToken, dstReceiver: d.dstReceiver, amount: d.amount, minReturnAmount: d.minReturnAmount, flags: d.flags};\n}\n\n/**\n * The minimum KyberSwap's build encodes for `amountOut` at `bps` slippage: the expected output less the slippage,\n * rounded down, less one more unit — the build endpoint always lands exactly one base unit under the plain\n * `floor(amountOut × (10000 − bps) / 10000)` (18 chains, 2026-11-24). The quote shows this value, so the dry quote,\n * the build and the check agree to the unit.\n */\nexport function kyberMinimum(amountOut: bigint, bps: number): bigint {\n const m = (amountOut * BigInt(10_000 - bps)) / 10_000n - 1n;\n return m > 0n ? m : 0n;\n}\n\n/**\n * The slippage to ask KyberSwap for so that its minimum — one unit under the plain floor ({@link kyberMinimum}) — still\n * meets the engine's floor for the slippage the user chose, `floor(amountOut × (10000 − bps) / 10000)`. One basis point\n * less for most outputs; more for a tiny output (a $1 WBTC buy is a few thousand units, where 1 bps is under one unit).\n * Null when no positive slippage does (an output too small to carry a minimum).\n */\nexport function kyberApiSlippage(amountOut: bigint, bps: number): number | null {\n const floor = (amountOut * BigInt(10_000 - bps)) / 10_000n;\n for (let b = bps - 1; b >= 1; b--) if (kyberMinimum(amountOut, b) >= floor && kyberMinimum(amountOut, b) > 0n) return b;\n return null;\n}\n\nconst chainIdOf = (caip2: string): number => (/^eip155:[0-9]+$/.test(caip2) ? Number(caip2.slice(7)) : NaN);\n\n/**\n * The app's own check of a KyberSwap quote (behind `remoteProvider`, or on any quote): one chain, the exact input,\n * a minimum at or under the expected output and at or above the caller's floor; an execution quote's transaction must\n * pass {@link checkKyberTransaction} against this app's request. A dry quote carries no transaction. The reason it fails, or null.\n */\nexport function kyberVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n if (params.sourceChain !== params.destChain) return notes.note(\"same-chain swaps only\", \"unsupported_pair\");\n try {\n const chainId = chainIdOf(params.sourceChain);\n if (!kyberChain(chainId)) return notes.note(`no pinned KyberSwap router on ${params.sourceChain}`, \"unsupported_pair\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n if (quote.sourceAmount !== params.amountIn) return notes.note(\"the quote prices another amount\", \"price_check_failed\");\n const min = BigInt(quote.minDestAmount), out = BigInt(quote.destAmount);\n if (min <= 0n || min > out) return notes.note(\"invalid quote amounts\", \"price_check_failed\");\n if (params.minAmountOut !== undefined && min < BigInt(params.minAmountOut)) return notes.note(\"the quote's minimum is under the floor\", \"price_check_failed\");\n // The minimum is the expected output less the requested slippage, never more slippage than asked for.\n const bps = params.slippageBps;\n if (bps !== undefined && Number.isInteger(bps) && bps >= 0 && bps < 10_000 && min < kyberMinimum(out, bps)) {\n return notes.note(\"the quote's minimum allows more slippage than requested\", \"price_check_failed\");\n }\n const tx = quote.txRequest;\n if (!tx) return params.dry === false ? notes.note(\"the quote carries no router transaction\", \"policy_refused\") : null;\n if (!tx.to || !tx.data) return notes.note(\"the quote carries no router transaction\", \"policy_refused\");\n if (tx.approvalAddress !== undefined && !same(tx.approvalAddress, KYBER_ROUTER_V2)) return notes.note(\"the quote asks to approve another spender\", \"vault_mismatch\");\n checkKyberTransaction({to: tx.to, data: tx.data, value: BigInt(tx.value ?? \"0\")}, {\n chainId,\n tokenIn: src.contract ? getAddress(src.contract) : ZERO,\n tokenOut: /^0x0+$/.test(params.destToken) ? ZERO : getAddress(params.destToken),\n amountIn: BigInt(params.amountIn),\n receiver: getAddress(params.destAddress),\n minAmountOut: min,\n });\n return null;\n } catch (e) {\n const text = e instanceof Error ? e.message.replace(/^kyberswap: /, \"\") : String(e);\n const info = refusalOf(e);\n return info ? notes.note(text, info) : text;\n }\n}\n\nfunction routerFor(chain: string): readonly string[] {\n return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];\n}\n\n/**\n * The provider's `exactAllowanceOnly` (protocol-swap2-core): true on the chains whose router is the `generic` build —\n * `swapGeneric` behind an owner-managed executor whitelist, so the router's owner (a single key on all but Linea) could\n * make it spend an allowance left on it. The engine then approves exactly the input and revokes it when the swap does\n * not spend it, whatever the app's `allowanceReuse` / `revokeUnspentApproval` say. False on the `lite` chains; true\n * for a chain this module does not know (fail closed).\n */\nexport function kyberExactAllowanceOnly(chain: string): boolean {\n return kyberChain(chainIdOf(chain))?.build !== \"lite\";\n}\n\n/**\n * The router a KyberSwap swap calls and approves, and {@link kyberVerifyQuote}: the app's side of\n * `remoteProvider({name: \"kyberswap\", baseUrl, ...kyberPins})`, so a backend's quote is checked against the pinned\n * router and the app's own request, never against itself.\n */\nexport const kyberPins: RemotePins = Object.freeze({\n callTargets: routerFor,\n spenders: routerFor,\n exactAllowanceOnly: kyberExactAllowanceOnly,\n verifyQuote: kyberVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,sBAAwD;AACxD,IAAAA,eAA4B;;;ACM5B,kBAA4B;AAC5B,oBAA2E;AAC3E,0BAA6B;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,M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SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AASO,SAAS,wBAAwB,OAAwB;AAC9D,SAAO,WAAW,UAAU,KAAK,CAAC,GAAG,UAAU;AACjD;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;;;ADnRM,IAAM,mBAAmB;AAEzB,SAAS,sBAAsB,IAAa,KAAmD;AACpG,MAAI,KAAC,oBAAM,GAAG,KAAK,KAAK,CAAC,eAAW,qBAAO,GAAG,KAAK,CAAC,EAAG,QAAO;AAC9D,MAAI,KAAC,6BAAY,IAAI,CAAC,eAAe,GAAG,CAAC,mBAAmB,CAAC,EAAG,QAAO;AACvE,aAAO,kCAAiB,IAAI,KAAK,EAAC,UAAU,kBAAkB,UAAU,sBAAe,4BAAW,GAAG,KAAK,CAAC,IAAI,MAAM,OAAM,CAAC;AAC9H;","names":["import_util"]}
|
package/dist/activity.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
KYBER_ROUTER_V2,
|
|
3
3
|
KYBER_SWAP_SELECTOR,
|
|
4
4
|
kyberChain
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-OHBN7OQI.js";
|
|
6
6
|
|
|
7
7
|
// src/activity.ts
|
|
8
8
|
import { chainLabel, describeSwapLike, matchesCall } from "@anywalletkit/protocol-swap2-core/activity";
|
|
@@ -18,4 +18,4 @@ export {
|
|
|
18
18
|
KYBERSWAP_MODULE,
|
|
19
19
|
describeKyberActivity
|
|
20
20
|
};
|
|
21
|
-
//# sourceMappingURL=chunk-
|
|
21
|
+
//# sourceMappingURL=chunk-5ZMVXS7P.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
kyberswapProvider
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-RZ2CCM34.js";
|
|
4
4
|
import {
|
|
5
5
|
kyberChain
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-OHBN7OQI.js";
|
|
7
7
|
|
|
8
8
|
// src/protocol.ts
|
|
9
9
|
import { SingleProviderSwap2 } from "@anywalletkit/protocol-swap2-core/swap2/single";
|
|
@@ -29,4 +29,4 @@ var KyberswapSwap2Protocol = class extends SingleProviderSwap2 {
|
|
|
29
29
|
export {
|
|
30
30
|
KyberswapSwap2Protocol
|
|
31
31
|
};
|
|
32
|
-
//# sourceMappingURL=chunk-
|
|
32
|
+
//# sourceMappingURL=chunk-LO4G4NX7.js.map
|
|
@@ -155,9 +155,13 @@ function kyberVerifyQuote(params, quote) {
|
|
|
155
155
|
function routerFor(chain) {
|
|
156
156
|
return kyberChain(chainIdOf(chain)) ? [KYBER_ROUTER_V2] : [];
|
|
157
157
|
}
|
|
158
|
+
function kyberExactAllowanceOnly(chain) {
|
|
159
|
+
return kyberChain(chainIdOf(chain))?.build !== "lite";
|
|
160
|
+
}
|
|
158
161
|
var kyberPins = Object.freeze({
|
|
159
162
|
callTargets: routerFor,
|
|
160
163
|
spenders: routerFor,
|
|
164
|
+
exactAllowanceOnly: kyberExactAllowanceOnly,
|
|
161
165
|
verifyQuote: kyberVerifyQuote,
|
|
162
166
|
reasonOf: (refusal) => notes.reasonOf(refusal)
|
|
163
167
|
});
|
|
@@ -179,6 +183,7 @@ export {
|
|
|
179
183
|
kyberMinimum,
|
|
180
184
|
kyberApiSlippage,
|
|
181
185
|
kyberVerifyQuote,
|
|
186
|
+
kyberExactAllowanceOnly,
|
|
182
187
|
kyberPins
|
|
183
188
|
};
|
|
184
|
-
//# sourceMappingURL=chunk-
|
|
189
|
+
//# sourceMappingURL=chunk-OHBN7OQI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router.ts"],"sourcesContent":["/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** 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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gB;AACnK,0BAAsB,EAAC,IAAI,GAAG,IAAI,MAAM,GAAG,MAAM,OAAO,OAAO,GAAG,SAAS,GAAG,EAAC,GAAG;AAAA,MAChF;AAAA,MACA,SAAS,IAAI,WAAW,WAAW,IAAI,QAAQ,IAAI;AAAA,MACnD,UAAU,SAAS,KAAK,OAAO,SAAS,IAAI,OAAO,WAAW,OAAO,SAAS;AAAA,MAC9E,UAAU,OAAO,OAAO,QAAQ;AAAA,MAChC,UAAU,WAAW,OAAO,WAAW;AAAA,MACvC,cAAc;AAAA,IAChB,CAAC;AACD,WAAO;AAAA,EACT,SAAS,GAAG;AACV,UAAM,OAAO,aAAa,QAAQ,EAAE,QAAQ,QAAQ,gBAAgB,EAAE,IAAI,OAAO,CAAC;AAClF,UAAM,OAAO,UAAU,CAAC;AACxB,WAAO,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,EACzC;AACF;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/router.ts"],"sourcesContent":["/**\n * KyberSwap MetaAggregationRouterV2 — the only contract a KyberSwap quote may settle through. This file pins the\n * router and its executor per chain and checks the transaction KyberSwap's build endpoint encoded against the request\n * before anything is approved or sent.\n *\n * The router itself guarantees only that the input comes from the caller and that `dstReceiver` gains at least\n * `minReturnAmount` of `dstToken`; the receiver, the tokens, the minimum, the fee receivers and the flags are all\n * the calldata's (KyberSwap's build endpoint encodes whatever `routeSummary` it is sent, fee entries included).\n * So the calldata is decoded strictly, re-encoded byte for byte, and every field that can move value is compared\n * with the request. The route inside `targetData` is opaque; the router reverts below the minimum.\n */\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {refusalNotes, refusalOf, withReason, type Swap2RefusalReason} from \"@anywalletkit/protocol-swap2-core/errors\";\nimport {ccAssetByToken} from \"@anywalletkit/swap2-assets\";\nimport {decodeFunctionData, encodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\n\n/** MetaAggregationRouterV2 — the same address on every chain KyberSwap serves (docs.kyberswap.com, contracts). */\nexport const KYBER_ROUTER_V2 = \"0x6131B5fae19EA4f9D964eAc0408E4408b66337b5\";\n/** AggregationExecutorProxy — the `callTarget` of every swap the build endpoint encodes. */\nexport const KYBER_EXECUTOR = \"0x8F10B468b06c6FD214B65F87778827F7D113f996\";\n/** KSAggregationRouterV3: deployed on part of the chains, never returned by the API so far. Refused until decoded. */\nexport const KYBER_ROUTER_V3 = \"0x6868d319c8c9a78f7d39dc3602c5c917315132d7\";\n/** The router's native-coin sentinel; this SDK uses the zero address. */\nexport const KYBER_NATIVE = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\n\n/**\n * Router build on a chain. `generic`: the 2022 build (18.6 KB) with `swapGeneric` and an owner-managed whitelist — its\n * owner can make the router call any whitelisted contract, so an allowance left on it is exposed to that owner.\n * `lite`: the later build (13.7 KB) without `swapGeneric` and without the whitelist. Both share `swap()`.\n * Read on-chain 2026-11-24 (`eth_getCode`, selectors in the bytecode, `owner()`; how-to-project/kyber-data).\n */\nexport type KyberRouterBuild = \"generic\" | \"lite\";\n\n/**\n * Every chain this module quotes on: KyberSwap's `supported-chains` list (active, plus Arc \"new\" and Elysium\n * \"provisional\") intersected with the SDK's EVM catalog, each with the router and executor code checked on-chain.\n * `slug` is the API's path segment (a chain id there is a 404).\n */\nexport const KYBER_CHAINS: Readonly<Record<number, {slug: string; name: string; build: KyberRouterBuild}>> = Object.freeze({\n 1: {slug: \"ethereum\", name: \"Ethereum\", build: \"generic\"},\n 8453: {slug: \"base\", name: \"Base\", build: \"generic\"},\n 56: {slug: \"bsc\", name: \"BNB Smart Chain\", build: \"generic\"},\n 42161: {slug: \"arbitrum\", name: \"Arbitrum\", build: \"generic\"},\n 10: {slug: \"optimism\", name: \"Optimism\", build: \"generic\"},\n 137: {slug: \"polygon\", name: \"Polygon\", build: \"generic\"},\n 43114: {slug: \"avalanche\", name: \"Avalanche\", build: \"generic\"},\n 59144: {slug: \"linea\", name: \"Linea\", build: \"generic\"},\n 146: {slug: \"sonic\", name: \"Sonic\", build: \"lite\"},\n 80094: {slug: \"berachain\", name: \"Berachain\", build: \"lite\"},\n 130: {slug: \"unichain\", name: \"Unichain\", build: \"lite\"},\n 999: {slug: \"hyperevm\", name: \"HyperEVM\", build: \"lite\"},\n 9745: {slug: \"plasma\", name: \"Plasma\", build: \"lite\"},\n 143: {slug: \"monad\", name: \"Monad\", build: \"lite\"},\n 4326: {slug: \"megaeth\", name: \"MegaETH\", build: \"lite\"},\n 4663: {slug: \"robinhood\", name: \"Robinhood Chain\", build: \"lite\"},\n 5042: {slug: \"arc\", name: \"Arc\", build: \"lite\"},\n 99901: {slug: \"elysium\", name: \"Elysium\", build: \"lite\"},\n});\n\n/** 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: k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AgB;AACnK,0BAAsB,EAAC,IAAI,GAAG,IAAI,MAAM,GAAG,MAAM,OAAO,OAAO,GAAG,SAAS,GAAG,EAAC,GAAG;AAAA,MAChF;AAAA,MACA,SAAS,IAAI,WAAW,WAAW,IAAI,QAAQ,IAAI;AAAA,MACnD,UAAU,SAAS,KAAK,OAAO,SAAS,IAAI,OAAO,WAAW,OAAO,SAAS;AAAA,MAC9E,UAAU,OAAO,OAAO,QAAQ;AAAA,MAChC,UAAU,WAAW,OAAO,WAAW;AAAA,MACvC,cAAc;AAAA,IAChB,CAAC;AACD,WAAO;AAAA,EACT,SAAS,GAAG;AACV,UAAM,OAAO,aAAa,QAAQ,EAAE,QAAQ,QAAQ,gBAAgB,EAAE,IAAI,OAAO,CAAC;AAClF,UAAM,OAAO,UAAU,CAAC;AACxB,WAAO,OAAO,MAAM,KAAK,MAAM,IAAI,IAAI;AAAA,EACzC;AACF;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,WAAW,UAAU,KAAK,CAAC,IAAI,CAAC,eAAe,IAAI,CAAC;AAC7D;AASO,SAAS,wBAAwB,OAAwB;AAC9D,SAAO,WAAW,UAAU,KAAK,CAAC,GAAG,UAAU;AACjD;AAOO,IAAM,YAAwB,OAAO,OAAO;AAAA,EACjD,aAAa;AAAA,EACb,UAAU;AAAA,EACV,oBAAoB;AAAA,EACpB,aAAa;AAAA,EACb,UAAU,CAAC,YAAoB,MAAM,SAAS,OAAO;AACvD,CAAC;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
describeKyberActivity
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-5ZMVXS7P.js";
|
|
4
4
|
import {
|
|
5
5
|
KYBER_NATIVE,
|
|
6
6
|
KYBER_ROUTER_ABI,
|
|
@@ -9,9 +9,10 @@ import {
|
|
|
9
9
|
checkKyberTransaction,
|
|
10
10
|
kyberApiSlippage,
|
|
11
11
|
kyberChain,
|
|
12
|
+
kyberExactAllowanceOnly,
|
|
12
13
|
kyberMinimum,
|
|
13
14
|
kyberNativeSwaps
|
|
14
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-OHBN7OQI.js";
|
|
15
16
|
|
|
16
17
|
// src/provider.ts
|
|
17
18
|
import { decodeErrorResult, decodeFunctionData, encodeFunctionData, getAddress, parseAbi } from "viem";
|
|
@@ -50,6 +51,10 @@ var sameText = (a, b) => a.length === b.length && a.toLowerCase() === b.toLowerC
|
|
|
50
51
|
var sameAmount = (a, b) => /^\d{1,80}$/.test(a) && /^\d{1,80}$/.test(b) && BigInt(a) === BigInt(b);
|
|
51
52
|
var apiToken = (t) => t === ZERO ? KYBER_NATIVE : t;
|
|
52
53
|
var short = (s) => String(s ?? "").replace(/\s+/g, " ").slice(0, 120);
|
|
54
|
+
function kyberGasEstimate(routeGas) {
|
|
55
|
+
const gas = uint(routeGas);
|
|
56
|
+
return gas !== null && gas > 0n && gas < 10000000000n ? gas.toString() : void 0;
|
|
57
|
+
}
|
|
53
58
|
var ERC20_READS = parseAbi(["function balanceOf(address) view returns (uint256)", "function allowance(address, address) view returns (uint256)", "function approve(address, uint256) returns (bool)"]);
|
|
54
59
|
function revertData(e) {
|
|
55
60
|
const err = e;
|
|
@@ -228,6 +233,8 @@ function kyberswapProvider(config = {}) {
|
|
|
228
233
|
supportsSameChain: true,
|
|
229
234
|
// The account's own estimate of the exact call, never the API's gas model.
|
|
230
235
|
ownGasEstimate: true,
|
|
236
|
+
// On a generic-build router (an owner-managed swapGeneric whitelist) no allowance may outlive the swap.
|
|
237
|
+
exactAllowanceOnly: kyberExactAllowanceOnly,
|
|
231
238
|
enabled: () => config.enabled ?? true,
|
|
232
239
|
supportsChain: (caip2) => chainIdOf(caip2) !== null,
|
|
233
240
|
supportsChainPair: (from, to) => from === to && chainIdOf(from) !== null,
|
|
@@ -296,6 +303,7 @@ function kyberswapProvider(config = {}) {
|
|
|
296
303
|
if (apiBps === null) return refuse("the output is too small to carry a minimum", "amount_too_small");
|
|
297
304
|
const minOut = kyberMinimum(r.amountOut, apiBps);
|
|
298
305
|
if (minOut < floor) return refuse(`floor breach (min=${minOut} < floor=${floor})`, "price_check_failed");
|
|
306
|
+
const gasEstimate = kyberGasEstimate(r.summary.gas);
|
|
299
307
|
const base = {
|
|
300
308
|
provider: "kyberswap",
|
|
301
309
|
intentId: `kyberswap:${chainId}`,
|
|
@@ -306,6 +314,7 @@ function kyberswapProvider(config = {}) {
|
|
|
306
314
|
destAmount: r.amountOut.toString(),
|
|
307
315
|
minDestAmount: minOut.toString(),
|
|
308
316
|
feeUsd: 0,
|
|
317
|
+
...gasEstimate !== void 0 ? { gasEstimate, gasEstimateSource: "venue" } : {},
|
|
309
318
|
etaSeconds: 15,
|
|
310
319
|
reliability: 0.95,
|
|
311
320
|
validUntilMs: Date.now() + ttl
|
|
@@ -424,7 +433,8 @@ function kyberswapProvider(config = {}) {
|
|
|
424
433
|
}
|
|
425
434
|
|
|
426
435
|
export {
|
|
436
|
+
kyberGasEstimate,
|
|
427
437
|
kyberValueLossBps,
|
|
428
438
|
kyberswapProvider
|
|
429
439
|
};
|
|
430
|
-
//# sourceMappingURL=chunk-
|
|
440
|
+
//# sourceMappingURL=chunk-RZ2CCM34.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.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, kyberExactAllowanceOnly, 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\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 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 // 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 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() + 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"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAQ,mBAAmB,oBAAoB,oBAAoB,YAAY,gBAAyB;AACxG,SAAQ,QAAQ,OAAO,eAAe,qBAAoB;AAC1D,SAAQ,aAAa,SAAS,WAAW,kBAAiE;AAE1G,SAAQ,sBAAqB;AAC7B,SAAQ,sBAAqB;AAkB7B,IAAM,OAAO;AACb,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AACzB,IAAM,uBAAuB;AAE7B,IAAM,iBAAiB;AAEvB,IAAM,eAAe;AAErB,IAAM,mBAAmB,KAAK;AAM9B,IAAM,gBAA8D;AAAA,EAClE,KAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,MAAM;AAAA,EAAkB,OAAO;AAAA,EAC/H,MAAM;AAAA,EAAY,OAAO;AAAA,EACzB,MAAM;AAAA,EAA0B,MAAM;AAAA,EACtC,MAAM;AAAA,EAAoB,MAAM;AAAA,EAChC,MAAM;AAAA,EACN,MAAM;AACR;AACA,IAAM,cAAc,CAAC,SACnB,OAAO,SAAS,YAAY,OAAO,UAAU,eAAe,KAAK,eAAe,IAAI,IAAI,cAAc,IAAI,IAAI;AAqChH,IAAM,OAAO,CAAC,MAA+B,OAAO,MAAM,YAAY,aAAa,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,OAAO,MAAM,YAAY,OAAO,cAAc,CAAC,KAAK,KAAK,IAAI,OAAO,CAAC,IAAI;AAClL,IAAM,SAAS,CAAC,MAA4B,OAAO,MAAM,Y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