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.
? 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.
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.
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
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
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) |
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.
Fee: 0.30% (single hop)
Gas: ~150k
Best when direct pool has deep liquidity
Fee: 0.599% (2 hops)
Gas: ~250k
No direct USDC/PEPE pool, route through WETH
Fee: ~0.90% (3 hops)
Gas: ~350k
No direct pools, route through most liquid pairs
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
SwapRouter02 Interface
The SwapRouter02 contract exposes several functions for different swap scenarios. Understanding these is essential for protocol developers and advanced users.
tokenOut: address
fee: uint24 (0.05%, 0.30%, 1.00%)
recipient: address
deadline: uint256
amountIn: uint256
amountOutMinimum: uint256
sqrtPriceLimitX96: uint160
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:
- Builds a graph of all token pairs with active pools
- For each possible path up to maxHops (default: 3), computes the output amount
- Accounts for fees at each hop (compounding: amount * (1-fee1) * (1-fee2) * ...)
- 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:
- Approve + Swap: Approve the router to spend your token, then swap — all in one tx
- Swap + Swap + Swap: Chain multiple swaps (e.g., USDC → ETH → LINK → AAVE)
- Multiple pool interactions: Add liquidity to two different pools in one tx
- Swap + Add liquidity: Swap to get the right token ratio, then add liquidity
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:
- Arbitrage without capital: Receive USDC via flash swap, swap for ETH on another DEX, repay the USDC — net profit without fronting capital
- Liquidation capture: Flash borrow to capture a liquidation opportunity that requires token X before you have token X
- One-block trades: Execute a multi-step trade where each step depends on the previous, all within one atomic transaction
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:
- Sandwich attacks: Bot front-runs your swap (buys, raising the price), your swap executes at worse price, bot sells behind you — capturing your slippage as profit
- Arbitrage extraction: Your swap moves the AMM price; bots arbitrage the price back to fair value and capture the spread
- Cex-dex arbitrage: Your swap is visible before execution; bots trade on CEX to move the price, then your swap fills at the manipulated price
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.