Skip to content

Quote & swap via Uniswap

Quote V2 and V3 routes, apply slippage and swap safely.

Stargaze routes swaps through the official Uniswap deployments; it has no router of its own. This guide reproduces the logic of hooks/useSwap.ts: quote every route, take the best output, derive a minimum from your slippage, simulate, then sign.

Addresses

From lib/config/uniswap.ts (uniswap[chainId]). Routers and the quoter can be overridden with NEXT_PUBLIC_UNISWAP_* env vars; V3 fee tiers are V3_FEE_TIERS = [100, 500, 3000, 10000].

1. Quote every route

Query V2 getAmountsOut and V3 QuoterV2 quoteExactInputSingle for each fee tier in parallel. QuoterV2 is not a view function, so call it with simulateContract. Routes that revert or return zero are ignored.

quote.ts
import type { Address, PublicClient } from "viem";import { v2RouterAbi, v3QuoterAbi } from "@/lib/web3/abis";import { uniswap, V3_FEE_TIERS } from "@/lib/config/uniswap"; type Route = { kind: "v2" } | { kind: "v3"; fee: number }; export async function bestQuote(client: PublicClient, chainId: 1 | 11155111, tokenIn: Address, tokenOut: Address, amountIn: bigint) {  const u = uniswap[chainId];  const tasks: Promise<{ route: Route; out: bigint }>[] = [    client      .readContract({ address: u.v2Router, abi: v2RouterAbi, functionName: "getAmountsOut", args: [amountIn, [tokenIn, tokenOut]] })      .then((a) => ({ route: { kind: "v2" } as Route, out: a[a.length - 1] })),    ...V3_FEE_TIERS.map((fee) =>      client        .simulateContract({          address: u.v3Quoter, abi: v3QuoterAbi, functionName: "quoteExactInputSingle",          args: [{ tokenIn, tokenOut, amountIn, fee, sqrtPriceLimitX96: 0n }],        })        .then((r) => ({ route: { kind: "v3", fee } as Route, out: r.result[0] })),    ),  ];  const ok = (await Promise.allSettled(tasks)).flatMap((s) => (s.status === "fulfilled" && s.value.out > 0n ? [s.value] : []));  return ok.length ? ok.reduce((a, b) => (b.out > a.out ? b : a)) : null; // null = no route}

Buying uses WETH as tokenIn, selling uses it as tokenOut. The app estimates price impact by quoting the same route with 1/10,000 of the amount and comparing the two rates.

2. Apply slippage

slippage.ts
const slippageBps = 50n; // 0.5 %const minOut = (quote.out * (10_000n - slippageBps)) / 10_000n;const deadline = BigInt(Math.floor(Date.now() / 1000) + 20 * 60);

3. Build the call

RouteBuy (ETH → token)Sell (token → ETH)
V2swapExactETHForTokensSupportingFeeOnTransferTokens(minOut, [weth, token], to, deadline) with value = amountInswapExactTokensForETHSupportingFeeOnTransferTokens(amountIn, minOut, [token, weth], to, deadline)
V3SwapRouter02 multicall(deadline, [exactInputSingle({ tokenIn: weth, …, recipient: to })]) with value = amountInmulticall(deadline, [exactInputSingle({ tokenIn: token, tokenOut: weth, recipient: 0x…0002 }), unwrapWETH9(minOut, to)])

For a V3 sell the router keeps the WETH (ADDRESS_THIS = 0x0000000000000000000000000000000000000002) and unwrapWETH9 sends native ETH to you. Selling first needs an ERC-20 approve(router, amountIn) for whichever router the best route uses — wait for that receipt before swapping.

build-v3-buy.ts
import { encodeFunctionData } from "viem";import { v3RouterAbi } from "@/lib/web3/abis"; const call = {  address: u.v3Router,  abi: v3RouterAbi,  functionName: "multicall",  args: [deadline, [    encodeFunctionData({      abi: v3RouterAbi,      functionName: "exactInputSingle",      args: [{ tokenIn: u.weth, tokenOut: token, fee: quote.route.fee, recipient: account, amountIn, amountOutMinimum: minOut, sqrtPriceLimitX96: 0n }],    }),  ]],  value: amountIn,} as const;

4. Simulate, sign, confirm

swap.ts
// the router must exist on THIS chainconst code = await publicClient.getCode({ address: call.address });if (!code || code === "0x") throw new Error("Uniswap router not found on this network"); // slippage, liquidity and deadline reverts surface here, before signingconst { request } = await publicClient.simulateContract({ ...call, account });const hash = await wallet.writeContract(request); const receipt = await publicClient.waitForTransactionReceipt({ hash });if (receipt.status !== "success") throw new Error("Swap reverted on-chain");