@anywalletkit/protocol-swap2-uniswap 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/activity.cjs +3 -1
- package/dist/activity.cjs.map +1 -1
- package/dist/activity.d.cts +1 -1
- package/dist/activity.d.ts +1 -1
- package/dist/activity.js +1 -1
- package/dist/{addresses-gagFZ2tJ.d.cts → addresses-Dumvcb4A.d.cts} +13 -4
- package/dist/{addresses-gagFZ2tJ.d.ts → addresses-Dumvcb4A.d.ts} +13 -4
- package/dist/{chunk-QQGCEDT3.js → chunk-M55L67V5.js} +3 -3
- package/dist/{chunk-7XZQD45M.js → chunk-XJDPJSBT.js} +29 -8
- package/dist/chunk-XJDPJSBT.js.map +1 -0
- package/dist/{chunk-SXUKROTA.js → chunk-ZOLQRZNH.js} +5 -3
- package/dist/chunk-ZOLQRZNH.js.map +1 -0
- package/dist/index.cjs +31 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/protocol.cjs +31 -8
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +1 -1
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +3 -3
- package/dist/provider.cjs +31 -8
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +7 -1
- package/dist/provider.d.ts +7 -1
- package/dist/provider.js +2 -2
- package/package.json +3 -3
- package/dist/chunk-7XZQD45M.js.map +0 -1
- package/dist/chunk-SXUKROTA.js.map +0 -1
- /package/dist/{chunk-QQGCEDT3.js.map → chunk-M55L67V5.js.map} +0 -0
package/dist/protocol.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/protocol.ts","../src/addresses.ts","../src/provider.ts","../src/activity.ts"],"sourcesContent":["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","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). */\nexport const HOP_SYMBOLS = [\"WETH\", \"USDC\", \"USDT\"] 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 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). `pull`, `sweepToken` and\n * 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 if (legs.length !== (nativeOut ? 2 : 1)) return `the multicall has ${legs.length} legs, not a swap${nativeOut ? \" and an unwrap\" : \"\"}`;\n const decode = (leg: Hex) => { try { return decodeFunctionData({abi: ROUTER_ABI, data: leg}); } catch { return null; } };\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). Execution: SwapRouter02\n * `multicall(deadline, …)` — `exactInputSingle` or `exactInput`, native input\n * wrapped by the router (`value`), native output kept in the router and paid\n * out with `unwrapWETH9(min, recipient)`. No API key, no Uniswap frontend, no\n * 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\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\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\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 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 results.forEach((raw, i) => {\n if (typeof raw !== \"string\" || raw === \"0x\") return;\n const r = candidates[i]!;\n try {\n const [out, , , gas] = decodeFunctionResult({abi: QUOTER_ABI, functionName: r.single ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw as Hex}) as readonly [bigint, unknown, unknown, bigint];\n if (out > 0n && (!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(\"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 (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 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) : 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.\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] = decodeFunctionResult({abi: QUOTER_ABI, functionName: pd.fee ? \"quoteExactInputSingle\" : \"quoteExactInput\", data: raw as Hex}) as readonly [bigint];\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;AAElC,IAAAA,eAA4B;;;ACF5B,kBAAiE;AACjE,kBAA4B;AAuBrB,IAAM,aAA0D,OAAO,OAAO;AAAA,EACnF,GAAG,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EACzN,IAAI,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC1N,IAAI,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC1N,KAAK,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC3N,MAAM,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC5N,OAAO,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA;AAAA;AAAA,EAG7N,KAAK,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC3N,OAAO,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,8CAA8C,YAAY,MAAK;AAA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,GAAG,OAAQ,QAAO,EAAC,OAAO,UAAS;AACvF,UAAI;AACF,cAAM,CAAC,OAAO,IAAK,MAAM,IAAI,SAAS,CAAC,EAAC,QAAQ,6BAA6B,QAAQ,CAAC,IAAI,YAAY,EAAC,CAAC,CAAC;AACzG,YAAI,CAAC,QAAS,QAAO,EAAC,OAAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AF/VO,IAAM,uBAAN,cAAmC,kCAAoB;AAAA,EACzC;AAAA,EACF;AAAA,EACA;AAAA,EACjB,YAAY,SAAmC,QAA4B;AACzE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,gBAAgB,MAAM;AACtC,SAAK,WAAW,OAAO,WAAW,CAAC;AACnC,SAAK,eAAe,OAAO,eAAe;AAAA,EAC5C;AAAA,EACmB,eAAe,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":["import_util","import_viem","import_util","import_util","out","gas"]}
|
|
1
|
+
{"version":3,"sources":["../src/protocol.ts","../src/addresses.ts","../src/provider.ts","../src/activity.ts"],"sourcesContent":["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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAkC;AAElC,IAAAA,eAA4B;;;ACF5B,kBAAiE;AACjE,kBAA4B;AAuBrB,IAAM,aAA0D,OAAO,OAAO;AAAA,EACnF,GAAG,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EACzN,IAAI,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC1N,IAAI,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC1N,KAAK,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC3N,MAAM,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA,EAC5N,OAAO,EAAC,SAAS,8CAA8C,QAAQ,8CAA8C,QAAQ,8CAA8C,MAAM,6CAA4C;AAAA;AAAA;AAA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AAO,UAAS;AACtC,eAAO,QAAQ,WAAW,QAAQ,EAAC,OAAO,aAAa,YAAY,IAAI,aAAY,IAAI,EAAC,OAAO,SAAQ;AAAA,MACzG,QAAQ;AACN,eAAO,EAAC,OAAO,UAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;;;AFnYO,IAAM,uBAAN,cAAmC,kCAAoB;AAAA,EACzC;AAAA,EACF;AAAA,EACA;AAAA,EACjB,YAAY,SAAmC,QAA4B;AACzE,UAAM,SAAS,MAAM;AACrB,SAAK,WAAW,gBAAgB,MAAM;AACtC,SAAK,WAAW,OAAO,WAAW,CAAC;AACnC,SAAK,eAAe,OAAO,eAAe;AAAA,EAC5C;AAAA,EACmB,eAAe,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":["import_util","import_viem","import_util","import_util","out","gas"]}
|
package/dist/protocol.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol
|
|
|
2
2
|
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
3
|
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
4
|
import { UniswapProviderConfig } from './provider.cjs';
|
|
5
|
-
import './addresses-
|
|
5
|
+
import './addresses-Dumvcb4A.cjs';
|
|
6
6
|
|
|
7
7
|
interface UniswapSwap2Config extends Swap2EngineConfig, UniswapProviderConfig {
|
|
8
8
|
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as _anywalletkit_protocol_swap2_core_types from '@anywalletkit/protocol
|
|
|
2
2
|
import { SingleProviderSwap2 } from '@anywalletkit/protocol-swap2-core/swap2/single';
|
|
3
3
|
import { Swap2EngineConfig, Swap2Account } from '@anywalletkit/protocol-swap2-core/swap2/base';
|
|
4
4
|
import { UniswapProviderConfig } from './provider.js';
|
|
5
|
-
import './addresses-
|
|
5
|
+
import './addresses-Dumvcb4A.js';
|
|
6
6
|
|
|
7
7
|
interface UniswapSwap2Config extends Swap2EngineConfig, UniswapProviderConfig {
|
|
8
8
|
}
|
package/dist/protocol.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
UniswapSwap2Protocol
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-M55L67V5.js";
|
|
4
|
+
import "./chunk-XJDPJSBT.js";
|
|
5
|
+
import "./chunk-ZOLQRZNH.js";
|
|
6
6
|
export {
|
|
7
7
|
UniswapSwap2Protocol
|
|
8
8
|
};
|
package/dist/provider.cjs
CHANGED
|
@@ -59,12 +59,13 @@ var UNISWAP_V3 = Object.freeze({
|
|
|
59
59
|
43114: { factory: "0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD", quoter: "0xbe0F5544EC67e9B3b2D979aaA43f18Fd87E6257F", router: "0xbb00FF08d01D300023C629E8fFfFcb65A5a578cE", weth: "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7" }
|
|
60
60
|
});
|
|
61
61
|
var FEE_TIERS = [100, 500, 3e3, 1e4];
|
|
62
|
-
var HOP_SYMBOLS = ["WETH", "USDC", "USDT"];
|
|
62
|
+
var HOP_SYMBOLS = ["WETH", "USDC", "USDT", "USDT0"];
|
|
63
63
|
var ADDRESS_THIS = "0x0000000000000000000000000000000000000002";
|
|
64
64
|
var ROUTER_ABI = (0, import_viem.parseAbi)([
|
|
65
65
|
"function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)",
|
|
66
66
|
"function exactInput((bytes path, address recipient, uint256 amountIn, uint256 amountOutMinimum) params) payable returns (uint256 amountOut)",
|
|
67
67
|
"function unwrapWETH9(uint256 amountMinimum, address recipient) payable",
|
|
68
|
+
"function refundETH() payable",
|
|
68
69
|
"function multicall(uint256 deadline, bytes[] data) payable returns (bytes[] results)",
|
|
69
70
|
"function factory() view returns (address)",
|
|
70
71
|
"function WETH9() view returns (address)"
|
|
@@ -103,7 +104,6 @@ function uniswapVerifyQuote(params, quote) {
|
|
|
103
104
|
} catch {
|
|
104
105
|
return "the router call is not multicall(deadline, legs)";
|
|
105
106
|
}
|
|
106
|
-
if (legs.length !== (nativeOut ? 2 : 1)) return `the multicall has ${legs.length} legs, not a swap${nativeOut ? " and an unwrap" : ""}`;
|
|
107
107
|
const decode = (leg) => {
|
|
108
108
|
try {
|
|
109
109
|
return (0, import_viem.decodeFunctionData)({ abi: ROUTER_ABI, data: leg });
|
|
@@ -111,6 +111,8 @@ function uniswapVerifyQuote(params, quote) {
|
|
|
111
111
|
return null;
|
|
112
112
|
}
|
|
113
113
|
};
|
|
114
|
+
if (nativeIn && legs.length === 2 && decode(legs[1])?.functionName === "refundETH") legs = legs.slice(0, 1);
|
|
115
|
+
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
116
|
const swap = decode(legs[0]);
|
|
115
117
|
const swapTo = nativeOut ? ADDRESS_THIS : recipient;
|
|
116
118
|
if (swap?.functionName === "exactInputSingle") {
|
|
@@ -181,18 +183,27 @@ var DEFAULT_SLIPPAGE_BPS = 50;
|
|
|
181
183
|
var DEFAULT_TTL_MS = 3e5;
|
|
182
184
|
var DEFAULT_DEADLINE_S = 600;
|
|
183
185
|
var MIN_POOL_GAS = 20000n;
|
|
186
|
+
var SQRT_PRICE_FLOOR = 4295128740n;
|
|
187
|
+
var SQRT_PRICE_CEIL = 1461446703485210103287273052203988822378723970341n;
|
|
188
|
+
var PARTIAL_FILL = "pool liquidity runs out before the full amount (partial fill)";
|
|
184
189
|
var QUOTER_ABI = (0, import_viem2.parseAbi)([
|
|
185
190
|
"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)",
|
|
186
191
|
"function quoteExactInput(bytes path, uint256 amountIn) returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)",
|
|
187
192
|
"function factory() view returns (address)",
|
|
188
193
|
"function WETH9() view returns (address)"
|
|
189
194
|
]);
|
|
195
|
+
function decodeQuote(single, raw) {
|
|
196
|
+
const [out, after, , gas] = (0, import_viem2.decodeFunctionResult)({ abi: QUOTER_ABI, functionName: single ? "quoteExactInputSingle" : "quoteExactInput", data: raw });
|
|
197
|
+
const prices = typeof after === "bigint" ? [after] : after;
|
|
198
|
+
return { out, gas, drained: prices.length === 0 || prices.some((p) => p <= SQRT_PRICE_FLOOR || p >= SQRT_PRICE_CEIL) };
|
|
199
|
+
}
|
|
190
200
|
var RPC_BATCH_MAX = 10;
|
|
191
201
|
function uniswapProvider(config) {
|
|
192
202
|
const deployments = config.deployments ?? UNISWAP_V3;
|
|
193
203
|
const slippageDefault = config.defaultSlippageBps ?? DEFAULT_SLIPPAGE_BPS;
|
|
194
204
|
const ttl = config.quoteTtlMs ?? DEFAULT_TTL_MS;
|
|
195
205
|
const deadlineS = config.deadlineSeconds ?? DEFAULT_DEADLINE_S;
|
|
206
|
+
const refundNative = config.refundNativeInput === true;
|
|
196
207
|
if (!Number.isInteger(slippageDefault) || slippageDefault <= 0 || slippageDefault >= 5e3) throw new Error("uniswap: defaultSlippageBps must be 1..4999");
|
|
197
208
|
const verified = /* @__PURE__ */ new Map();
|
|
198
209
|
const chainIdOf = (caip2) => {
|
|
@@ -316,16 +327,22 @@ function uniswapProvider(config) {
|
|
|
316
327
|
signal
|
|
317
328
|
);
|
|
318
329
|
let best = null;
|
|
330
|
+
let partial = false;
|
|
319
331
|
results.forEach((raw, i) => {
|
|
320
332
|
if (typeof raw !== "string" || raw === "0x") return;
|
|
321
333
|
const r = candidates[i];
|
|
322
334
|
try {
|
|
323
|
-
const
|
|
324
|
-
if (out2
|
|
335
|
+
const { out: out2, drained, gas: gas2 } = decodeQuote(!!r.single, raw);
|
|
336
|
+
if (out2 <= 0n) return;
|
|
337
|
+
if (drained) {
|
|
338
|
+
partial = true;
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (!best || out2 > best.out) best = { route: r, out: out2, gas: gas2 };
|
|
325
342
|
} catch {
|
|
326
343
|
}
|
|
327
344
|
});
|
|
328
|
-
if (!best) return refuse("no Uniswap v3 pool route for this pair and amount");
|
|
345
|
+
if (!best) return refuse(partial ? PARTIAL_FILL : "no Uniswap v3 pool route for this pair and amount");
|
|
329
346
|
const { route, out, gas } = best;
|
|
330
347
|
let priceImpactBps;
|
|
331
348
|
const probeIn = amountIn / 1000n;
|
|
@@ -348,6 +365,7 @@ function uniswapProvider(config) {
|
|
|
348
365
|
}
|
|
349
366
|
const bps = params.slippageBps ?? slippageDefault;
|
|
350
367
|
const minOut = out * BigInt(1e4 - bps) / 10000n;
|
|
368
|
+
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`);
|
|
351
369
|
if (params.minAmountOut !== void 0 && minOut < BigInt(params.minAmountOut)) {
|
|
352
370
|
return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`);
|
|
353
371
|
}
|
|
@@ -356,10 +374,12 @@ function uniswapProvider(config) {
|
|
|
356
374
|
const swap = route.single ? (0, import_viem2.encodeFunctionData)({ abi: ROUTER_ABI, functionName: "exactInputSingle", args: [{ tokenIn, tokenOut, fee: route.single.fee, recipient: swapTo, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n }] }) : (0, import_viem2.encodeFunctionData)({ abi: ROUTER_ABI, functionName: "exactInput", args: [{ path: route.path, recipient: swapTo, amountIn, amountOutMinimum: minOut }] });
|
|
357
375
|
const legs = [swap];
|
|
358
376
|
if (nativeOut) legs.push((0, import_viem2.encodeFunctionData)({ abi: ROUTER_ABI, functionName: "unwrapWETH9", args: [minOut, recipient] }));
|
|
377
|
+
const refund = nativeIn && refundNative;
|
|
378
|
+
if (refund) legs.push((0, import_viem2.encodeFunctionData)({ abi: ROUTER_ABI, functionName: "refundETH" }));
|
|
359
379
|
const deadline = BigInt(Math.floor(Date.now() / 1e3) + deadlineS);
|
|
360
380
|
const data = (0, import_viem2.encodeFunctionData)({ abi: ROUTER_ABI, functionName: "multicall", args: [deadline, legs] });
|
|
361
381
|
const pools = route.single ? 1n : BigInt((route.path.length - 42) / 46);
|
|
362
|
-
const gasLimit = gas >= MIN_POOL_GAS * pools ? gas * 3n / 2n + 120000n + (nativeOut ? 40000n : 0n) : void 0;
|
|
382
|
+
const gasLimit = gas >= MIN_POOL_GAS * pools ? gas * 3n / 2n + 120000n + (nativeOut ? 40000n : 0n) + (refund ? 10000n : 0n) : void 0;
|
|
363
383
|
return {
|
|
364
384
|
provider: "uniswap",
|
|
365
385
|
intentId: `uniswap:${chainId}`,
|
|
@@ -399,7 +419,9 @@ function uniswapProvider(config) {
|
|
|
399
419
|
/**
|
|
400
420
|
* Right before broadcast (after any approval): re-quote the SAME route on
|
|
401
421
|
* chain. If the pool now pays less than the signed minimum, the swap would
|
|
402
|
-
* only revert and burn gas — refuse it here with the reason instead.
|
|
422
|
+
* only revert and burn gas — refuse it here with the reason instead. A pool
|
|
423
|
+
* that no longer holds enough for the whole input (it would fill part of it)
|
|
424
|
+
* is refused the same way.
|
|
403
425
|
*/
|
|
404
426
|
async preflightDeposit(quote) {
|
|
405
427
|
const chainId = Number(quote.intentId.split(":")[1]);
|
|
@@ -409,7 +431,8 @@ function uniswapProvider(config) {
|
|
|
409
431
|
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)] });
|
|
410
432
|
const [raw] = await rpc(chainId, [call(d.quoter, data)]);
|
|
411
433
|
if (typeof raw !== "string" || raw === "0x") throw new Error("uniswap: the pool no longer quotes this route \u2014 refresh and try again");
|
|
412
|
-
const
|
|
434
|
+
const { out, drained } = decodeQuote(!!pd.fee, raw);
|
|
435
|
+
if (drained) throw new Error(`uniswap: ${PARTIAL_FILL} \u2014 the pool can no longer take this swap. Nothing was sent; refresh the quote.`);
|
|
413
436
|
if (out < BigInt(pd.minOut)) {
|
|
414
437
|
throw new Error(`uniswap: price moved \u2014 the pool now pays ${out}, under your minimum ${pd.minOut}. Nothing was sent; refresh the quote.`);
|
|
415
438
|
}
|