@anywalletkit/protocol-swap2-uniswap 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/addresses.ts","../src/provider.ts","../src/activity.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./addresses.js\";\nexport * from \"./provider.js\";\nexport {UniswapSwap2Protocol} from \"./protocol.js\";\nexport {UniswapSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { UniswapSwap2Config } from \"./protocol.js\"\n","import {decodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\n\n/**\n * Uniswap v3 deployments this module trusts: the UniswapV3Factory, QuoterV2 and\n * SwapRouter02 that Uniswap's deployments.json lists as active on each chain\n * (re-checked 2026-11-04). Every entry was checked on-chain: SwapRouter02.factory()\n * and QuoterV2.factory() both return `factory`, and both report `weth` as WETH9\n * (on Celo both report 0x0 — see `nativeWrap`).\n * The provider re-checks the same facts once per chain at runtime before quoting\n * (see `verifyDeployment`).\n */\nexport interface UniswapDeployment {\n factory: `0x${string}`;\n quoter: `0x${string}`;\n router: `0x${string}`;\n /** The chain's wrapped native token (WETH, WBNB, WPOL, WAVAX) — on a chain\n * without one (Celo), the hop token used for two-hop routes instead. */\n weth: `0x${string}`;\n /** false: the router has no WETH9 (reports 0x0) — no native in/out, the coin is an ERC-20 there. */\n nativeWrap?: false;\n}\n\nexport const UNISWAP_V3: Readonly<Record<number, UniswapDeployment>> = Object.freeze({\n 1: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\"},\n 10: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x4200000000000000000000000000000000000006\"},\n 56: {factory: \"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7\", quoter: \"0x78D78E420Da98ad378D7799bE8f4AF69033EB077\", router: \"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2\", weth: \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"},\n 137: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270\"},\n 8453: {factory: \"0x33128a8fC17869897dcE68Ed026d694621f6FDfD\", quoter: \"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a\", router: \"0x2626664c2603336E57B271c5C0b26F421741e481\", weth: \"0x4200000000000000000000000000000000000006\"},\n 42161: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1\"},\n // zkSync Era and Celo: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04. Celo's\n // router and quoter report WETH9 0x0, so `weth` there is the CELO ERC-20, used only as the two-hop token.\n 324: {factory: \"0x8FdA5a7a8dCA67BBcDd10F02Fa0649A937215422\", quoter: \"0x8Cb537fc92E26d8EBBb760E632c95484b6Ea3e28\", router: \"0x99c56385daBCE3E81d8499d0b8d0257aBC07E8A3\", weth: \"0x5AEa5775959fBC2557Cc8789bC1bf90A239D9a91\"},\n 42220: {factory: \"0xAfE208a311B21f13EF87E33A90049fC17A7acDEc\", quoter: \"0x82825d0554fA07f7FC52Ab63c961F330fdEFa8E8\", router: \"0x5615CDAb10dc425a742d643d949a7F474C01abc4\", weth: \"0x471EcE3750Da237f93B8E339c536989b8978a438\", nativeWrap: false},\n // Unichain, Monad, Linea: factory, QuoterV2 and SwapRouter02 as Uniswap's deployments.json lists them (status\n // active), verified on-chain 2026-11-04: router + quoter report the factory and WETH9, and the quoter's gasEstimate\n // is non-zero. The old `Quoter` on these chains (deprecated) quotes the same amounts but always reports gas 0.\n 130: {factory: \"0x1F98400000000000000000000000000000000003\", quoter: \"0x385A5cf5F83e99f7BB2852b6A19C3538b9FA7658\", router: \"0x73855d06DE49d0fe4A9c42636Ba96c62da12FF9C\", weth: \"0x4200000000000000000000000000000000000006\"},\n 143: {factory: \"0x204FAca1764B154221e35c0d20aBb3c525710498\", quoter: \"0x661E93cca42AfacB172121EF892830cA3b70F08d\", router: \"0xfE31F71C1b106EAc32F1A19239c9a9A72ddfb900\", weth: \"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A\"},\n 59144: {factory: \"0x31FAfd4889FA1269F7a13A66eE0fB458f27D72A9\", quoter: \"0x42bE4D6527829FeFA1493e1fb9F3676d2425C3C1\", router: \"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a\", weth: \"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f\"},\n // World Chain, Ink, X Layer: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04\n // (router + quoter report the factory and WETH9; X Layer's router wraps WOKB).\n 480: {factory: \"0x7a5028BDa40e7B173C278C5342087826455ea25a\", quoter: \"0x10158D43e6cc414deE1Bd1eB0EfC6a5cBCfF244c\", router: \"0x091AD9e2e6e5eD44c1c66dB50e49A601F9f36cF6\", weth: \"0x4200000000000000000000000000000000000006\"},\n 57073: {factory: \"0x640887A9ba3A9C53Ed27D0F7e8246A4F933f3424\", quoter: \"0x96b572D2d880cf2Fa2563651BD23ADE6f5516652\", router: \"0x177778F19E89dD1012BdBe603F144088A95C4B53\", weth: \"0x4200000000000000000000000000000000000006\"},\n 196: {factory: \"0x4B2ab38DBF28D31D467aA8993f6c2585981D6804\", quoter: \"0xD1b797D92d87B688193A2B976eFc8D577D204343\", router: \"0x4f0C28f5926AFDA16bf2506D5D9e57Ea190f9bcA\", weth: \"0xe538905cf8410324e03A5A23C1c177a474D59b2b\"},\n // Robinhood Chain: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04.\n 4663: {factory: \"0x1f7d7550B1b028f7571E69A784071F0205FD2EfA\", quoter: \"0x33e885eD0Ec9bF04EcfB19341582aADCb4c8A9E7\", router: \"0xCaf681a66D020601342297493863E78C959E5cb2\", weth: \"0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73\"},\n 43114: {factory: \"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD\", quoter: \"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F\", router: \"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE\", weth: \"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7\"},\n});\n\n/** Pool fee tiers probed for every hop (0.01%, 0.05%, 0.3%, 1%). */\nexport const FEE_TIERS = [100, 500, 3000, 10000] as const;\n/** Two-hop routes go through these (when the catalog knows them on the chain). USDT0 is the dollar pair on chains\n * without a native USDT (Ink, Unichain, Monad, X Layer, Arbitrum…): on Ink the WETH/USDC pools are dust, and\n * WETH → USDT0 → USDC is the only route with liquidity (matrix v8, 2026-11-07). */\nexport const HOP_SYMBOLS = [\"WETH\", \"USDC\", \"USDT\", \"USDT0\"] as const;\n/** SwapRouter02 recipient sentinel: \"keep the output in the router\" (then unwrapWETH9). */\nexport const ADDRESS_THIS = \"0x0000000000000000000000000000000000000002\";\n\n/** The SwapRouter02 entry points this module writes (and the deployment probes). */\nexport const ROUTER_ABI = parseAbi([\n \"function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)\",\n \"function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)\",\n \"function unwrapWETH9(uint256 amountMinimum, address recipient) payable\",\n \"function refundETH() payable\",\n \"function multicall(uint256 deadline, bytes[] data) payable returns (bytes[] results)\",\n \"function factory() view returns (address)\",\n \"function WETH9() view returns (address)\",\n]);\n/** Most pools one `exactInput` path may cross: the provider builds direct and one-hop (two-pool) routes only. */\nconst MAX_PATH_POOLS = 2;\n\n/**\n * The swap a Uniswap quote's router call makes, opened on the client against the app's own request (scan 2026-10-28,\n * F1): one `multicall(deadline, legs)` on the chain's pinned SwapRouter02 whose legs are exactly one `exactInputSingle`\n * or `exactInput` — then `unwrapWETH9` for a native output — selling exactly the input of the source token (WETH for a\n * native input, paid as `value`) for the destination token, with `amountOutMinimum` the quote's minimum, paid to the\n * recipient (or kept in the router and unwrapped to the recipient for that same minimum). A native input may end with\n * `refundETH()`, which returns any unspent `value` to the sender (a provider builds it only with `refundNativeInput`,\n * so it is not required). `pull`, `sweepToken` and every other router call are refused. The reason it fails, or null.\n */\nexport function uniswapVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n const id = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;\n const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : undefined;\n if (!d || params.destChain !== params.sourceChain) return \"not a same-chain swap on a pinned Uniswap deployment\";\n const tx = quote.txRequest;\n if (!tx?.data || !tx.to || tx.serializedTx !== undefined) return \"the quote carries no router call\";\n if (getAddress(tx.to) !== getAddress(d.router)) return `the call targets ${tx.to}, not the SwapRouter`;\n const src = sourceAssetOf(params);\n if (!src) return `unknown source token ${params.sourceToken}`;\n const nativeIn = !src.contract;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if ((nativeIn || nativeOut) && d.nativeWrap === false) return \"this chain's router has no wrapped native\";\n let tokenIn: string, tokenOut: string, recipient: string, amountIn: bigint, minOut: bigint;\n try {\n tokenIn = getAddress(nativeIn ? d.weth : src.contract!);\n tokenOut = getAddress(nativeOut ? d.weth : params.destToken);\n recipient = getAddress(params.destAddress);\n amountIn = BigInt(params.amountIn);\n minOut = BigInt(quote.minDestAmount);\n } catch {\n return \"the request does not name EVM tokens, a recipient and amounts\";\n }\n if (nativeIn ? BigInt(tx.value ?? \"0\") !== amountIn || tx.approvalAddress !== undefined\n : BigInt(tx.value ?? \"0\") !== 0n || !tx.approvalAddress || getAddress(tx.approvalAddress) !== getAddress(d.router)) {\n return nativeIn ? \"a native input is paid as exactly the input in value, with no approval\" : \"a token input attaches no value and approves the SwapRouter\";\n }\n let legs: readonly Hex[];\n try {\n const outer = decodeFunctionData({abi: ROUTER_ABI, data: tx.data as Hex});\n if (outer.functionName !== \"multicall\") return `${outer.functionName} is not multicall(deadline, legs)`;\n legs = outer.args[1];\n } catch {\n return \"the router call is not multicall(deadline, legs)\";\n }\n const decode = (leg: Hex) => { try { return decodeFunctionData({abi: ROUTER_ABI, data: leg}); } catch { return null; } };\n if (nativeIn && legs.length === 2 && decode(legs[1]!)?.functionName === \"refundETH\") legs = legs.slice(0, 1);\n if (legs.length !== (nativeOut ? 2 : 1)) return `the multicall has ${legs.length} legs, not a swap${nativeOut ? \" and an unwrap\" : nativeIn ? \" (and a refund)\" : \"\"}`;\n const swap = decode(legs[0]!);\n const swapTo = nativeOut ? ADDRESS_THIS : recipient;\n if (swap?.functionName === \"exactInputSingle\") {\n const a = swap.args[0];\n if (getAddress(a.tokenIn) !== tokenIn || getAddress(a.tokenOut) !== tokenOut) return \"the swap trades other tokens\";\n if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut || a.sqrtPriceLimitX96 !== 0n) return \"the swap's input, minimum or price limit is not the quote's\";\n if (getAddress(a.recipient) !== getAddress(swapTo)) return `the swap pays ${a.recipient}, not the recipient`;\n } else if (swap?.functionName === \"exactInput\") {\n const a = swap.args[0];\n const path = a.path.slice(2);\n const pools = (path.length / 2 - 20) / 23;\n if (!/^[0-9a-fA-F]*$/.test(path) || !Number.isInteger(pools) || pools < 1 || pools > MAX_PATH_POOLS) return \"the swap path is not 1–2 pools\";\n if (getAddress(`0x${path.slice(0, 40)}`) !== tokenIn || getAddress(`0x${path.slice(-40)}`) !== tokenOut) return \"the swap path trades other tokens\";\n if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return \"the swap's input or minimum is not the quote's\";\n if (getAddress(a.recipient) !== getAddress(swapTo)) return `the swap pays ${a.recipient}, not the recipient`;\n } else {\n return `${swap?.functionName ?? \"an unknown call\"} is not exactInputSingle / exactInput`;\n }\n if (nativeOut) {\n const unwrap = decode(legs[1]!);\n if (unwrap?.functionName !== \"unwrapWETH9\") return `${unwrap?.functionName ?? \"an unknown call\"} is not unwrapWETH9`;\n if (unwrap.args[0] !== minOut || getAddress(unwrap.args[1]) !== recipient) return \"the unwrap pays someone else or less than the minimum\";\n }\n return null;\n}\n\n/**\n * The SwapRouter a Uniswap swap calls and approves on a chain (the shipped {@link UNISWAP_V3} table), and\n * {@link uniswapVerifyQuote} — the app's pins for `remoteProvider({name: \"uniswap\", baseUrl, ...uniswapPins})` (scan\n * 2026-10-27 modules, F9; scan 2026-10-28, F1).\n */\nexport const uniswapPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => uniswapRouterFor(chain),\n spenders: (chain: string): readonly string[] => uniswapRouterFor(chain),\n verifyQuote: uniswapVerifyQuote,\n});\nfunction uniswapRouterFor(chain: string): readonly string[] {\n const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;\n const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : undefined;\n return d ? [d.router] : [];\n}\n","import {decodeFunctionResult, encodeFunctionData, encodePacked, getAddress, parseAbi, type Hex} from \"viem\";\nimport {describeUniswapActivity} from \"./activity.js\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\nimport {evmRef, isEvm, timeoutSignal, sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Asset, CrossChainProvider, IntentRef, IntentStatus, Quote, QuoteParams, UnsignedTx} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {ADDRESS_THIS, FEE_TIERS, HOP_SYMBOLS, ROUTER_ABI, UNISWAP_V3, type UniswapDeployment} from \"./addresses.js\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\n/**\n * Uniswap v3, straight from the contracts — the permissionless swap venue.\n *\n * Quote: QuoterV2 via `eth_call` (one JSON-RPC batch: every fee tier direct,\n * plus two-hop routes through WETH / USDC / USDT / USDT0). Execution: SwapRouter02\n * `multicall(deadline, …)` — `exactInputSingle` or `exactInput`, native input\n * wrapped by the router (`value`, then `refundETH()` when `refundNativeInput`), native output kept in the\n * router and paid out with `unwrapWETH9(min, recipient)`. No API key, no Uniswap\n * frontend, no aggregator: if the pools are live, the swap works.\n *\n * Same-chain only. ERC-20 sources approve exactly the input to the router\n * (`approvalAddress`); the engine handles that leg.\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** The router itself enforces amountOutMinimum and the deadline, and preflight\n * re-quotes the exact route before broadcast — so the quote may outlive an\n * approval being mined (an Ethereum approve + head wait took >30 s live). */\nconst DEFAULT_TTL_MS = 300_000;\nconst DEFAULT_DEADLINE_S = 600;\n/** Least gas one v3 pool swap can use (cold pool storage + two token transfers cost far more); a quoter figure\n * under this per pool does not measure the swap. */\nconst MIN_POOL_GAS = 20_000n;\n/** The pool's price bounds the router swaps to when no limit is set (TickMath MIN_SQRT_RATIO + 1, MAX_SQRT_RATIO - 1).\n * A quote that leaves a pool at one of them ran the pool dry: it is a partial fill of a smaller input, not a quote for\n * this one (matrix v8, Ink: 0.01 ETH \"quoted\" 1 raw USDC out of a pool holding 168). */\nconst SQRT_PRICE_FLOOR = 4295128740n;\nconst SQRT_PRICE_CEIL = 1461446703485210103287273052203988822378723970341n;\nconst PARTIAL_FILL = \"pool liquidity runs out before the full amount (partial fill)\";\n\nconst QUOTER_ABI = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n \"function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)\",\n \"function factory() view returns (address)\",\n \"function WETH9() view returns (address)\",\n]);\n\n/** A quoter result's output, the pool price(s) it leaves behind and its gas figure, for either quote shape. */\nfunction decodeQuote(single: boolean, raw: Hex): {out: bigint; drained: boolean; gas: bigint} {\n const [out, after, , gas] = decodeFunctionResult({abi: QUOTER_ABI, functionName: single ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw}) as readonly [bigint, bigint | readonly bigint[], unknown, bigint];\n const prices = typeof after === \"bigint\" ? [after] : after;\n return {out, gas, drained: prices.length === 0 || prices.some((p) => p <= SQRT_PRICE_FLOOR || p >= SQRT_PRICE_CEIL)};\n}\n\nexport interface UniswapProviderConfig {\n enabled?: boolean;\n /** JSON-RPC endpoints per EVM chain id, tried in order. A chain without one is not offered. */\n rpcUrls: Readonly<Record<number, readonly string[]>>;\n /** Slippage when the caller names none (bps). Default 50. */\n defaultSlippageBps?: number;\n /** Local quote lifetime (must cover an approval being mined). Default 5 min. */\n quoteTtlMs?: number;\n /** Seconds the router accepts the swap after the quote (multicall deadline). Default 600. */\n deadlineSeconds?: number;\n /** Override the deployments (tests, new chains). Still verified on-chain before use. */\n deployments?: Readonly<Record<number, UniswapDeployment>>;\n /**\n * End a native-input swap with `refundETH()`, so `value` the pool did not take goes back to the sender in the same\n * transaction. Default false: clients pinned to `uniswapVerifyQuote` before 0.4.2 refuse the extra leg, so a server\n * turns this on only once the apps it serves verify with ≥ 0.4.2.\n */\n refundNativeInput?: boolean;\n}\n\ninterface Route {\n /** Human description for the review / logs. */\n label: string;\n /** The pool fee(s) the route pays — already inside the quoted output. */\n poolFee: string;\n single?: {fee: number};\n path?: Hex;\n}\n\ntype RpcCall = {method: string; params: unknown[]};\n\n/** Largest JSON-RPC batch sent to one node (X Layer's public RPCs refuse more than 10). */\nconst RPC_BATCH_MAX = 10;\n\nexport function uniswapProvider(config: UniswapProviderConfig): CrossChainProvider {\n const deployments = config.deployments ?? UNISWAP_V3;\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const deadlineS = config.deadlineSeconds ?? DEFAULT_DEADLINE_S;\n const refundNative = config.refundNativeInput === true;\n if (!Number.isInteger(slippageDefault) || slippageDefault <= 0 || slippageDefault >= 5_000) throw new Error(\"uniswap: defaultSlippageBps must be 1..4999\");\n const verified = new Map<number, Promise<void>>();\n\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return deployments[id] && config.rpcUrls[id]?.length ? id : null;\n };\n\n /**\n * JSON-RPC batch with endpoint failover; each slot is the result or null (reverted / errored).\n * Sent in chunks of RPC_BATCH_MAX: some public nodes cap a batch (X Layer's at 10 calls).\n */\n async function rpc(chainId: number, calls: RpcCall[], signal?: AbortSignal): Promise<(unknown | null)[]> {\n if (calls.length <= RPC_BATCH_MAX) return rpcBatch(chainId, calls, signal);\n const chunks: RpcCall[][] = [];\n for (let i = 0; i < calls.length; i += RPC_BATCH_MAX) chunks.push(calls.slice(i, i + RPC_BATCH_MAX));\n return (await Promise.all(chunks.map((c) => rpcBatch(chainId, c, signal)))).flat();\n }\n\n async function rpcBatch(chainId: number, calls: RpcCall[], signal?: AbortSignal): Promise<(unknown | null)[]> {\n let lastErr: unknown;\n for (const url of config.rpcUrls[chainId] ?? []) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify(calls.map((c, id) => ({jsonrpc: \"2.0\", id, ...c}))),\n signal: signal ?? timeoutSignal(12_000),\n });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n const body = (await res.json()) as {id: number; result?: unknown; error?: unknown}[] | {error?: {message?: string}};\n if (!Array.isArray(body)) throw new Error(body.error?.message ?? \"batch refused\");\n const out: (unknown | null)[] = calls.map(() => null);\n for (const r of body) if (typeof r.id === \"number\" && r.id < out.length && r.error === undefined) out[r.id] = r.result ?? null;\n return out;\n } catch (e) {\n lastErr = e;\n }\n }\n throw new Error(`uniswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`);\n }\n\n const call = (to: string, data: Hex): RpcCall => ({method: \"eth_call\", params: [{to, data}, \"latest\"]});\n\n /** The pinned addresses still describe one deployment (router + quoter agree on factory and WETH). */\n function verifyDeployment(chainId: number): Promise<void> {\n let p = verified.get(chainId);\n if (!p) {\n const d = deployments[chainId]!;\n p = (async () => {\n const f = encodeFunctionData({abi: ROUTER_ABI, functionName: \"factory\"});\n const w = encodeFunctionData({abi: ROUTER_ABI, functionName: \"WETH9\"});\n const [rf, rw, qf, qw] = await rpc(chainId, [call(d.router, f), call(d.router, w), call(d.quoter, f), call(d.quoter, w)]);\n const addr = (r: unknown) => (typeof r === \"string\" && r.length >= 42 ? getAddress(`0x${r.slice(-40)}`) : null);\n const wrapped = d.nativeWrap === false ? getAddress(ZERO) : getAddress(d.weth);\n const ok = [rf, qf].every((r) => addr(r) === getAddress(d.factory)) && addr(rw) === wrapped && addr(qw) === wrapped;\n if (!ok) throw new Error(`uniswap: the router/quoter on chain ${chainId} do not match the pinned deployment — refusing`);\n })();\n p.catch(() => verified.delete(chainId));\n verified.set(chainId, p);\n }\n return p;\n }\n\n /** Every candidate route for tokenIn → tokenOut on this chain. */\n function routes(chainId: number, caip2: string, tokenIn: Hex, tokenOut: Hex): Route[] {\n const d = deployments[chainId]!;\n const out: Route[] = FEE_TIERS.map((fee) => ({label: `direct ${fee / 10_000}%`, poolFee: `${fee / 10_000}%`, single: {fee}}));\n const mids = new Set<string>();\n for (const sym of HOP_SYMBOLS) {\n const mid = sym === \"WETH\" ? d.weth : ccAsset(caip2, sym)?.contract;\n if (!mid || !/^0x[0-9a-fA-F]{40}$/.test(mid)) continue;\n const m = getAddress(mid);\n if (m === getAddress(tokenIn) || m === getAddress(tokenOut) || mids.has(m)) continue;\n mids.add(m);\n for (const f1 of [100, 500, 3000]) {\n for (const f2 of [100, 500, 3000]) {\n out.push({label: `via ${sym} ${f1 / 10_000}% → ${f2 / 10_000}%`, poolFee: `${f1 / 10_000}% + ${f2 / 10_000}%`, path: encodePacked([\"address\", \"uint24\", \"address\", \"uint24\", \"address\"], [tokenIn, f1, m, f2, tokenOut])});\n }\n }\n }\n return out;\n }\n\n return {\n name: \"uniswap\",\n describeActivity: (tx, ctx) => describeUniswapActivity(tx, ctx, config.deployments ?? UNISWAP_V3),\n supportsSameChain: true,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute(from: Asset, to: Asset): boolean {\n return from.chain === to.chain && chainIdOf(from.chain) !== null;\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string): null => {\n params.onRefusal?.(`uniswap: ${why}`);\n return null;\n };\n if (params.flex) return refuse(\"amount-flexible deposits are not supported\");\n if (params.sourceChain !== params.destChain) return refuse(\"same-chain swaps only\");\n const chainId = chainIdOf(params.sourceChain);\n if (chainId === null) return refuse(`no Uniswap v3 deployment or RPC for ${params.sourceChain}`);\n const d = deployments[chainId]!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`);\n const nativeIn = !src.contract;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if ((nativeIn || nativeOut) && d.nativeWrap === false) return refuse(\"this chain's router has no wrapped native — swap the coin's ERC-20 instead\");\n if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse(\"destination token must be an EVM address\");\n if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse(\"recipient must be an EVM address\");\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 tokenIn = getAddress(nativeIn ? d.weth : src.contract!);\n const tokenOut = getAddress(nativeOut ? d.weth : params.destToken);\n if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? \"that is a wrap/unwrap, not a swap\" : \"same token in and out\");\n\n try {\n await verifyDeployment(chainId);\n const candidates = routes(chainId, params.sourceChain, tokenIn, tokenOut);\n const results = await rpc(\n chainId,\n candidates.map((r) =>\n call(\n d.quoter,\n r.single\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn, tokenOut, amountIn, fee: r.single.fee, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [r.path!, amountIn]}),\n ),\n ),\n signal,\n );\n let best: {route: Route; out: bigint; gas: bigint} | null = null;\n let partial = false;\n results.forEach((raw, i) => {\n if (typeof raw !== \"string\" || raw === \"0x\") return;\n const r = candidates[i]!;\n try {\n const {out, drained, gas} = decodeQuote(!!r.single, raw as Hex);\n if (out <= 0n) return;\n if (drained) {\n partial = true;\n return;\n }\n if (!best || out > best.out) best = {route: r, out, gas};\n } catch {\n /* a malformed slot is just not a candidate */\n }\n });\n if (!best) return refuse(partial ? PARTIAL_FILL : \"no Uniswap v3 pool route for this pair and amount\");\n const {route, out, gas} = best as {route: Route; out: bigint; gas: bigint};\n\n // Price impact (SDK-127): a probe 1/1000 the size on the same route gives the pool's\n // marginal rate; the full-size rate's shortfall against it is the impact. Pool fees\n // are paid on both sides, so they cancel. Informational — the Oct 16 run swapped\n // 16.78 USDT into 0.0099 USDT0 through an empty pool and nothing said a word.\n let priceImpactBps: number | undefined;\n const probeIn = amountIn / 1000n;\n if (probeIn > 0n) {\n try {\n const [raw] = await rpc(\n chainId,\n [call(d.quoter, route.single\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn, tokenOut, amountIn: probeIn, fee: route.single.fee, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [route.path!, probeIn]}))],\n signal,\n );\n if (typeof raw === \"string\" && raw !== \"0x\") {\n const [probeOut] = decodeFunctionResult({abi: QUOTER_ABI, functionName: route.single ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw as Hex}) as readonly [bigint];\n if (probeOut > 0n) {\n const ratioBps = (out * probeIn * 10_000n) / (probeOut * amountIn); // (out/amountIn) ÷ (probeOut/probeIn), in bps\n priceImpactBps = Math.max(0, bigintToNumber(10_000n - ratioBps));\n }\n }\n } catch {\n /* the quote stands; impact is information, not a gate */\n }\n }\n\n const bps = params.slippageBps ?? slippageDefault;\n const minOut = (out * BigInt(10_000 - bps)) / 10_000n;\n if (minOut <= 0n) return refuse(`the minimum output rounds to 0 (quoted ${out} at ${bps} bps slippage) — the amount is too small for this pool`);\n if (params.minAmountOut !== undefined && minOut < BigInt(params.minAmountOut)) {\n return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`);\n }\n const recipient = getAddress(params.destAddress);\n const swapTo = nativeOut ? ADDRESS_THIS : recipient;\n const swap = route.single\n ? encodeFunctionData({abi: ROUTER_ABI, functionName: \"exactInputSingle\", args: [{tokenIn, tokenOut, fee: route.single.fee, recipient: swapTo as Hex, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: ROUTER_ABI, functionName: \"exactInput\", args: [{path: route.path!, recipient: swapTo as Hex, amountIn, amountOutMinimum: minOut}]});\n const legs: Hex[] = [swap];\n if (nativeOut) legs.push(encodeFunctionData({abi: ROUTER_ABI, functionName: \"unwrapWETH9\", args: [minOut, recipient]}));\n // The router wraps only what the pool takes: `value` it did not spend would stay in the router for anyone to\n // sweep. refundETH() pays it back to the sender in the same transaction (nothing to send on a full fill). Opt-in\n // (`refundNativeInput`) until every pinned client accepts the leg; the preflight partial-fill check and the\n // minimum already make an unspent remainder revert rather than stay behind.\n const refund = nativeIn && refundNative;\n if (refund) legs.push(encodeFunctionData({abi: ROUTER_ABI, functionName: \"refundETH\"}));\n const deadline = BigInt(Math.floor(Date.now() / 1000) + deadlineS);\n const data = encodeFunctionData({abi: ROUTER_ABI, functionName: \"multicall\", args: [deadline, legs]});\n // Quoter gas covers the pool hops; the router's own overhead and an unwrap ride on top. A figure no real pool\n // swap can cost (0 from a quoter that does not measure gas) is no figure: the limit is then left to the\n // wallet, which estimates the exact call with headroom right before broadcast, as for THORChain and Chainflip.\n // A limit derived from it would be the bare overhead, and the swap would run out of gas on chain.\n const pools = route.single ? 1n : BigInt((route.path!.length - 42) / 46);\n const gasLimit = gas >= MIN_POOL_GAS * pools ? (gas * 3n) / 2n + 120_000n + (nativeOut ? 40_000n : 0n) + (refund ? 10_000n : 0n) : undefined;\n\n return {\n provider: \"uniswap\",\n intentId: `uniswap:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: d.router,\n data,\n value: nativeIn ? amountIn.toString() : \"0\",\n chainId,\n ...(gasLimit !== undefined ? {gasLimit: gasLimit.toString()} : {}),\n ...(nativeIn ? {} : {approvalAddress: d.router}),\n },\n sourceAmount: amountIn.toString(),\n destAmount: out.toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n etaSeconds: 15,\n reliability: 0.98,\n validUntilMs: Date.now() + ttl,\n providerData: {\n route: route.label,\n poolFee: route.poolFee,\n router: d.router,\n tokenIn,\n tokenOut,\n amountIn: amountIn.toString(),\n minOut: minOut.toString(),\n ...(route.single ? {fee: String(route.single.fee)} : {path: route.path!}),\n ...(priceImpactBps !== undefined ? {priceImpactBps: String(priceImpactBps)} : {}),\n },\n };\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, \"\") : String(e));\n }\n },\n\n /**\n * Right before broadcast (after any approval): re-quote the SAME route on\n * chain. If the pool now pays less than the signed minimum, the swap would\n * only revert and burn gas — refuse it here with the reason instead. A pool\n * that no longer holds enough for the whole input (it would fill part of it)\n * is refused the same way.\n */\n async preflightDeposit(quote: Quote): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const d = deployments[chainId];\n const pd = quote.providerData ?? {};\n if (!d || !pd.amountIn || !pd.minOut || !pd.tokenIn || !pd.tokenOut) return;\n const data = pd.fee\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn: pd.tokenIn as Hex, tokenOut: pd.tokenOut as Hex, amountIn: BigInt(pd.amountIn), fee: Number(pd.fee), sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [pd.path as Hex, BigInt(pd.amountIn)]});\n const [raw] = await rpc(chainId, [call(d.quoter, data)]);\n if (typeof raw !== \"string\" || raw === \"0x\") throw new Error(\"uniswap: the pool no longer quotes this route — refresh and try again\");\n const {out, drained} = decodeQuote(!!pd.fee, raw as Hex);\n if (drained) throw new Error(`uniswap: ${PARTIAL_FILL} — the pool can no longer take this swap. Nothing was sent; refresh the quote.`);\n if (out < BigInt(pd.minOut)) {\n throw new Error(`uniswap: price moved — the pool now pays ${out}, under your minimum ${pd.minOut}. Nothing was sent; refresh the quote.`);\n }\n },\n\n async buildDeposit(quote: Quote): Promise<UnsignedTx> {\n const tx = quote.txRequest;\n if (!tx?.to || !tx.data) throw new Error(\"swap2: Uniswap quote has no transaction request\");\n return {\n chain: \"\",\n to: tx.to,\n value: tx.value ?? \"0\",\n data: tx.data,\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n };\n },\n\n /** Same-chain: the swap is done when its transaction is mined successfully. */\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!deployments[chainId] || !config.rpcUrls[chainId]?.length) return {state: \"pending\"};\n try {\n const [receipt] = (await rpc(chainId, [{method: \"eth_getTransactionReceipt\", params: [ref.sourceTxHash]}])) as [{status?: string} | null];\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Uniswap v3: a call into the chain's SwapRouter02\n * (the deployment table, or the caller's override) with one of the router's\n * swap entry points → `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 {UNISWAP_V3, type UniswapDeployment} from \"./addresses.js\";\n\nexport const UNISWAP_MODULE = \"@anywalletkit/protocol-swap2-uniswap\";\n\n/** SwapRouter02 entry points (`viem toFunctionSelector`, 2026-10-14). */\nexport const UNISWAP_ROUTER_SELECTORS: ReadonlySet<string> = new Set([\n \"0x5ae401dc\", // multicall(uint256 deadline, bytes[] data)\n \"0xac9650d8\", // multicall(bytes[] data)\n \"0x1f0464d1\", // multicall(bytes32 previousBlockhash, bytes[] data)\n \"0x04e45aaf\", // exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))\n \"0xb858183f\", // exactInput((bytes,address,uint256,uint256))\n \"0x5023b4df\", // exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160))\n \"0x09b81346\", // exactOutput((bytes,address,uint256,uint256))\n]);\n\nexport function describeUniswapActivity(\n tx: ChainTx,\n ctx: DescribeActivityContext,\n deployments: Readonly<Record<number, UniswapDeployment>> = UNISWAP_V3,\n): ActivityItem | null {\n if (!isEvm(tx.chain)) return null;\n const deployment = deployments[evmRef(tx.chain)];\n if (!deployment || !matchesCall(tx, [deployment.router], UNISWAP_ROUTER_SELECTORS)) return null;\n return describeSwapLike(tx, ctx, {protocol: UNISWAP_MODULE, subtitle: `Uniswap v3 · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {UNISWAP_V3} from \"./addresses.js\";\nimport {uniswapProvider, type UniswapProviderConfig} from \"./provider.js\";\n\nexport interface UniswapSwap2Config extends Swap2EngineConfig, UniswapProviderConfig {}\n\n/** Uniswap v3 as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class UniswapSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n private readonly _rpcUrls: UniswapProviderConfig[\"rpcUrls\"];\n private readonly _deployments: NonNullable<UniswapProviderConfig[\"deployments\"]>;\n constructor(account: Swap2Account | undefined, config: UniswapSwap2Config) {\n super(account, config);\n this.provider = uniswapProvider(config);\n this._rpcUrls = config.rpcUrls ?? {};\n this._deployments = config.deployments ?? UNISWAP_V3;\n }\n protected override chainSupported(caip2: string): boolean {\n return isEvm(caip2) && !!this._deployments[evmRef(caip2)] && !!this._rpcUrls[evmRef(caip2)]?.length;\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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,qBAAO,KAAK,CAAC,GAAG;AAAA,EAC/F;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,cAAc,WAAW,KAAK,eAAe,SAAS;AAAA,EAC/D;AACF;","names":["import_viem","import_util","import_util","out","gas","import_util"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/addresses.ts","../src/provider.ts","../src/activity.ts","../src/protocol.ts"],"sourcesContent":["export * from \"./addresses.js\";\nexport * from \"./provider.js\";\nexport {UniswapSwap2Protocol} from \"./protocol.js\";\nexport {UniswapSwap2Protocol as default} from \"./protocol.js\";\nexport * from \"./activity.js\";\nexport type { UniswapSwap2Config } from \"./protocol.js\"\n","import {decodeFunctionData, getAddress, parseAbi, type Hex} from \"viem\";\nimport {sourceAssetOf} from \"@anywalletkit/protocol-swap2-core/util\";\nimport type {Quote, QuoteParams, RemotePins} from \"@anywalletkit/protocol-swap2-core/types\";\nimport {refusalNotes} from \"@anywalletkit/protocol-swap2-core/errors\";\n\n/**\n * Uniswap v3 deployments this module trusts: the UniswapV3Factory, QuoterV2 and\n * SwapRouter02 that Uniswap's deployments.json lists as active on each chain\n * (re-checked 2026-11-04). Every entry was checked on-chain: SwapRouter02.factory()\n * and QuoterV2.factory() both return `factory`, and both report `weth` as WETH9\n * (on Celo both report 0x0 — see `nativeWrap`).\n * The provider re-checks the same facts once per chain at runtime before quoting\n * (see `verifyDeployment`).\n */\nexport interface UniswapDeployment {\n factory: `0x${string}`;\n quoter: `0x${string}`;\n router: `0x${string}`;\n /** The chain's wrapped native token (WETH, WBNB, WPOL, WAVAX) — on a chain\n * without one (Celo), the hop token used for two-hop routes instead. */\n weth: `0x${string}`;\n /** false: the router has no WETH9 (reports 0x0) — no native in/out, the coin is an ERC-20 there. */\n nativeWrap?: false;\n}\n\nexport const UNISWAP_V3: Readonly<Record<number, UniswapDeployment>> = Object.freeze({\n 1: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2\"},\n 10: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x4200000000000000000000000000000000000006\"},\n 56: {factory: \"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7\", quoter: \"0x78D78E420Da98ad378D7799bE8f4AF69033EB077\", router: \"0xB971eF87ede563556b2ED4b1C0b0019111Dd85d2\", weth: \"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c\"},\n 137: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270\"},\n 8453: {factory: \"0x33128a8fC17869897dcE68Ed026d694621f6FDfD\", quoter: \"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a\", router: \"0x2626664c2603336E57B271c5C0b26F421741e481\", weth: \"0x4200000000000000000000000000000000000006\"},\n 42161: {factory: \"0x1F98431c8aD98523631AE4a59f267346ea31F984\", quoter: \"0x61fFE014bA17989E743c5F6cB21bF9697530B21e\", router: \"0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45\", weth: \"0x82aF49447D8a07e3bd95BD0d56f35241523fBab1\"},\n // zkSync Era and Celo: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04. Celo's\n // router and quoter report WETH9 0x0, so `weth` there is the CELO ERC-20, used only as the two-hop token.\n 324: {factory: \"0x8FdA5a7a8dCA67BBcDd10F02Fa0649A937215422\", quoter: \"0x8Cb537fc92E26d8EBBb760E632c95484b6Ea3e28\", router: \"0x99c56385daBCE3E81d8499d0b8d0257aBC07E8A3\", weth: \"0x5AEa5775959fBC2557Cc8789bC1bf90A239D9a91\"},\n 42220: {factory: \"0xAfE208a311B21f13EF87E33A90049fC17A7acDEc\", quoter: \"0x82825d0554fA07f7FC52Ab63c961F330fdEFa8E8\", router: \"0x5615CDAb10dc425a742d643d949a7F474C01abc4\", weth: \"0x471EcE3750Da237f93B8E339c536989b8978a438\", nativeWrap: false},\n // Unichain, Monad, Linea: factory, QuoterV2 and SwapRouter02 as Uniswap's deployments.json lists them (status\n // active), verified on-chain 2026-11-04: router + quoter report the factory and WETH9, and the quoter's gasEstimate\n // is non-zero. The old `Quoter` on these chains (deprecated) quotes the same amounts but always reports gas 0.\n 130: {factory: \"0x1F98400000000000000000000000000000000003\", quoter: \"0x385A5cf5F83e99f7BB2852b6A19C3538b9FA7658\", router: \"0x73855d06DE49d0fe4A9c42636Ba96c62da12FF9C\", weth: \"0x4200000000000000000000000000000000000006\"},\n 143: {factory: \"0x204FAca1764B154221e35c0d20aBb3c525710498\", quoter: \"0x661E93cca42AfacB172121EF892830cA3b70F08d\", router: \"0xfE31F71C1b106EAc32F1A19239c9a9A72ddfb900\", weth: \"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A\"},\n 59144: {factory: \"0x31FAfd4889FA1269F7a13A66eE0fB458f27D72A9\", quoter: \"0x42bE4D6527829FeFA1493e1fb9F3676d2425C3C1\", router: \"0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a\", weth: \"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f\"},\n // World Chain, Ink, X Layer: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04\n // (router + quoter report the factory and WETH9; X Layer's router wraps WOKB).\n 480: {factory: \"0x7a5028BDa40e7B173C278C5342087826455ea25a\", quoter: \"0x10158D43e6cc414deE1Bd1eB0EfC6a5cBCfF244c\", router: \"0x091AD9e2e6e5eD44c1c66dB50e49A601F9f36cF6\", weth: \"0x4200000000000000000000000000000000000006\"},\n 57073: {factory: \"0x640887A9ba3A9C53Ed27D0F7e8246A4F933f3424\", quoter: \"0x96b572D2d880cf2Fa2563651BD23ADE6f5516652\", router: \"0x177778F19E89dD1012BdBe603F144088A95C4B53\", weth: \"0x4200000000000000000000000000000000000006\"},\n 196: {factory: \"0x4B2ab38DBF28D31D467aA8993f6c2585981D6804\", quoter: \"0xD1b797D92d87B688193A2B976eFc8D577D204343\", router: \"0x4f0C28f5926AFDA16bf2506D5D9e57Ea190f9bcA\", weth: \"0xe538905cf8410324e03A5A23C1c177a474D59b2b\"},\n // Robinhood Chain: as Uniswap's deployments.json lists them (status active), verified on-chain 2026-11-04.\n 4663: {factory: \"0x1f7d7550B1b028f7571E69A784071F0205FD2EfA\", quoter: \"0x33e885eD0Ec9bF04EcfB19341582aADCb4c8A9E7\", router: \"0xCaf681a66D020601342297493863E78C959E5cb2\", weth: \"0x0Bd7D308f8E1639FAb988df18A8011f41EAcAD73\"},\n 43114: {factory: \"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD\", quoter: \"0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F\", router: \"0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE\", weth: \"0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7\"},\n});\n\n/** Pool fee tiers probed for every hop (0.01%, 0.05%, 0.3%, 1%). */\nexport const FEE_TIERS = [100, 500, 3000, 10000] as const;\n/** Two-hop routes go through these (when the catalog knows them on the chain). USDT0 is the dollar pair on chains\n * without a native USDT (Ink, Unichain, Monad, X Layer, Arbitrum…): on Ink the WETH/USDC pools are dust, and\n * WETH → USDT0 → USDC is the only route with liquidity (matrix v8, 2026-11-07). */\nexport const HOP_SYMBOLS = [\"WETH\", \"USDC\", \"USDT\", \"USDT0\"] as const;\n/** SwapRouter02 recipient sentinel: \"keep the output in the router\" (then unwrapWETH9). */\nexport const ADDRESS_THIS = \"0x0000000000000000000000000000000000000002\";\n\n/** The SwapRouter02 entry points this module writes (and the deployment probes). */\nexport const ROUTER_ABI = parseAbi([\n \"function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)\",\n \"function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)\",\n \"function unwrapWETH9(uint256 amountMinimum, address recipient) payable\",\n \"function refundETH() payable\",\n \"function multicall(uint256 deadline, bytes[] data) payable returns (bytes[] results)\",\n \"function factory() view returns (address)\",\n \"function WETH9() view returns (address)\",\n]);\n/** Most pools one `exactInput` path may cross: the provider builds direct and one-hop (two-pool) routes only. */\nconst MAX_PATH_POOLS = 2;\n/** The reasons of the texts {@link uniswapVerifyQuote} returned, for `uniswapPins.reasonOf`. */\nconst notes = refusalNotes();\n\n/**\n * The swap a Uniswap quote's router call makes, opened on the client against the app's own request (scan 2026-10-28,\n * F1): one `multicall(deadline, legs)` on the chain's pinned SwapRouter02 whose legs are exactly one `exactInputSingle`\n * or `exactInput` — then `unwrapWETH9` for a native output — selling exactly the input of the source token (WETH for a\n * native input, paid as `value`) for the destination token, with `amountOutMinimum` the quote's minimum, paid to the\n * recipient (or kept in the router and unwrapped to the recipient for that same minimum). A native input may end with\n * `refundETH()`, which returns any unspent `value` to the sender (a provider builds it only with `refundNativeInput`,\n * so it is not required). `pull`, `sweepToken` and every other router call are refused. The reason it fails, or null.\n */\nexport function uniswapVerifyQuote(params: QuoteParams, quote: Quote): string | null {\n const id = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;\n const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : undefined;\n if (!d || params.destChain !== params.sourceChain) return notes.note(\"not a same-chain swap on a pinned Uniswap deployment\", \"unsupported_pair\");\n const tx = quote.txRequest;\n if (!tx?.data || !tx.to || tx.serializedTx !== undefined) return notes.note(\"the quote carries no router call\", \"policy_refused\");\n if (getAddress(tx.to) !== getAddress(d.router)) return notes.note(`the call targets ${tx.to}, not the SwapRouter`, \"vault_mismatch\");\n const src = sourceAssetOf(params);\n if (!src) return notes.note(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const nativeIn = !src.contract;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if ((nativeIn || nativeOut) && d.nativeWrap === false) return notes.note(\"this chain's router has no wrapped native\", \"unsupported_pair\");\n let tokenIn: string, tokenOut: string, recipient: string, amountIn: bigint, minOut: bigint;\n try {\n tokenIn = getAddress(nativeIn ? d.weth : src.contract!);\n tokenOut = getAddress(nativeOut ? d.weth : params.destToken);\n recipient = getAddress(params.destAddress);\n amountIn = BigInt(params.amountIn);\n minOut = BigInt(quote.minDestAmount);\n } catch {\n return \"the request does not name EVM tokens, a recipient and amounts\";\n }\n if (nativeIn ? BigInt(tx.value ?? \"0\") !== amountIn || tx.approvalAddress !== undefined\n : BigInt(tx.value ?? \"0\") !== 0n || !tx.approvalAddress || getAddress(tx.approvalAddress) !== getAddress(d.router)) {\n return notes.note(nativeIn ? \"a native input is paid as exactly the input in value, with no approval\" : \"a token input attaches no value and approves the SwapRouter\", \"policy_refused\");\n }\n let legs: readonly Hex[];\n try {\n const outer = decodeFunctionData({abi: ROUTER_ABI, data: tx.data as Hex});\n if (outer.functionName !== \"multicall\") return notes.note(`${outer.functionName} is not multicall(deadline, legs)`, \"policy_refused\");\n legs = outer.args[1];\n } catch {\n return notes.note(\"the router call is not multicall(deadline, legs)\", \"policy_refused\");\n }\n const decode = (leg: Hex) => { try { return decodeFunctionData({abi: ROUTER_ABI, data: leg}); } catch { return null; } };\n if (nativeIn && legs.length === 2 && decode(legs[1]!)?.functionName === \"refundETH\") legs = legs.slice(0, 1);\n if (legs.length !== (nativeOut ? 2 : 1)) return notes.note(`the multicall has ${legs.length} legs, not a swap${nativeOut ? \" and an unwrap\" : nativeIn ? \" (and a refund)\" : \"\"}`, \"policy_refused\");\n const swap = decode(legs[0]!);\n const swapTo = nativeOut ? ADDRESS_THIS : recipient;\n if (swap?.functionName === \"exactInputSingle\") {\n const a = swap.args[0];\n if (getAddress(a.tokenIn) !== tokenIn || getAddress(a.tokenOut) !== tokenOut) return notes.note(\"the swap trades other tokens\", \"policy_refused\");\n if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut || a.sqrtPriceLimitX96 !== 0n) return notes.note(\"the swap's input, minimum or price limit is not the quote's\", \"price_check_failed\");\n if (getAddress(a.recipient) !== getAddress(swapTo)) return notes.note(`the swap pays ${a.recipient}, not the recipient`, \"recipient_mismatch\");\n } else if (swap?.functionName === \"exactInput\") {\n const a = swap.args[0];\n const path = a.path.slice(2);\n const pools = (path.length / 2 - 20) / 23;\n if (!/^[0-9a-fA-F]*$/.test(path) || !Number.isInteger(pools) || pools < 1 || pools > MAX_PATH_POOLS) return notes.note(\"the swap path is not 1–2 pools\", \"policy_refused\");\n if (getAddress(`0x${path.slice(0, 40)}`) !== tokenIn || getAddress(`0x${path.slice(-40)}`) !== tokenOut) return notes.note(\"the swap path trades other tokens\", \"policy_refused\");\n if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return notes.note(\"the swap's input or minimum is not the quote's\", \"price_check_failed\");\n if (getAddress(a.recipient) !== getAddress(swapTo)) return notes.note(`the swap pays ${a.recipient}, not the recipient`, \"recipient_mismatch\");\n } else {\n return notes.note(`${swap?.functionName ?? \"an unknown call\"} is not exactInputSingle / exactInput`, \"policy_refused\");\n }\n if (nativeOut) {\n const unwrap = decode(legs[1]!);\n if (unwrap?.functionName !== \"unwrapWETH9\") return notes.note(`${unwrap?.functionName ?? \"an unknown call\"} is not unwrapWETH9`, \"policy_refused\");\n // One text for two checks; the reason names the one that failed (another recipient wins over the amount).\n if (unwrap.args[0] !== minOut || getAddress(unwrap.args[1]) !== recipient) return notes.note(\"the unwrap pays someone else or less than the minimum\", getAddress(unwrap.args[1]) !== recipient ? \"recipient_mismatch\" : \"price_check_failed\");\n }\n return null;\n}\n\n/**\n * The SwapRouter a Uniswap swap calls and approves on a chain (the shipped {@link UNISWAP_V3} table), and\n * {@link uniswapVerifyQuote} — the app's pins for `remoteProvider({name: \"uniswap\", baseUrl, ...uniswapPins})` (scan\n * 2026-10-27 modules, F9; scan 2026-10-28, F1). `reasonOf` classifies the texts `uniswapVerifyQuote` returned.\n */\nexport const uniswapPins: RemotePins = Object.freeze({\n callTargets: (chain: string): readonly string[] => uniswapRouterFor(chain),\n spenders: (chain: string): readonly string[] => uniswapRouterFor(chain),\n verifyQuote: uniswapVerifyQuote,\n reasonOf: (refusal: string) => notes.reasonOf(refusal),\n});\nfunction uniswapRouterFor(chain: string): readonly string[] {\n const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;\n const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : undefined;\n return d ? [d.router] : [];\n}\n","import {decodeFunctionResult, encodeFunctionData, encodePacked, getAddress, parseAbi, type Hex} from \"viem\";\nimport {describeUniswapActivity} from \"./activity.js\";\nimport {ccAsset} from \"@anywalletkit/swap2-assets\";\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 {ADDRESS_THIS, FEE_TIERS, HOP_SYMBOLS, ROUTER_ABI, UNISWAP_V3, type UniswapDeployment} from \"./addresses.js\";\nimport {bigintToNumber} from \"@anywalletkit/core\";\n\n/**\n * Uniswap v3, straight from the contracts — the permissionless swap venue.\n *\n * Quote: QuoterV2 via `eth_call` (one JSON-RPC batch: every fee tier direct,\n * plus two-hop routes through WETH / USDC / USDT / USDT0). Execution: SwapRouter02\n * `multicall(deadline, …)` — `exactInputSingle` or `exactInput`, native input\n * wrapped by the router (`value`, then `refundETH()` when `refundNativeInput`), native output kept in the\n * router and paid out with `unwrapWETH9(min, recipient)`. No API key, no Uniswap\n * frontend, no aggregator: if the pools are live, the swap works.\n *\n * Same-chain only. ERC-20 sources approve exactly the input to the router\n * (`approvalAddress`); the engine handles that leg.\n */\n\nconst ZERO = \"0x0000000000000000000000000000000000000000\";\nconst DEFAULT_SLIPPAGE_BPS = 50;\n/** The router itself enforces amountOutMinimum and the deadline, and preflight\n * re-quotes the exact route before broadcast — so the quote may outlive an\n * approval being mined (an Ethereum approve + head wait took >30 s live). */\nconst DEFAULT_TTL_MS = 300_000;\nconst DEFAULT_DEADLINE_S = 600;\n/** Least gas one v3 pool swap can use (cold pool storage + two token transfers cost far more); a quoter figure\n * under this per pool does not measure the swap. */\nconst MIN_POOL_GAS = 20_000n;\n/** The pool's price bounds the router swaps to when no limit is set (TickMath MIN_SQRT_RATIO + 1, MAX_SQRT_RATIO - 1).\n * A quote that leaves a pool at one of them ran the pool dry: it is a partial fill of a smaller input, not a quote for\n * this one (matrix v8, Ink: 0.01 ETH \"quoted\" 1 raw USDC out of a pool holding 168). */\nconst SQRT_PRICE_FLOOR = 4295128740n;\nconst SQRT_PRICE_CEIL = 1461446703485210103287273052203988822378723970341n;\nconst PARTIAL_FILL = \"pool liquidity runs out before the full amount (partial fill)\";\n\nconst QUOTER_ABI = parseAbi([\n \"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)\",\n \"function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)\",\n \"function factory() view returns (address)\",\n \"function WETH9() view returns (address)\",\n]);\n\n/** A quoter result's output, the pool price(s) it leaves behind and its gas figure, for either quote shape. */\nfunction decodeQuote(single: boolean, raw: Hex): {out: bigint; drained: boolean; gas: bigint} {\n const [out, after, , gas] = decodeFunctionResult({abi: QUOTER_ABI, functionName: single ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw}) as readonly [bigint, bigint | readonly bigint[], unknown, bigint];\n const prices = typeof after === \"bigint\" ? [after] : after;\n return {out, gas, drained: prices.length === 0 || prices.some((p) => p <= SQRT_PRICE_FLOOR || p >= SQRT_PRICE_CEIL)};\n}\n\nexport interface UniswapProviderConfig {\n enabled?: boolean;\n /** JSON-RPC endpoints per EVM chain id, tried in order. A chain without one is not offered. */\n rpcUrls: Readonly<Record<number, readonly string[]>>;\n /** Slippage when the caller names none (bps). Default 50. */\n defaultSlippageBps?: number;\n /** Local quote lifetime (must cover an approval being mined). Default 5 min. */\n quoteTtlMs?: number;\n /** Seconds the router accepts the swap after the quote (multicall deadline). Default 600. */\n deadlineSeconds?: number;\n /** Override the deployments (tests, new chains). Still verified on-chain before use. */\n deployments?: Readonly<Record<number, UniswapDeployment>>;\n /**\n * End a native-input swap with `refundETH()`, so `value` the pool did not take goes back to the sender in the same\n * transaction. Default false: clients pinned to `uniswapVerifyQuote` before 0.4.2 refuse the extra leg, so a server\n * turns this on only once the apps it serves verify with ≥ 0.4.2.\n */\n refundNativeInput?: boolean;\n}\n\ninterface Route {\n /** Human description for the review / logs. */\n label: string;\n /** The pool fee(s) the route pays — already inside the quoted output. */\n poolFee: string;\n single?: {fee: number};\n path?: Hex;\n}\n\ntype RpcCall = {method: string; params: unknown[]};\n\n/** Largest JSON-RPC batch sent to one node (X Layer's public RPCs refuse more than 10). */\nconst RPC_BATCH_MAX = 10;\n\nexport function uniswapProvider(config: UniswapProviderConfig): CrossChainProvider {\n const deployments = config.deployments ?? UNISWAP_V3;\n const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;\n const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;\n const deadlineS = config.deadlineSeconds ?? DEFAULT_DEADLINE_S;\n const refundNative = config.refundNativeInput === true;\n if (!Number.isInteger(slippageDefault) || slippageDefault <= 0 || slippageDefault >= 5_000) throw new Error(\"uniswap: defaultSlippageBps must be 1..4999\");\n const verified = new Map<number, Promise<void>>();\n\n const chainIdOf = (caip2: string): number | null => {\n if (!isEvm(caip2)) return null;\n const id = evmRef(caip2);\n return deployments[id] && config.rpcUrls[id]?.length ? id : null;\n };\n\n /**\n * JSON-RPC batch with endpoint failover; each slot is the result or null (reverted / errored).\n * Sent in chunks of RPC_BATCH_MAX: some public nodes cap a batch (X Layer's at 10 calls).\n */\n async function rpc(chainId: number, calls: RpcCall[], signal?: AbortSignal): Promise<(unknown | null)[]> {\n if (calls.length <= RPC_BATCH_MAX) return rpcBatch(chainId, calls, signal);\n const chunks: RpcCall[][] = [];\n for (let i = 0; i < calls.length; i += RPC_BATCH_MAX) chunks.push(calls.slice(i, i + RPC_BATCH_MAX));\n return (await Promise.all(chunks.map((c) => rpcBatch(chainId, c, signal)))).flat();\n }\n\n async function rpcBatch(chainId: number, calls: RpcCall[], signal?: AbortSignal): Promise<(unknown | null)[]> {\n let lastErr: unknown;\n for (const url of config.rpcUrls[chainId] ?? []) {\n try {\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\"content-type\": \"application/json\"},\n body: JSON.stringify(calls.map((c, id) => ({jsonrpc: \"2.0\", id, ...c}))),\n signal: signal ?? timeoutSignal(12_000),\n });\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 {id: number; result?: unknown; error?: unknown}[] | {error?: {message?: string}};\n if (!Array.isArray(body)) throw new Error(body.error?.message ?? \"batch refused\");\n const out: (unknown | null)[] = calls.map(() => null);\n for (const r of body) if (typeof r.id === \"number\" && r.id < out.length && r.error === undefined) out[r.id] = r.result ?? null;\n return out;\n } catch (e) {\n lastErr = e;\n }\n }\n const error = new Error(`uniswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`);\n // Every endpoint failed: the last one's own classification (a 429, a rejected key), else unavailable — never the caller's abort.\n throw signal?.aborted ? error : withReason(error, refusalOf(lastErr) ?? \"upstream_unavailable\");\n }\n\n const call = (to: string, data: Hex): RpcCall => ({method: \"eth_call\", params: [{to, data}, \"latest\"]});\n\n /** The pinned addresses still describe one deployment (router + quoter agree on factory and WETH). */\n function verifyDeployment(chainId: number): Promise<void> {\n let p = verified.get(chainId);\n if (!p) {\n const d = deployments[chainId]!;\n p = (async () => {\n const f = encodeFunctionData({abi: ROUTER_ABI, functionName: \"factory\"});\n const w = encodeFunctionData({abi: ROUTER_ABI, functionName: \"WETH9\"});\n const [rf, rw, qf, qw] = await rpc(chainId, [call(d.router, f), call(d.router, w), call(d.quoter, f), call(d.quoter, w)]);\n const addr = (r: unknown) => (typeof r === \"string\" && r.length >= 42 ? getAddress(`0x${r.slice(-40)}`) : null);\n const wrapped = d.nativeWrap === false ? getAddress(ZERO) : getAddress(d.weth);\n const ok = [rf, qf].every((r) => addr(r) === getAddress(d.factory)) && addr(rw) === wrapped && addr(qw) === wrapped;\n if (!ok) throw refusal(\"vault_mismatch\", `uniswap: the router/quoter on chain ${chainId} do not match the pinned deployment — refusing`);\n })();\n p.catch(() => verified.delete(chainId));\n verified.set(chainId, p);\n }\n return p;\n }\n\n /** Every candidate route for tokenIn → tokenOut on this chain. */\n function routes(chainId: number, caip2: string, tokenIn: Hex, tokenOut: Hex): Route[] {\n const d = deployments[chainId]!;\n const out: Route[] = FEE_TIERS.map((fee) => ({label: `direct ${fee / 10_000}%`, poolFee: `${fee / 10_000}%`, single: {fee}}));\n const mids = new Set<string>();\n for (const sym of HOP_SYMBOLS) {\n const mid = sym === \"WETH\" ? d.weth : ccAsset(caip2, sym)?.contract;\n if (!mid || !/^0x[0-9a-fA-F]{40}$/.test(mid)) continue;\n const m = getAddress(mid);\n if (m === getAddress(tokenIn) || m === getAddress(tokenOut) || mids.has(m)) continue;\n mids.add(m);\n for (const f1 of [100, 500, 3000]) {\n for (const f2 of [100, 500, 3000]) {\n out.push({label: `via ${sym} ${f1 / 10_000}% → ${f2 / 10_000}%`, poolFee: `${f1 / 10_000}% + ${f2 / 10_000}%`, path: encodePacked([\"address\", \"uint24\", \"address\", \"uint24\", \"address\"], [tokenIn, f1, m, f2, tokenOut])});\n }\n }\n }\n return out;\n }\n\n return {\n name: \"uniswap\",\n describeActivity: (tx, ctx) => describeUniswapActivity(tx, ctx, config.deployments ?? UNISWAP_V3),\n supportsSameChain: true,\n enabled: () => config.enabled ?? true,\n supportsChain: (caip2: string) => chainIdOf(caip2) !== null,\n supportsChainPair: (from: string, to: string) => from === to && chainIdOf(from) !== null,\n supportsRoute(from: Asset, to: Asset): boolean {\n return from.chain === to.chain && chainIdOf(from.chain) !== null;\n },\n\n async getQuote(params: QuoteParams, signal?: AbortSignal): Promise<Quote | null> {\n const refuse = (why: string, info?: Swap2RefusalReason | Swap2RefusalInfo): null => {\n params.onRefusal?.(`uniswap: ${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(`no Uniswap v3 deployment or RPC for ${params.sourceChain}`, \"unsupported_pair\");\n const d = deployments[chainId]!;\n const src = sourceAssetOf(params);\n if (!src) return refuse(`unknown source token ${params.sourceToken}`, \"unsupported_pair\");\n const nativeIn = !src.contract;\n const nativeOut = /^0x0+$/.test(params.destToken);\n if ((nativeIn || nativeOut) && d.nativeWrap === false) return refuse(\"this chain's router has no wrapped native — swap the coin's ERC-20 instead\", \"unsupported_pair\");\n if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse(\"destination token must be an EVM address\", \"unsupported_pair\");\n if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse(\"recipient must be an EVM address\", \"recipient_mismatch\");\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 tokenIn = getAddress(nativeIn ? d.weth : src.contract!);\n const tokenOut = getAddress(nativeOut ? d.weth : params.destToken);\n if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? \"that is a wrap/unwrap, not a swap\" : \"same token in and out\", \"unsupported_pair\");\n\n try {\n await verifyDeployment(chainId);\n const candidates = routes(chainId, params.sourceChain, tokenIn, tokenOut);\n const results = await rpc(\n chainId,\n candidates.map((r) =>\n call(\n d.quoter,\n r.single\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn, tokenOut, amountIn, fee: r.single.fee, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [r.path!, amountIn]}),\n ),\n ),\n signal,\n );\n let best: {route: Route; out: bigint; gas: bigint} | null = null;\n let partial = false;\n results.forEach((raw, i) => {\n if (typeof raw !== \"string\" || raw === \"0x\") return;\n const r = candidates[i]!;\n try {\n const {out, drained, gas} = decodeQuote(!!r.single, raw as Hex);\n if (out <= 0n) return;\n if (drained) {\n partial = true;\n return;\n }\n if (!best || out > best.out) best = {route: r, out, gas};\n } catch {\n /* a malformed slot is just not a candidate */\n }\n });\n if (!best) return refuse(partial ? PARTIAL_FILL : \"no Uniswap v3 pool route for this pair and amount\", partial ? \"insufficient_liquidity\" : \"no_route\");\n const {route, out, gas} = best as {route: Route; out: bigint; gas: bigint};\n\n // Price impact (SDK-127): a probe 1/1000 the size on the same route gives the pool's\n // marginal rate; the full-size rate's shortfall against it is the impact. Pool fees\n // are paid on both sides, so they cancel. Informational — the Oct 16 run swapped\n // 16.78 USDT into 0.0099 USDT0 through an empty pool and nothing said a word.\n let priceImpactBps: number | undefined;\n const probeIn = amountIn / 1000n;\n if (probeIn > 0n) {\n try {\n const [raw] = await rpc(\n chainId,\n [call(d.quoter, route.single\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn, tokenOut, amountIn: probeIn, fee: route.single.fee, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [route.path!, probeIn]}))],\n signal,\n );\n if (typeof raw === \"string\" && raw !== \"0x\") {\n const [probeOut] = decodeFunctionResult({abi: QUOTER_ABI, functionName: route.single ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw as Hex}) as readonly [bigint];\n if (probeOut > 0n) {\n const ratioBps = (out * probeIn * 10_000n) / (probeOut * amountIn); // (out/amountIn) ÷ (probeOut/probeIn), in bps\n priceImpactBps = Math.max(0, bigintToNumber(10_000n - ratioBps));\n }\n }\n } catch {\n /* the quote stands; impact is information, not a gate */\n }\n }\n\n const bps = params.slippageBps ?? slippageDefault;\n const minOut = (out * BigInt(10_000 - bps)) / 10_000n;\n if (minOut <= 0n) return refuse(`the minimum output rounds to 0 (quoted ${out} at ${bps} bps slippage) — the amount is too small for this pool`, \"amount_too_small\");\n if (params.minAmountOut !== undefined && minOut < BigInt(params.minAmountOut)) {\n return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`, \"price_check_failed\");\n }\n const recipient = getAddress(params.destAddress);\n const swapTo = nativeOut ? ADDRESS_THIS : recipient;\n const swap = route.single\n ? encodeFunctionData({abi: ROUTER_ABI, functionName: \"exactInputSingle\", args: [{tokenIn, tokenOut, fee: route.single.fee, recipient: swapTo as Hex, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: ROUTER_ABI, functionName: \"exactInput\", args: [{path: route.path!, recipient: swapTo as Hex, amountIn, amountOutMinimum: minOut}]});\n const legs: Hex[] = [swap];\n if (nativeOut) legs.push(encodeFunctionData({abi: ROUTER_ABI, functionName: \"unwrapWETH9\", args: [minOut, recipient]}));\n // The router wraps only what the pool takes: `value` it did not spend would stay in the router for anyone to\n // sweep. refundETH() pays it back to the sender in the same transaction (nothing to send on a full fill). Opt-in\n // (`refundNativeInput`) until every pinned client accepts the leg; the preflight partial-fill check and the\n // minimum already make an unspent remainder revert rather than stay behind.\n const refund = nativeIn && refundNative;\n if (refund) legs.push(encodeFunctionData({abi: ROUTER_ABI, functionName: \"refundETH\"}));\n const deadline = BigInt(Math.floor(Date.now() / 1000) + deadlineS);\n const data = encodeFunctionData({abi: ROUTER_ABI, functionName: \"multicall\", args: [deadline, legs]});\n // Quoter gas covers the pool hops; the router's own overhead and an unwrap ride on top. A figure no real pool\n // swap can cost (0 from a quoter that does not measure gas) is no figure: the limit is then left to the\n // wallet, which estimates the exact call with headroom right before broadcast, as for THORChain and Chainflip.\n // A limit derived from it would be the bare overhead, and the swap would run out of gas on chain.\n const pools = route.single ? 1n : BigInt((route.path!.length - 42) / 46);\n const gasLimit = gas >= MIN_POOL_GAS * pools ? (gas * 3n) / 2n + 120_000n + (nativeOut ? 40_000n : 0n) + (refund ? 10_000n : 0n) : undefined;\n\n return {\n provider: \"uniswap\",\n intentId: `uniswap:${chainId}`,\n depositAddress: \"\",\n depositMemo: null,\n txRequest: {\n to: d.router,\n data,\n value: nativeIn ? amountIn.toString() : \"0\",\n chainId,\n ...(gasLimit !== undefined ? {gasLimit: gasLimit.toString()} : {}),\n ...(nativeIn ? {} : {approvalAddress: d.router}),\n },\n sourceAmount: amountIn.toString(),\n destAmount: out.toString(),\n minDestAmount: minOut.toString(),\n feeUsd: 0,\n etaSeconds: 15,\n reliability: 0.98,\n validUntilMs: Date.now() + ttl,\n providerData: {\n route: route.label,\n poolFee: route.poolFee,\n router: d.router,\n tokenIn,\n tokenOut,\n amountIn: amountIn.toString(),\n minOut: minOut.toString(),\n ...(route.single ? {fee: String(route.single.fee)} : {path: route.path!}),\n ...(priceImpactBps !== undefined ? {priceImpactBps: String(priceImpactBps)} : {}),\n },\n };\n } catch (e) {\n return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, \"\") : String(e), refusalOf(e));\n }\n },\n\n /**\n * Right before broadcast (after any approval): re-quote the SAME route on\n * chain. If the pool now pays less than the signed minimum, the swap would\n * only revert and burn gas — refuse it here with the reason instead. A pool\n * that no longer holds enough for the whole input (it would fill part of it)\n * is refused the same way.\n */\n async preflightDeposit(quote: Quote): Promise<void> {\n const chainId = Number(quote.intentId.split(\":\")[1]);\n const d = deployments[chainId];\n const pd = quote.providerData ?? {};\n if (!d || !pd.amountIn || !pd.minOut || !pd.tokenIn || !pd.tokenOut) return;\n const data = pd.fee\n ? encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInputSingle\", args: [{tokenIn: pd.tokenIn as Hex, tokenOut: pd.tokenOut as Hex, amountIn: BigInt(pd.amountIn), fee: Number(pd.fee), sqrtPriceLimitX96: 0n}]})\n : encodeFunctionData({abi: QUOTER_ABI, functionName: \"quoteExactInput\", args: [pd.path as Hex, BigInt(pd.amountIn)]});\n const [raw] = await rpc(chainId, [call(d.quoter, data)]);\n if (typeof raw !== \"string\" || raw === \"0x\") throw refusal(\"no_route\", \"uniswap: the pool no longer quotes this route — refresh and try again\");\n let quoted: ReturnType<typeof decodeQuote>;\n try {\n quoted = decodeQuote(!!pd.fee, raw as Hex);\n } catch (e) {\n throw e instanceof Error ? withReason(e, \"upstream_unavailable\") : e; // the node answered in another shape\n }\n const {out, drained} = quoted;\n if (drained) throw refusal(\"insufficient_liquidity\", `uniswap: ${PARTIAL_FILL} — the pool can no longer take this swap. Nothing was sent; refresh the quote.`);\n if (out < BigInt(pd.minOut)) {\n throw refusal(\"price_check_failed\", `uniswap: price moved — the pool now pays ${out}, under your minimum ${pd.minOut}. Nothing was sent; refresh the quote.`);\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: Uniswap quote has no transaction request\");\n return {\n chain: \"\",\n to: tx.to,\n value: tx.value ?? \"0\",\n data: tx.data,\n ...(tx.chainId !== undefined ? {chainId: tx.chainId} : {}),\n ...(tx.gasLimit ? {gasLimit: tx.gasLimit} : {}),\n ...(tx.approvalAddress ? {approvalAddress: tx.approvalAddress} : {}),\n };\n },\n\n /** Same-chain: the swap is done when its transaction is mined successfully. */\n async trackIntent(ref: IntentRef): Promise<IntentStatus> {\n if (!ref.sourceTxHash) return {state: \"pending\"};\n const chainId = Number(ref.intentId.split(\":\")[1]);\n if (!deployments[chainId] || !config.rpcUrls[chainId]?.length) return {state: \"pending\"};\n try {\n const [receipt] = (await rpc(chainId, [{method: \"eth_getTransactionReceipt\", params: [ref.sourceTxHash]}])) as [{status?: string} | null];\n if (!receipt) return {state: \"pending\"};\n return receipt.status === \"0x1\" ? {state: \"completed\", destTxHash: ref.sourceTxHash} : {state: \"failed\"};\n } catch {\n return {state: \"pending\"};\n }\n },\n };\n}\n","/**\n * Activity recognition for Uniswap v3: a call into the chain's SwapRouter02\n * (the deployment table, or the caller's override) with one of the router's\n * swap entry points → `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 {UNISWAP_V3, type UniswapDeployment} from \"./addresses.js\";\n\nexport const UNISWAP_MODULE = \"@anywalletkit/protocol-swap2-uniswap\";\n\n/** SwapRouter02 entry points (`viem toFunctionSelector`, 2026-10-14). */\nexport const UNISWAP_ROUTER_SELECTORS: ReadonlySet<string> = new Set([\n \"0x5ae401dc\", // multicall(uint256 deadline, bytes[] data)\n \"0xac9650d8\", // multicall(bytes[] data)\n \"0x1f0464d1\", // multicall(bytes32 previousBlockhash, bytes[] data)\n \"0x04e45aaf\", // exactInputSingle((address,address,uint24,address,uint256,uint256,uint160))\n \"0xb858183f\", // exactInput((bytes,address,uint256,uint256))\n \"0x5023b4df\", // exactOutputSingle((address,address,uint24,address,uint256,uint256,uint160))\n \"0x09b81346\", // exactOutput((bytes,address,uint256,uint256))\n]);\n\nexport function describeUniswapActivity(\n tx: ChainTx,\n ctx: DescribeActivityContext,\n deployments: Readonly<Record<number, UniswapDeployment>> = UNISWAP_V3,\n): ActivityItem | null {\n if (!isEvm(tx.chain)) return null;\n const deployment = deployments[evmRef(tx.chain)];\n if (!deployment || !matchesCall(tx, [deployment.router], UNISWAP_ROUTER_SELECTORS)) return null;\n return describeSwapLike(tx, ctx, {protocol: UNISWAP_MODULE, subtitle: `Uniswap v3 · ${chainLabel(tx.chain)}`, kind: \"swap\"});\n}\n","import {SingleProviderSwap2} from \"@anywalletkit/protocol-swap2-core/swap2/single\";\nimport type {Swap2Account, Swap2EngineConfig} from \"@anywalletkit/protocol-swap2-core/swap2/base\";\nimport {evmRef, isEvm} from \"@anywalletkit/protocol-swap2-core/util\";\nimport {UNISWAP_V3} from \"./addresses.js\";\nimport {uniswapProvider, type UniswapProviderConfig} from \"./provider.js\";\n\nexport interface UniswapSwap2Config extends Swap2EngineConfig, UniswapProviderConfig {}\n\n/** Uniswap v3 as a standalone swap2 protocol (same-chain swaps on one account). */\nexport class UniswapSwap2Protocol extends SingleProviderSwap2 {\n protected readonly provider;\n private readonly _rpcUrls: UniswapProviderConfig[\"rpcUrls\"];\n private readonly _deployments: NonNullable<UniswapProviderConfig[\"deployments\"]>;\n constructor(account: Swap2Account | undefined, config: UniswapSwap2Config) {\n super(account, config);\n this.provider = uniswapProvider(config);\n this._rpcUrls = config.rpcUrls ?? {};\n this._deployments = config.deployments ?? UNISWAP_V3;\n }\n protected override chainSupported(caip2: string): boolean {\n return isEvm(caip2) && !!this._deployments[evmRef(caip2)] && !!this._rpcUrls[evmRef(caip2)]?.length;\n }\n protected override pairSupported(fromChain: string, toChain: string): boolean {\n return fromChain === toChain && this.chainSupported(fromChain);\n }\n}\n"],"mappings":";;;;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Ae,OAAwB;AACxD,eAAO,oBAAM,KAAK,KAAK,CAAC,CAAC,KAAK,iBAAa,qBAAO,KAAK,CAAC,KAAK,CAAC,CAAC,KAAK,aAAS,qBAAO,KAAK,CAAC,GAAG;AAAA,EAC/F;AAAA,EACmB,cAAc,WAAmB,SAA0B;AAC5E,WAAO,cAAc,WAAW,KAAK,eAAe,SAAS;AAAA,EAC/D;AACF;","names":["refusal","import_viem","import_util","import_util","import_errors","error","out","gas","import_util"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as ADDRESS_THIS, F as FEE_TIERS, H as HOP_SYMBOLS, R as ROUTER_ABI, U as UNISWAP_V3, a as UniswapDeployment, u as uniswapPins, b as uniswapVerifyQuote } from './addresses-Dumvcb4A.cjs';
1
+ export { A as ADDRESS_THIS, F as FEE_TIERS, H as HOP_SYMBOLS, R as ROUTER_ABI, U as UNISWAP_V3, a as UniswapDeployment, u as uniswapPins, b as uniswapVerifyQuote } from './addresses-B8Qq_0DN.cjs';
2
2
  export { UniswapProviderConfig, uniswapProvider } from './provider.cjs';
3
3
  export { UniswapSwap2Config, UniswapSwap2Protocol, UniswapSwap2Protocol as default } from './protocol.cjs';
4
4
  export { UNISWAP_MODULE, UNISWAP_ROUTER_SELECTORS, describeUniswapActivity } from './activity.cjs';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { A as ADDRESS_THIS, F as FEE_TIERS, H as HOP_SYMBOLS, R as ROUTER_ABI, U as UNISWAP_V3, a as UniswapDeployment, u as uniswapPins, b as uniswapVerifyQuote } from './addresses-Dumvcb4A.js';
1
+ export { A as ADDRESS_THIS, F as FEE_TIERS, H as HOP_SYMBOLS, R as ROUTER_ABI, U as UNISWAP_V3, a as UniswapDeployment, u as uniswapPins, b as uniswapVerifyQuote } from './addresses-B8Qq_0DN.js';
2
2
  export { UniswapProviderConfig, uniswapProvider } from './provider.js';
3
3
  export { UniswapSwap2Config, UniswapSwap2Protocol, UniswapSwap2Protocol as default } from './protocol.js';
4
4
  export { UNISWAP_MODULE, UNISWAP_ROUTER_SELECTORS, describeUniswapActivity } from './activity.js';
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  UniswapSwap2Protocol
3
- } from "./chunk-M55L67V5.js";
3
+ } from "./chunk-HPS3TTCB.js";
4
4
  import {
5
5
  uniswapProvider
6
- } from "./chunk-XJDPJSBT.js";
6
+ } from "./chunk-6ZGWUPLL.js";
7
7
  import {
8
8
  ADDRESS_THIS,
9
9
  FEE_TIERS,
@@ -15,7 +15,7 @@ import {
15
15
  describeUniswapActivity,
16
16
  uniswapPins,
17
17
  uniswapVerifyQuote
18
- } from "./chunk-ZOLQRZNH.js";
18
+ } from "./chunk-32CIYNG2.js";
19
19
  export {
20
20
  ADDRESS_THIS,
21
21
  FEE_TIERS,
package/dist/protocol.cjs CHANGED
@@ -29,6 +29,7 @@ var import_util4 = require("@anywalletkit/protocol-swap2-core/util");
29
29
  // src/addresses.ts
30
30
  var import_viem = require("viem");
31
31
  var import_util = require("@anywalletkit/protocol-swap2-core/util");
32
+ var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
32
33
  var UNISWAP_V3 = Object.freeze({
33
34
  1: { factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984", quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e", router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45", weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" },
34
35
  10: { factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984", quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e", router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45", weth: "0x4200000000000000000000000000000000000006" },
@@ -68,18 +69,19 @@ var ROUTER_ABI = (0, import_viem.parseAbi)([
68
69
  "function WETH9() view returns (address)"
69
70
  ]);
70
71
  var MAX_PATH_POOLS = 2;
72
+ var notes = (0, import_errors.refusalNotes)();
71
73
  function uniswapVerifyQuote(params, quote) {
72
74
  const id = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;
73
75
  const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : void 0;
74
- if (!d || params.destChain !== params.sourceChain) return "not a same-chain swap on a pinned Uniswap deployment";
76
+ if (!d || params.destChain !== params.sourceChain) return notes.note("not a same-chain swap on a pinned Uniswap deployment", "unsupported_pair");
75
77
  const tx = quote.txRequest;
76
- if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return "the quote carries no router call";
77
- if ((0, import_viem.getAddress)(tx.to) !== (0, import_viem.getAddress)(d.router)) return `the call targets ${tx.to}, not the SwapRouter`;
78
+ if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return notes.note("the quote carries no router call", "policy_refused");
79
+ if ((0, import_viem.getAddress)(tx.to) !== (0, import_viem.getAddress)(d.router)) return notes.note(`the call targets ${tx.to}, not the SwapRouter`, "vault_mismatch");
78
80
  const src = (0, import_util.sourceAssetOf)(params);
79
- if (!src) return `unknown source token ${params.sourceToken}`;
81
+ if (!src) return notes.note(`unknown source token ${params.sourceToken}`, "unsupported_pair");
80
82
  const nativeIn = !src.contract;
81
83
  const nativeOut = /^0x0+$/.test(params.destToken);
82
- if ((nativeIn || nativeOut) && d.nativeWrap === false) return "this chain's router has no wrapped native";
84
+ if ((nativeIn || nativeOut) && d.nativeWrap === false) return notes.note("this chain's router has no wrapped native", "unsupported_pair");
83
85
  let tokenIn, tokenOut, recipient, amountIn, minOut;
84
86
  try {
85
87
  tokenIn = (0, import_viem.getAddress)(nativeIn ? d.weth : src.contract);
@@ -91,15 +93,15 @@ function uniswapVerifyQuote(params, quote) {
91
93
  return "the request does not name EVM tokens, a recipient and amounts";
92
94
  }
93
95
  if (nativeIn ? BigInt(tx.value ?? "0") !== amountIn || tx.approvalAddress !== void 0 : BigInt(tx.value ?? "0") !== 0n || !tx.approvalAddress || (0, import_viem.getAddress)(tx.approvalAddress) !== (0, import_viem.getAddress)(d.router)) {
94
- return nativeIn ? "a native input is paid as exactly the input in value, with no approval" : "a token input attaches no value and approves the SwapRouter";
96
+ return notes.note(nativeIn ? "a native input is paid as exactly the input in value, with no approval" : "a token input attaches no value and approves the SwapRouter", "policy_refused");
95
97
  }
96
98
  let legs;
97
99
  try {
98
100
  const outer = (0, import_viem.decodeFunctionData)({ abi: ROUTER_ABI, data: tx.data });
99
- if (outer.functionName !== "multicall") return `${outer.functionName} is not multicall(deadline, legs)`;
101
+ if (outer.functionName !== "multicall") return notes.note(`${outer.functionName} is not multicall(deadline, legs)`, "policy_refused");
100
102
  legs = outer.args[1];
101
103
  } catch {
102
- return "the router call is not multicall(deadline, legs)";
104
+ return notes.note("the router call is not multicall(deadline, legs)", "policy_refused");
103
105
  }
104
106
  const decode = (leg) => {
105
107
  try {
@@ -109,36 +111,37 @@ function uniswapVerifyQuote(params, quote) {
109
111
  }
110
112
  };
111
113
  if (nativeIn && legs.length === 2 && decode(legs[1])?.functionName === "refundETH") legs = legs.slice(0, 1);
112
- if (legs.length !== (nativeOut ? 2 : 1)) return `the multicall has ${legs.length} legs, not a swap${nativeOut ? " and an unwrap" : nativeIn ? " (and a refund)" : ""}`;
114
+ if (legs.length !== (nativeOut ? 2 : 1)) return notes.note(`the multicall has ${legs.length} legs, not a swap${nativeOut ? " and an unwrap" : nativeIn ? " (and a refund)" : ""}`, "policy_refused");
113
115
  const swap = decode(legs[0]);
114
116
  const swapTo = nativeOut ? ADDRESS_THIS : recipient;
115
117
  if (swap?.functionName === "exactInputSingle") {
116
118
  const a = swap.args[0];
117
- if ((0, import_viem.getAddress)(a.tokenIn) !== tokenIn || (0, import_viem.getAddress)(a.tokenOut) !== tokenOut) return "the swap trades other tokens";
118
- if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut || a.sqrtPriceLimitX96 !== 0n) return "the swap's input, minimum or price limit is not the quote's";
119
- if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return `the swap pays ${a.recipient}, not the recipient`;
119
+ if ((0, import_viem.getAddress)(a.tokenIn) !== tokenIn || (0, import_viem.getAddress)(a.tokenOut) !== tokenOut) return notes.note("the swap trades other tokens", "policy_refused");
120
+ if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut || a.sqrtPriceLimitX96 !== 0n) return notes.note("the swap's input, minimum or price limit is not the quote's", "price_check_failed");
121
+ if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return notes.note(`the swap pays ${a.recipient}, not the recipient`, "recipient_mismatch");
120
122
  } else if (swap?.functionName === "exactInput") {
121
123
  const a = swap.args[0];
122
124
  const path = a.path.slice(2);
123
125
  const pools = (path.length / 2 - 20) / 23;
124
- if (!/^[0-9a-fA-F]*$/.test(path) || !Number.isInteger(pools) || pools < 1 || pools > MAX_PATH_POOLS) return "the swap path is not 1\u20132 pools";
125
- if ((0, import_viem.getAddress)(`0x${path.slice(0, 40)}`) !== tokenIn || (0, import_viem.getAddress)(`0x${path.slice(-40)}`) !== tokenOut) return "the swap path trades other tokens";
126
- if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return "the swap's input or minimum is not the quote's";
127
- if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return `the swap pays ${a.recipient}, not the recipient`;
126
+ if (!/^[0-9a-fA-F]*$/.test(path) || !Number.isInteger(pools) || pools < 1 || pools > MAX_PATH_POOLS) return notes.note("the swap path is not 1\u20132 pools", "policy_refused");
127
+ if ((0, import_viem.getAddress)(`0x${path.slice(0, 40)}`) !== tokenIn || (0, import_viem.getAddress)(`0x${path.slice(-40)}`) !== tokenOut) return notes.note("the swap path trades other tokens", "policy_refused");
128
+ if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return notes.note("the swap's input or minimum is not the quote's", "price_check_failed");
129
+ if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return notes.note(`the swap pays ${a.recipient}, not the recipient`, "recipient_mismatch");
128
130
  } else {
129
- return `${swap?.functionName ?? "an unknown call"} is not exactInputSingle / exactInput`;
131
+ return notes.note(`${swap?.functionName ?? "an unknown call"} is not exactInputSingle / exactInput`, "policy_refused");
130
132
  }
131
133
  if (nativeOut) {
132
134
  const unwrap = decode(legs[1]);
133
- if (unwrap?.functionName !== "unwrapWETH9") return `${unwrap?.functionName ?? "an unknown call"} is not unwrapWETH9`;
134
- if (unwrap.args[0] !== minOut || (0, import_viem.getAddress)(unwrap.args[1]) !== recipient) return "the unwrap pays someone else or less than the minimum";
135
+ if (unwrap?.functionName !== "unwrapWETH9") return notes.note(`${unwrap?.functionName ?? "an unknown call"} is not unwrapWETH9`, "policy_refused");
136
+ if (unwrap.args[0] !== minOut || (0, import_viem.getAddress)(unwrap.args[1]) !== recipient) return notes.note("the unwrap pays someone else or less than the minimum", (0, import_viem.getAddress)(unwrap.args[1]) !== recipient ? "recipient_mismatch" : "price_check_failed");
135
137
  }
136
138
  return null;
137
139
  }
138
140
  var uniswapPins = Object.freeze({
139
141
  callTargets: (chain) => uniswapRouterFor(chain),
140
142
  spenders: (chain) => uniswapRouterFor(chain),
141
- verifyQuote: uniswapVerifyQuote
143
+ verifyQuote: uniswapVerifyQuote,
144
+ reasonOf: (refusal2) => notes.reasonOf(refusal2)
142
145
  });
143
146
  function uniswapRouterFor(chain) {
144
147
  const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;
@@ -179,6 +182,7 @@ function describeUniswapActivity(tx, ctx, deployments = UNISWAP_V3) {
179
182
  // src/provider.ts
180
183
  var import_swap2_assets = require("@anywalletkit/swap2-assets");
181
184
  var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
185
+ var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
182
186
  var import_core = require("@anywalletkit/core");
183
187
  var ZERO = "0x0000000000000000000000000000000000000000";
184
188
  var DEFAULT_SLIPPAGE_BPS = 50;
@@ -229,7 +233,11 @@ function uniswapProvider(config) {
229
233
  body: JSON.stringify(calls.map((c, id) => ({ jsonrpc: "2.0", id, ...c }))),
230
234
  signal: signal ?? (0, import_util3.timeoutSignal)(12e3)
231
235
  });
232
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
236
+ if (!res.ok) {
237
+ const error2 = new Error(`HTTP ${res.status}`);
238
+ const info = (0, import_errors2.httpRefusal)(res.status, res.headers?.get?.("retry-after"));
239
+ throw info ? (0, import_errors2.withReason)(error2, info) : error2;
240
+ }
233
241
  const body = await res.json();
234
242
  if (!Array.isArray(body)) throw new Error(body.error?.message ?? "batch refused");
235
243
  const out = calls.map(() => null);
@@ -239,7 +247,8 @@ function uniswapProvider(config) {
239
247
  lastErr = e;
240
248
  }
241
249
  }
242
- throw new Error(`uniswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`);
250
+ const error = new Error(`uniswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`);
251
+ throw signal?.aborted ? error : (0, import_errors2.withReason)(error, (0, import_errors2.refusalOf)(lastErr) ?? "upstream_unavailable");
243
252
  }
244
253
  const call = (to, data) => ({ method: "eth_call", params: [{ to, data }, "latest"] });
245
254
  function verifyDeployment(chainId) {
@@ -253,7 +262,7 @@ function uniswapProvider(config) {
253
262
  const addr = (r) => typeof r === "string" && r.length >= 42 ? (0, import_viem2.getAddress)(`0x${r.slice(-40)}`) : null;
254
263
  const wrapped = d.nativeWrap === false ? (0, import_viem2.getAddress)(ZERO) : (0, import_viem2.getAddress)(d.weth);
255
264
  const ok = [rf, qf].every((r) => addr(r) === (0, import_viem2.getAddress)(d.factory)) && addr(rw) === wrapped && addr(qw) === wrapped;
256
- if (!ok) throw new Error(`uniswap: the router/quoter on chain ${chainId} do not match the pinned deployment \u2014 refusing`);
265
+ if (!ok) throw (0, import_errors2.refusal)("vault_mismatch", `uniswap: the router/quoter on chain ${chainId} do not match the pinned deployment \u2014 refusing`);
257
266
  })();
258
267
  p.catch(() => verified.delete(chainId));
259
268
  verified.set(chainId, p);
@@ -289,22 +298,22 @@ function uniswapProvider(config) {
289
298
  return from.chain === to.chain && chainIdOf(from.chain) !== null;
290
299
  },
291
300
  async getQuote(params, signal) {
292
- const refuse = (why) => {
293
- params.onRefusal?.(`uniswap: ${why}`);
301
+ const refuse = (why, info) => {
302
+ params.onRefusal?.(`uniswap: ${why}`, typeof info === "string" ? { reason: info } : info);
294
303
  return null;
295
304
  };
296
- if (params.flex) return refuse("amount-flexible deposits are not supported");
297
- if (params.sourceChain !== params.destChain) return refuse("same-chain swaps only");
305
+ if (params.flex) return refuse("amount-flexible deposits are not supported", "unsupported_pair");
306
+ if (params.sourceChain !== params.destChain) return refuse("same-chain swaps only", "unsupported_pair");
298
307
  const chainId = chainIdOf(params.sourceChain);
299
- if (chainId === null) return refuse(`no Uniswap v3 deployment or RPC for ${params.sourceChain}`);
308
+ if (chainId === null) return refuse(`no Uniswap v3 deployment or RPC for ${params.sourceChain}`, "unsupported_pair");
300
309
  const d = deployments[chainId];
301
310
  const src = (0, import_util3.sourceAssetOf)(params);
302
- if (!src) return refuse(`unknown source token ${params.sourceToken}`);
311
+ if (!src) return refuse(`unknown source token ${params.sourceToken}`, "unsupported_pair");
303
312
  const nativeIn = !src.contract;
304
313
  const nativeOut = /^0x0+$/.test(params.destToken);
305
- if ((nativeIn || nativeOut) && d.nativeWrap === false) return refuse("this chain's router has no wrapped native \u2014 swap the coin's ERC-20 instead");
306
- if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address");
307
- if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address");
314
+ if ((nativeIn || nativeOut) && d.nativeWrap === false) return refuse("this chain's router has no wrapped native \u2014 swap the coin's ERC-20 instead", "unsupported_pair");
315
+ if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address", "unsupported_pair");
316
+ if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address", "recipient_mismatch");
308
317
  let amountIn;
309
318
  try {
310
319
  amountIn = BigInt(params.amountIn);
@@ -314,7 +323,7 @@ function uniswapProvider(config) {
314
323
  if (amountIn <= 0n) return refuse("amount must be positive");
315
324
  const tokenIn = (0, import_viem2.getAddress)(nativeIn ? d.weth : src.contract);
316
325
  const tokenOut = (0, import_viem2.getAddress)(nativeOut ? d.weth : params.destToken);
317
- if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? "that is a wrap/unwrap, not a swap" : "same token in and out");
326
+ if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? "that is a wrap/unwrap, not a swap" : "same token in and out", "unsupported_pair");
318
327
  try {
319
328
  await verifyDeployment(chainId);
320
329
  const candidates = routes(chainId, params.sourceChain, tokenIn, tokenOut);
@@ -344,7 +353,7 @@ function uniswapProvider(config) {
344
353
  } catch {
345
354
  }
346
355
  });
347
- if (!best) return refuse(partial ? PARTIAL_FILL : "no Uniswap v3 pool route for this pair and amount");
356
+ if (!best) return refuse(partial ? PARTIAL_FILL : "no Uniswap v3 pool route for this pair and amount", partial ? "insufficient_liquidity" : "no_route");
348
357
  const { route, out, gas } = best;
349
358
  let priceImpactBps;
350
359
  const probeIn = amountIn / 1000n;
@@ -367,9 +376,9 @@ function uniswapProvider(config) {
367
376
  }
368
377
  const bps = params.slippageBps ?? slippageDefault;
369
378
  const minOut = out * BigInt(1e4 - bps) / 10000n;
370
- if (minOut <= 0n) return refuse(`the minimum output rounds to 0 (quoted ${out} at ${bps} bps slippage) \u2014 the amount is too small for this pool`);
379
+ if (minOut <= 0n) return refuse(`the minimum output rounds to 0 (quoted ${out} at ${bps} bps slippage) \u2014 the amount is too small for this pool`, "amount_too_small");
371
380
  if (params.minAmountOut !== void 0 && minOut < BigInt(params.minAmountOut)) {
372
- return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`);
381
+ return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`, "price_check_failed");
373
382
  }
374
383
  const recipient = (0, import_viem2.getAddress)(params.destAddress);
375
384
  const swapTo = nativeOut ? ADDRESS_THIS : recipient;
@@ -415,7 +424,7 @@ function uniswapProvider(config) {
415
424
  }
416
425
  };
417
426
  } catch (e) {
418
- return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, "") : String(e));
427
+ return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, "") : String(e), (0, import_errors2.refusalOf)(e));
419
428
  }
420
429
  },
421
430
  /**
@@ -432,16 +441,22 @@ function uniswapProvider(config) {
432
441
  if (!d || !pd.amountIn || !pd.minOut || !pd.tokenIn || !pd.tokenOut) return;
433
442
  const data = pd.fee ? (0, import_viem2.encodeFunctionData)({ abi: QUOTER_ABI, functionName: "quoteExactInputSingle", args: [{ tokenIn: pd.tokenIn, tokenOut: pd.tokenOut, amountIn: BigInt(pd.amountIn), fee: Number(pd.fee), sqrtPriceLimitX96: 0n }] }) : (0, import_viem2.encodeFunctionData)({ abi: QUOTER_ABI, functionName: "quoteExactInput", args: [pd.path, BigInt(pd.amountIn)] });
434
443
  const [raw] = await rpc(chainId, [call(d.quoter, data)]);
435
- if (typeof raw !== "string" || raw === "0x") throw new Error("uniswap: the pool no longer quotes this route \u2014 refresh and try again");
436
- const { out, drained } = decodeQuote(!!pd.fee, raw);
437
- if (drained) throw new Error(`uniswap: ${PARTIAL_FILL} \u2014 the pool can no longer take this swap. Nothing was sent; refresh the quote.`);
444
+ if (typeof raw !== "string" || raw === "0x") throw (0, import_errors2.refusal)("no_route", "uniswap: the pool no longer quotes this route \u2014 refresh and try again");
445
+ let quoted;
446
+ try {
447
+ quoted = decodeQuote(!!pd.fee, raw);
448
+ } catch (e) {
449
+ throw e instanceof Error ? (0, import_errors2.withReason)(e, "upstream_unavailable") : e;
450
+ }
451
+ const { out, drained } = quoted;
452
+ if (drained) throw (0, import_errors2.refusal)("insufficient_liquidity", `uniswap: ${PARTIAL_FILL} \u2014 the pool can no longer take this swap. Nothing was sent; refresh the quote.`);
438
453
  if (out < BigInt(pd.minOut)) {
439
- throw new Error(`uniswap: price moved \u2014 the pool now pays ${out}, under your minimum ${pd.minOut}. Nothing was sent; refresh the quote.`);
454
+ throw (0, import_errors2.refusal)("price_check_failed", `uniswap: price moved \u2014 the pool now pays ${out}, under your minimum ${pd.minOut}. Nothing was sent; refresh the quote.`);
440
455
  }
441
456
  },
442
457
  async buildDeposit(quote) {
443
458
  const tx = quote.txRequest;
444
- if (!tx?.to || !tx.data) throw new Error("swap2: Uniswap quote has no transaction request");
459
+ if (!tx?.to || !tx.data) throw (0, import_errors2.refusal)("policy_refused", "swap2: Uniswap quote has no transaction request");
445
460
  return {
446
461
  chain: "",
447
462
  to: tx.to,