This skill covers simulating Uniswap swaps, calculating price impact, and analyzing routing decisions.
Use the Quoter contract to simulate swaps without executing:
import { createPublicClient, http, encodeFunctionData } from "viem";
// QuoterV2 for v3 pools
const quote = await client.readContract({
address: quoterV2Address,
abi: quoterV2Abi,
functionName: "quoteExactInputSingle",
args: [
{
tokenIn,
tokenOut,
amountIn,
fee,
sqrtPriceLimitX96: 0n,
},
],
});
// Returns: [amountOut, sqrtPriceX96After, initializedTicksCrossed, gasEstimate]
function calculatePriceImpact(
amountIn: bigint,
amountOut: bigint,
marketPrice: number, // token1/token0
decimals0: number,
decimals1: number,
): number {
const executionPrice =
Number(amountOut) / 10 ** decimals1 / (Number(amountIn) / 10 ** decimals0);
return Math.abs(1 - executionPrice / marketPrice);
}
Calculate minimum amount out:
const minAmountOut = (amountOut * (10000n - BigInt(slippageBps))) / 10000n;
For tokens without direct pools, route through intermediary tokens:
// ETH -> USDC -> DAI (two hops)
const path = encodePacked(
["address", "uint24", "address", "uint24", "address"],
[WETH, 3000, USDC, 100, DAI],
);
const quote = await client.readContract({
address: quoterV2Address,
abi: quoterV2Abi,
functionName: "quoteExactInput",
args: [path, amountIn],
});
Typical gas costs by swap complexity:
Always add a 15-20% buffer to gas estimates.
When building swap tools:
共 1 个版本