Section 5 of 9

Learn
+5 Shields

Uniswap V2 Architecture: Factory + Pair + Router

Uniswap V2 Architecture

Why Three Contracts?

The single-contract AMM you built works, but it has a problem: it only handles one token pair. A real DEX needs to support thousands of pairs. Uniswap V2 solves this with a clean separation into three contracts:

Factory (singleton): Creates and registers new pairs. Uses CREATE2 to give each pair a deterministic address. Anyone can call createPair(tokenA, tokenB).

Pair (one per token pair): Holds reserves, executes swaps, mints/burns LP tokens. This is the contract you have been building. The Factory deploys one per unique pair.

Router (singleton): User-facing convenience contract. Handles slippage protection, multi-hop paths (ETH → USDC → DAI), deadline enforcement, and WETH wrapping. Users interact with the Router, never directly with Pairs.

CREATE2: Deterministic Addresses

The Factory uses CREATE2 to deploy each Pair. This means the Pair address can be calculated without querying the blockchain:

pairAddress = keccak256(
    0xff,
    factoryAddress,
    keccak256(abi.encodePacked(token0, token1)),
    initCodeHash
)

Why does this matter? The Router can calculate Pair addresses without storage lookups. Every getReserves() call avoids an extra contract call to the Factory. This saves gas on every single swap.

Token Ordering

Uniswap V2 always orders tokens by address: token0 < token1. This ensures there is exactly one pair per token combination. createPair(USDC, WETH) and createPair(WETH, USDC) produce the same pair.

What You Will Build Next

In the following sections you will:

  1. Add LP token minting/burning to your Pair contract
  2. Build a Factory that deploys Pairs with CREATE2
  3. Build a Router with multi-hop swaps and slippage protection
  4. Add a TWAP oracle for manipulation-resistant price feeds

Verify Your Understanding

What opcode does Uniswap V2's Factory use to deploy Pair contracts with deterministic addresses?

It is a variant of CREATE that takes a salt parameter.

Knowledge Check

Answer correctly to earn lynx

Verify your understanding