How Uniswap's Router Executes Trades

The Uniswap Router is the smart contract that orchestrates token swaps — finding the best path through pools, computing the output amount, handling approvals, and executing the transfers. Understanding how the router works is essential for understanding MEV, gas optimization, and why some swaps cost more than others despite similar amounts.

? Route Visualizer

Input a token pair to see all possible swap paths, their estimated outputs, and fee costs.

Best Path
USDC → WETH → PEPE
Output: 2.34B PEPE
Fee: 0.599% (2 hops)
Alternative Path
USDC → WETH → (direct check)
Output: pending...
Fee: computing...
Routing is a graph problem: For a USDC→PEPE swap, the router builds a directed graph of all pools and finds paths through token nodes. Direct pools (USDC/PEPE) might have less liquidity than multi-hop paths (USDC→WETH→PEPE). The router computes output for every path and returns the best one.

? Swap Execution Flow Diagram

A Uniswap swap goes through several discrete steps. Each step has a gas cost and a potential failure point. Understanding this flow is key to optimizing swap gas costs and debugging failed transactions.

Token transfer Approval interaction Pool swap call Fee distribution

exactInput vs exactOutput

Two different swap primitives with different risk/reward profiles. Choosing the right one depends on whether you know your input budget or your output requirement.

exactInput
You specify: how much tokenIn to spend
Router calculates: max tokenOut you'll receive

If output < minimumOut → revert
If price moves up → you get less out
If price moves down → you get more out (windfall)

Most common for simple swaps
exactOutput
You specify: how much tokenOut to receive
Router calculates: max tokenIn required

If input > maximumIn → revert
If price moves up → you pay more than expected
If price moves down → you pay less (windfall)

Use when you need a fixed output amount
exactOutput gotcha: With exactOutput, the required input can be higher than expected if price moves unfavorably. If you set maximumIn too conservatively and the price moves against you, the swap reverts — but you've still paid gas for the transaction attempt. Setting a 2-3% maximumIn buffer above the quoted input is standard practice.

Gas Optimization: Why Same-Chain Multi-Hop is Expensive

Each pool interaction costs ~50k-100k gas. A 2-hop swap calls two pools, meaning ~100k-200k extra gas vs a direct swap. This is why aggregators sometimes find that a direct pool with slightly worse pricing beats a multi-hop path once gas costs are factored in.

Swap Type Pools Called Est. Gas Gas Cost (~$50)
Direct (1 pool) 1 ~150k ~$7.50
2-hop (USDC→ETH→TOKEN) 2 ~250k ~$12.50
3-hop 3 ~350k ~$17.50
Multicall batch (5 swaps) 5 ~400k ~$20 (amortized)
Aggregation optimization: DEX aggregators like 1inch and 0x split large orders across multiple pools to minimize slippage and gas. A $1M swap might route 40% through Pool A, 35% through Pool B, and 25% through Pool C — finding the optimal split is an optimization problem solved off-chain before the transaction is submitted.

Multi-Hop Path Examples

Multi-hop paths occur when there's no direct pool between your input and output token. The router finds intermediate tokens to bridge through. Each hop adds a fee and gas cost.

USDC → WBTC (Direct)
Path: USDC/WBTC pool
Fee: 0.30% (single hop)
Gas: ~150k
Best when direct pool has deep liquidity
USDC → PEPE (2-hop)
Path: USDC → WETH → PEPE
Fee: 0.599% (2 hops)
Gas: ~250k
No direct USDC/PEPE pool, route through WETH
USDT → ARB (3-hop)
Path: USDT → USDC → WETH → ARB
Fee: ~0.90% (3 hops)
Gas: ~350k
No direct pools, route through most liquid pairs
Path Output Calculation
// For USDC → WETH → PEPE:
amount1 = exactInput(preferredAmount, [USDC, WETH, PEPE])
// Step 1: USDC → WETH at USDC/WETH pool
wethOut = swap(usdcIn * 0.997, USDC/WETH pool)
// Step 2: WETH → PEPE at WETH/PEPE pool
pepeOut = swap(wethOut * 0.997, WETH/PEPE pool)
finalOutput = pepeOut

Router vs DEX Aggregators

The Uniswap Router finds the best path within Uniswap pools. DEX aggregators (0x, 1inch, Paraswap, CowSwap) find the best path across multiple DEXes and can split orders to minimize slippage. For large trades, aggregators usually outperform the raw router.

Uniswap Router

  • Searches only Uniswap V2/V3 pools
  • Single-path routing (one path per swap)
  • No order splitting across pools
  • Lower gas for simple swaps
  • Free to use (no protocol fee)
  • Good for small-medium swaps

DEX Aggregators (0x, 1inch)

  • Searches Uniswap + Sushi + Curve + others
  • Multi-path routing (splits across pools)
  • Optimizes for best net output
  • Higher gas due to more complexity
  • May charge a small protocol fee (0.05%)
  • Better for large or complex swaps
When to use which: For a $1,000 ETH/USDC swap, the router is fine — slippage difference vs an aggregator is cents. For a $500,000 ETH/USDC swap, the aggregator's ability to split across multiple pools could save $5,000+ in slippage, far exceeding the additional gas cost.

SwapRouter02 Interface

The SwapRouter02 contract exposes several functions for different swap scenarios. Understanding these is essential for protocol developers and advanced users.

// Single exactInput swap
function exactInputSingle(tuple) returns (uint256 amountOut)
// Multi-hop exactInput (any path length)
function exactInput(tuple) returns (uint256 amountOut)
// exactOutput variants
function exactOutputSingle(tuple) returns (uint256 amountIn)
function exactOutput(tuple) returns (uint256 amountIn)
// Batch multiple operations atomically
function multicall(bytes[]) returns (bytes[])
exactInputSingle Params
tokenIn: address
tokenOut: address
fee: uint24 (0.05%, 0.30%, 1.00%)
recipient: address
deadline: uint256
amountIn: uint256
amountOutMinimum: uint256
sqrtPriceLimitX96: uint160
exactInput Params
path: bytes (encoded token/fee/token/fee/...)
recipient: address
deadline: uint256
amountIn: uint256
amountOutMinimum: uint256

path is tightly packed: tokenIn-fee-tokenOut-fee-...

How Path Finding Works

When you submit a swap to the Uniswap Router, it needs to find the best path from your input token to your output token. This is a graph traversal problem: each pool is an edge connecting two token nodes, and the router needs to find the path (or combination of paths) that maximizes your output.

The router uses a "best route" algorithm that:

  1. Builds a graph of all token pairs with active pools
  2. For each possible path up to maxHops (default: 3), computes the output amount
  3. Accounts for fees at each hop (compounding: amount * (1-fee1) * (1-fee2) * ...)
  4. Returns the path with the highest output

The key insight: the router doesn't use Dijkstra's algorithm or other optimal-path finders — it uses a bounded greedy search. This means it may miss optimal routes in complex path graphs, which is why DEX aggregators (which use more sophisticated algorithms) often find better paths than the raw router.

Multicall: Batching Multiple Operations

The multicall function lets you batch multiple operations into a single transaction. This is critical for gas optimization — instead of approving, swapping, approving, swapping in separate transactions (each requiring a new block), you can do it all in one transaction with one base cost.

Common multicall patterns:

The gas savings are significant: a separate approval tx costs ~46k gas minimum; when included in a multicall, the approval is batched with the swap and costs only a few thousand extra gas since you're already paying the transaction base fee.

Flash Swaps: Get Token First, Pay Later

Uniswap V2 supports flash swaps — you can receive a token before paying for it, as long as you pay (or return the tokens) within the same transaction. This is possible because the AMM's constant-product invariant is only checked at the end of the transaction — if you don't pay back, the k invariant would be violated and the EVM reverts the entire transaction.

Flash swap use cases:

Flash swap gas is higher than regular swaps because the pool needs to check that you're repaying (or the transaction reverts). The pool essentially extends you a short-term, uncollateralized loan within the transaction — the repayment is mandatory for the tx to succeed.

MEV Exposure in Routing

When you submit a swap to the mempool, MEV bots see it and can exploit it in several ways:

To reduce MEV exposure: use private RPC endpoints (e.g., Flashbots Protect) that hide your transaction from the public mempool, set conservative slippage tolerances (0.1% not 0.5%), and consider using aggregators that have MEV protection built in.

Key Concepts

SwapRouter02
The primary Uniswap V3 router contract (address 0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45). Exposes exactInput, exactOutput, and multicall functions. Replaces older router versions. The UniversalRouter in V4 adds execution permissions and more gas-efficient execution for complex paths.
Path encoding
In multicall and exactInput, the path is encoded as a tightly-packed bytes array: tokenIn (20 bytes) + fee (3 bytes) + tokenOut (20 bytes) + fee (3 bytes) + tokenOut (20 bytes)... For a 2-hop path USDC → WETH → PEPE, the bytes would be: USDC_address + 0.003 + WETH_address + 0.003 + PEPE_address.
sqrtPriceLimitX96
A parameter in exactInputSingle that lets you specify the maximum acceptable price (in sqrt price terms) for the swap. If the pool's price moves beyond this limit during your swap, the transaction reverts. This is a form of slippage protection — you won't accept worse than X price.
Deadline
A parameter in all router functions that specifies the latest block.timestamp at which the swap can execute. If the transaction lands after this deadline, it reverts. This protects against transactions that sit in the mempool and execute at worse prices due to timing drift.
AmountOutMinimum
The minimum output you accept from a swap. If the actual output (accounting for price impact and fees) falls below this, the transaction reverts. This is your slippage protection — it ensures you don't accept worse than X output. Setting it to 0 is dangerous; setting it too high may cause transaction failures in volatile markets.
Multicall batching
The ability to combine multiple function calls into a single transaction. The multicall function takes an array of encoded function calls and executes them in sequence atomically. If any call fails, the entire transaction reverts. This is the primary mechanism for gas-efficient DeFi operations.