@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.
- package/dist/activity.cjs +23 -20
- 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-Dumvcb4A.d.cts → addresses-B8Qq_0DN.d.cts} +1 -1
- package/dist/{addresses-Dumvcb4A.d.ts → addresses-B8Qq_0DN.d.ts} +1 -1
- package/dist/{chunk-ZOLQRZNH.js → chunk-32CIYNG2.js} +24 -21
- package/dist/chunk-32CIYNG2.js.map +1 -0
- package/dist/{chunk-XJDPJSBT.js → chunk-6ZGWUPLL.js} +36 -24
- package/dist/chunk-6ZGWUPLL.js.map +1 -0
- package/dist/{chunk-M55L67V5.js → chunk-HPS3TTCB.js} +3 -3
- package/dist/index.cjs +57 -42
- 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 +57 -42
- 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 +57 -42
- package/dist/provider.cjs.map +1 -1
- package/dist/provider.d.cts +1 -1
- package/dist/provider.d.ts +1 -1
- package/dist/provider.js +2 -2
- package/package.json +3 -3
- package/dist/chunk-XJDPJSBT.js.map +0 -1
- package/dist/chunk-ZOLQRZNH.js.map +0 -1
- /package/dist/{chunk-M55L67V5.js.map → chunk-HPS3TTCB.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;AAAA,SAAQ,sBAAsB,oBAAoB,cAAc,YAAY,gBAAyB;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,YAAM,UAAU,OAAO,IAAI,SAAS,MAAM,GAAG,EAAE,CAAC,CAAC;AACjD,UAAI,CAAC,YAAY,OAAO,KAAK,CAAC,OAAO,QAAQ,OAAO,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;","names":["error","out","gas"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
uniswapProvider
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-6ZGWUPLL.js";
|
|
4
4
|
import {
|
|
5
5
|
UNISWAP_V3
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-32CIYNG2.js";
|
|
7
7
|
|
|
8
8
|
// src/protocol.ts
|
|
9
9
|
import { SingleProviderSwap2 } from "@anywalletkit/protocol-swap2-core/swap2/single";
|
|
@@ -29,4 +29,4 @@ var UniswapSwap2Protocol = class extends SingleProviderSwap2 {
|
|
|
29
29
|
export {
|
|
30
30
|
UniswapSwap2Protocol
|
|
31
31
|
};
|
|
32
|
-
//# sourceMappingURL=chunk-
|
|
32
|
+
//# sourceMappingURL=chunk-HPS3TTCB.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -39,6 +39,7 @@ module.exports = __toCommonJS(src_exports);
|
|
|
39
39
|
// src/addresses.ts
|
|
40
40
|
var import_viem = require("viem");
|
|
41
41
|
var import_util = require("@anywalletkit/protocol-swap2-core/util");
|
|
42
|
+
var import_errors = require("@anywalletkit/protocol-swap2-core/errors");
|
|
42
43
|
var UNISWAP_V3 = Object.freeze({
|
|
43
44
|
1: { factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984", quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e", router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45", weth: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" },
|
|
44
45
|
10: { factory: "0x1F98431c8aD98523631AE4a59f267346ea31F984", quoter: "0x61fFE014bA17989E743c5F6cB21bF9697530B21e", router: "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45", weth: "0x4200000000000000000000000000000000000006" },
|
|
@@ -78,18 +79,19 @@ var ROUTER_ABI = (0, import_viem.parseAbi)([
|
|
|
78
79
|
"function WETH9() view returns (address)"
|
|
79
80
|
]);
|
|
80
81
|
var MAX_PATH_POOLS = 2;
|
|
82
|
+
var notes = (0, import_errors.refusalNotes)();
|
|
81
83
|
function uniswapVerifyQuote(params, quote) {
|
|
82
84
|
const id = /^eip155:[0-9]+$/.test(params.sourceChain) ? Number(params.sourceChain.slice(7)) : NaN;
|
|
83
85
|
const d = Object.prototype.hasOwnProperty.call(UNISWAP_V3, id) ? UNISWAP_V3[id] : void 0;
|
|
84
|
-
if (!d || params.destChain !== params.sourceChain) return "not a same-chain swap on a pinned Uniswap deployment";
|
|
86
|
+
if (!d || params.destChain !== params.sourceChain) return notes.note("not a same-chain swap on a pinned Uniswap deployment", "unsupported_pair");
|
|
85
87
|
const tx = quote.txRequest;
|
|
86
|
-
if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return "the quote carries no router call";
|
|
87
|
-
if ((0, import_viem.getAddress)(tx.to) !== (0, import_viem.getAddress)(d.router)) return `the call targets ${tx.to}, not the SwapRouter
|
|
88
|
+
if (!tx?.data || !tx.to || tx.serializedTx !== void 0) return notes.note("the quote carries no router call", "policy_refused");
|
|
89
|
+
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");
|
|
88
90
|
const src = (0, import_util.sourceAssetOf)(params);
|
|
89
|
-
if (!src) return `unknown source token ${params.sourceToken}
|
|
91
|
+
if (!src) return notes.note(`unknown source token ${params.sourceToken}`, "unsupported_pair");
|
|
90
92
|
const nativeIn = !src.contract;
|
|
91
93
|
const nativeOut = /^0x0+$/.test(params.destToken);
|
|
92
|
-
if ((nativeIn || nativeOut) && d.nativeWrap === false) return "this chain's router has no wrapped native";
|
|
94
|
+
if ((nativeIn || nativeOut) && d.nativeWrap === false) return notes.note("this chain's router has no wrapped native", "unsupported_pair");
|
|
93
95
|
let tokenIn, tokenOut, recipient, amountIn, minOut;
|
|
94
96
|
try {
|
|
95
97
|
tokenIn = (0, import_viem.getAddress)(nativeIn ? d.weth : src.contract);
|
|
@@ -101,15 +103,15 @@ function uniswapVerifyQuote(params, quote) {
|
|
|
101
103
|
return "the request does not name EVM tokens, a recipient and amounts";
|
|
102
104
|
}
|
|
103
105
|
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)) {
|
|
104
|
-
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";
|
|
106
|
+
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");
|
|
105
107
|
}
|
|
106
108
|
let legs;
|
|
107
109
|
try {
|
|
108
110
|
const outer = (0, import_viem.decodeFunctionData)({ abi: ROUTER_ABI, data: tx.data });
|
|
109
|
-
if (outer.functionName !== "multicall") return `${outer.functionName} is not multicall(deadline, legs)
|
|
111
|
+
if (outer.functionName !== "multicall") return notes.note(`${outer.functionName} is not multicall(deadline, legs)`, "policy_refused");
|
|
110
112
|
legs = outer.args[1];
|
|
111
113
|
} catch {
|
|
112
|
-
return "the router call is not multicall(deadline, legs)";
|
|
114
|
+
return notes.note("the router call is not multicall(deadline, legs)", "policy_refused");
|
|
113
115
|
}
|
|
114
116
|
const decode = (leg) => {
|
|
115
117
|
try {
|
|
@@ -119,36 +121,37 @@ function uniswapVerifyQuote(params, quote) {
|
|
|
119
121
|
}
|
|
120
122
|
};
|
|
121
123
|
if (nativeIn && legs.length === 2 && decode(legs[1])?.functionName === "refundETH") legs = legs.slice(0, 1);
|
|
122
|
-
if (legs.length !== (nativeOut ? 2 : 1)) return `the multicall has ${legs.length} legs, not a swap${nativeOut ? " and an unwrap" : nativeIn ? " (and a refund)" : ""}
|
|
124
|
+
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");
|
|
123
125
|
const swap = decode(legs[0]);
|
|
124
126
|
const swapTo = nativeOut ? ADDRESS_THIS : recipient;
|
|
125
127
|
if (swap?.functionName === "exactInputSingle") {
|
|
126
128
|
const a = swap.args[0];
|
|
127
|
-
if ((0, import_viem.getAddress)(a.tokenIn) !== tokenIn || (0, import_viem.getAddress)(a.tokenOut) !== tokenOut) return "the swap trades other tokens";
|
|
128
|
-
if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut || a.sqrtPriceLimitX96 !== 0n) return "the swap's input, minimum or price limit is not the quote's";
|
|
129
|
-
if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return `the swap pays ${a.recipient}, not the recipient
|
|
129
|
+
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");
|
|
130
|
+
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");
|
|
131
|
+
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");
|
|
130
132
|
} else if (swap?.functionName === "exactInput") {
|
|
131
133
|
const a = swap.args[0];
|
|
132
134
|
const path = a.path.slice(2);
|
|
133
135
|
const pools = (path.length / 2 - 20) / 23;
|
|
134
|
-
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";
|
|
135
|
-
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";
|
|
136
|
-
if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return "the swap's input or minimum is not the quote's";
|
|
137
|
-
if ((0, import_viem.getAddress)(a.recipient) !== (0, import_viem.getAddress)(swapTo)) return `the swap pays ${a.recipient}, not the recipient
|
|
136
|
+
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");
|
|
137
|
+
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");
|
|
138
|
+
if (a.amountIn !== amountIn || a.amountOutMinimum !== minOut) return notes.note("the swap's input or minimum is not the quote's", "price_check_failed");
|
|
139
|
+
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");
|
|
138
140
|
} else {
|
|
139
|
-
return `${swap?.functionName ?? "an unknown call"} is not exactInputSingle / exactInput
|
|
141
|
+
return notes.note(`${swap?.functionName ?? "an unknown call"} is not exactInputSingle / exactInput`, "policy_refused");
|
|
140
142
|
}
|
|
141
143
|
if (nativeOut) {
|
|
142
144
|
const unwrap = decode(legs[1]);
|
|
143
|
-
if (unwrap?.functionName !== "unwrapWETH9") return `${unwrap?.functionName ?? "an unknown call"} is not unwrapWETH9
|
|
144
|
-
if (unwrap.args[0] !== minOut || (0, import_viem.getAddress)(unwrap.args[1]) !== recipient) return "the unwrap pays someone else or less than the minimum";
|
|
145
|
+
if (unwrap?.functionName !== "unwrapWETH9") return notes.note(`${unwrap?.functionName ?? "an unknown call"} is not unwrapWETH9`, "policy_refused");
|
|
146
|
+
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");
|
|
145
147
|
}
|
|
146
148
|
return null;
|
|
147
149
|
}
|
|
148
150
|
var uniswapPins = Object.freeze({
|
|
149
151
|
callTargets: (chain) => uniswapRouterFor(chain),
|
|
150
152
|
spenders: (chain) => uniswapRouterFor(chain),
|
|
151
|
-
verifyQuote: uniswapVerifyQuote
|
|
153
|
+
verifyQuote: uniswapVerifyQuote,
|
|
154
|
+
reasonOf: (refusal2) => notes.reasonOf(refusal2)
|
|
152
155
|
});
|
|
153
156
|
function uniswapRouterFor(chain) {
|
|
154
157
|
const id = /^eip155:[0-9]+$/.test(chain) ? Number(chain.slice(7)) : NaN;
|
|
@@ -189,6 +192,7 @@ function describeUniswapActivity(tx, ctx, deployments = UNISWAP_V3) {
|
|
|
189
192
|
// src/provider.ts
|
|
190
193
|
var import_swap2_assets = require("@anywalletkit/swap2-assets");
|
|
191
194
|
var import_util3 = require("@anywalletkit/protocol-swap2-core/util");
|
|
195
|
+
var import_errors2 = require("@anywalletkit/protocol-swap2-core/errors");
|
|
192
196
|
var import_core = require("@anywalletkit/core");
|
|
193
197
|
var ZERO = "0x0000000000000000000000000000000000000000";
|
|
194
198
|
var DEFAULT_SLIPPAGE_BPS = 50;
|
|
@@ -239,7 +243,11 @@ function uniswapProvider(config) {
|
|
|
239
243
|
body: JSON.stringify(calls.map((c, id) => ({ jsonrpc: "2.0", id, ...c }))),
|
|
240
244
|
signal: signal ?? (0, import_util3.timeoutSignal)(12e3)
|
|
241
245
|
});
|
|
242
|
-
if (!res.ok)
|
|
246
|
+
if (!res.ok) {
|
|
247
|
+
const error2 = new Error(`HTTP ${res.status}`);
|
|
248
|
+
const info = (0, import_errors2.httpRefusal)(res.status, res.headers?.get?.("retry-after"));
|
|
249
|
+
throw info ? (0, import_errors2.withReason)(error2, info) : error2;
|
|
250
|
+
}
|
|
243
251
|
const body = await res.json();
|
|
244
252
|
if (!Array.isArray(body)) throw new Error(body.error?.message ?? "batch refused");
|
|
245
253
|
const out = calls.map(() => null);
|
|
@@ -249,7 +257,8 @@ function uniswapProvider(config) {
|
|
|
249
257
|
lastErr = e;
|
|
250
258
|
}
|
|
251
259
|
}
|
|
252
|
-
|
|
260
|
+
const error = new Error(`uniswap: no RPC answered on chain ${chainId} (${lastErr instanceof Error ? lastErr.message : String(lastErr)})`);
|
|
261
|
+
throw signal?.aborted ? error : (0, import_errors2.withReason)(error, (0, import_errors2.refusalOf)(lastErr) ?? "upstream_unavailable");
|
|
253
262
|
}
|
|
254
263
|
const call = (to, data) => ({ method: "eth_call", params: [{ to, data }, "latest"] });
|
|
255
264
|
function verifyDeployment(chainId) {
|
|
@@ -263,7 +272,7 @@ function uniswapProvider(config) {
|
|
|
263
272
|
const addr = (r) => typeof r === "string" && r.length >= 42 ? (0, import_viem2.getAddress)(`0x${r.slice(-40)}`) : null;
|
|
264
273
|
const wrapped = d.nativeWrap === false ? (0, import_viem2.getAddress)(ZERO) : (0, import_viem2.getAddress)(d.weth);
|
|
265
274
|
const ok = [rf, qf].every((r) => addr(r) === (0, import_viem2.getAddress)(d.factory)) && addr(rw) === wrapped && addr(qw) === wrapped;
|
|
266
|
-
if (!ok) throw
|
|
275
|
+
if (!ok) throw (0, import_errors2.refusal)("vault_mismatch", `uniswap: the router/quoter on chain ${chainId} do not match the pinned deployment \u2014 refusing`);
|
|
267
276
|
})();
|
|
268
277
|
p.catch(() => verified.delete(chainId));
|
|
269
278
|
verified.set(chainId, p);
|
|
@@ -299,22 +308,22 @@ function uniswapProvider(config) {
|
|
|
299
308
|
return from.chain === to.chain && chainIdOf(from.chain) !== null;
|
|
300
309
|
},
|
|
301
310
|
async getQuote(params, signal) {
|
|
302
|
-
const refuse = (why) => {
|
|
303
|
-
params.onRefusal?.(`uniswap: ${why}
|
|
311
|
+
const refuse = (why, info) => {
|
|
312
|
+
params.onRefusal?.(`uniswap: ${why}`, typeof info === "string" ? { reason: info } : info);
|
|
304
313
|
return null;
|
|
305
314
|
};
|
|
306
|
-
if (params.flex) return refuse("amount-flexible deposits are not supported");
|
|
307
|
-
if (params.sourceChain !== params.destChain) return refuse("same-chain swaps only");
|
|
315
|
+
if (params.flex) return refuse("amount-flexible deposits are not supported", "unsupported_pair");
|
|
316
|
+
if (params.sourceChain !== params.destChain) return refuse("same-chain swaps only", "unsupported_pair");
|
|
308
317
|
const chainId = chainIdOf(params.sourceChain);
|
|
309
|
-
if (chainId === null) return refuse(`no Uniswap v3 deployment or RPC for ${params.sourceChain}
|
|
318
|
+
if (chainId === null) return refuse(`no Uniswap v3 deployment or RPC for ${params.sourceChain}`, "unsupported_pair");
|
|
310
319
|
const d = deployments[chainId];
|
|
311
320
|
const src = (0, import_util3.sourceAssetOf)(params);
|
|
312
|
-
if (!src) return refuse(`unknown source token ${params.sourceToken}
|
|
321
|
+
if (!src) return refuse(`unknown source token ${params.sourceToken}`, "unsupported_pair");
|
|
313
322
|
const nativeIn = !src.contract;
|
|
314
323
|
const nativeOut = /^0x0+$/.test(params.destToken);
|
|
315
|
-
if ((nativeIn || nativeOut) && d.nativeWrap === false) return refuse("this chain's router has no wrapped native \u2014 swap the coin's ERC-20 instead");
|
|
316
|
-
if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address");
|
|
317
|
-
if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address");
|
|
324
|
+
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");
|
|
325
|
+
if (!nativeOut && !/^0x[0-9a-fA-F]{40}$/.test(params.destToken)) return refuse("destination token must be an EVM address", "unsupported_pair");
|
|
326
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(params.destAddress)) return refuse("recipient must be an EVM address", "recipient_mismatch");
|
|
318
327
|
let amountIn;
|
|
319
328
|
try {
|
|
320
329
|
amountIn = BigInt(params.amountIn);
|
|
@@ -324,7 +333,7 @@ function uniswapProvider(config) {
|
|
|
324
333
|
if (amountIn <= 0n) return refuse("amount must be positive");
|
|
325
334
|
const tokenIn = (0, import_viem2.getAddress)(nativeIn ? d.weth : src.contract);
|
|
326
335
|
const tokenOut = (0, import_viem2.getAddress)(nativeOut ? d.weth : params.destToken);
|
|
327
|
-
if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? "that is a wrap/unwrap, not a swap" : "same token in and out");
|
|
336
|
+
if (tokenIn === tokenOut) return refuse(nativeIn || nativeOut ? "that is a wrap/unwrap, not a swap" : "same token in and out", "unsupported_pair");
|
|
328
337
|
try {
|
|
329
338
|
await verifyDeployment(chainId);
|
|
330
339
|
const candidates = routes(chainId, params.sourceChain, tokenIn, tokenOut);
|
|
@@ -354,7 +363,7 @@ function uniswapProvider(config) {
|
|
|
354
363
|
} catch {
|
|
355
364
|
}
|
|
356
365
|
});
|
|
357
|
-
if (!best) return refuse(partial ? PARTIAL_FILL : "no Uniswap v3 pool route for this pair and amount");
|
|
366
|
+
if (!best) return refuse(partial ? PARTIAL_FILL : "no Uniswap v3 pool route for this pair and amount", partial ? "insufficient_liquidity" : "no_route");
|
|
358
367
|
const { route, out, gas } = best;
|
|
359
368
|
let priceImpactBps;
|
|
360
369
|
const probeIn = amountIn / 1000n;
|
|
@@ -377,9 +386,9 @@ function uniswapProvider(config) {
|
|
|
377
386
|
}
|
|
378
387
|
const bps = params.slippageBps ?? slippageDefault;
|
|
379
388
|
const minOut = out * BigInt(1e4 - bps) / 10000n;
|
|
380
|
-
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
|
|
389
|
+
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");
|
|
381
390
|
if (params.minAmountOut !== void 0 && minOut < BigInt(params.minAmountOut)) {
|
|
382
|
-
return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})
|
|
391
|
+
return refuse(`floor breach (min=${minOut} < floor=${params.minAmountOut})`, "price_check_failed");
|
|
383
392
|
}
|
|
384
393
|
const recipient = (0, import_viem2.getAddress)(params.destAddress);
|
|
385
394
|
const swapTo = nativeOut ? ADDRESS_THIS : recipient;
|
|
@@ -425,7 +434,7 @@ function uniswapProvider(config) {
|
|
|
425
434
|
}
|
|
426
435
|
};
|
|
427
436
|
} catch (e) {
|
|
428
|
-
return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, "") : String(e));
|
|
437
|
+
return refuse(e instanceof Error ? e.message.replace(/^uniswap: /, "") : String(e), (0, import_errors2.refusalOf)(e));
|
|
429
438
|
}
|
|
430
439
|
},
|
|
431
440
|
/**
|
|
@@ -442,16 +451,22 @@ function uniswapProvider(config) {
|
|
|
442
451
|
if (!d || !pd.amountIn || !pd.minOut || !pd.tokenIn || !pd.tokenOut) return;
|
|
443
452
|
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)] });
|
|
444
453
|
const [raw] = await rpc(chainId, [call(d.quoter, data)]);
|
|
445
|
-
if (typeof raw !== "string" || raw === "0x") throw
|
|
446
|
-
|
|
447
|
-
|
|
454
|
+
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");
|
|
455
|
+
let quoted;
|
|
456
|
+
try {
|
|
457
|
+
quoted = decodeQuote(!!pd.fee, raw);
|
|
458
|
+
} catch (e) {
|
|
459
|
+
throw e instanceof Error ? (0, import_errors2.withReason)(e, "upstream_unavailable") : e;
|
|
460
|
+
}
|
|
461
|
+
const { out, drained } = quoted;
|
|
462
|
+
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.`);
|
|
448
463
|
if (out < BigInt(pd.minOut)) {
|
|
449
|
-
throw
|
|
464
|
+
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.`);
|
|
450
465
|
}
|
|
451
466
|
},
|
|
452
467
|
async buildDeposit(quote) {
|
|
453
468
|
const tx = quote.txRequest;
|
|
454
|
-
if (!tx?.to || !tx.data) throw
|
|
469
|
+
if (!tx?.to || !tx.data) throw (0, import_errors2.refusal)("policy_refused", "swap2: Uniswap quote has no transaction request");
|
|
455
470
|
return {
|
|
456
471
|
chain: "",
|
|
457
472
|
to: tx.to,
|