Constant Product AMM (Automated Market Maker) - Simplified

This is one of the most important DeFi primitives. Understanding AMMs is essential for auditing any DEX (Decentralized Exchange). Let me break it down step by step.

The Core Concept: x × y = k

This is the fundamental formula of constant product AMMs. Let’s understand what it means.

x = amount of token A in the pool
y = amount of token B in the pool
k = constant (pool's total liquidity)

Formula: x × y = k

Example:
- Pool has 5 ETH and 25,000 DAI
- k = 5 × 25,000 = 125,000
- This k never changes unless liquidity is added

Why “constant product”?


Part 1: Understanding Swaps

The Initial Pool State

Pool contains:
- 5 ETH (token X)
- 25,000 DAI (token Y)

Current price of ETH = 25,000 DAI / 5 ETH = 5,000 DAI per ETH

k = 5 × 25,000 = 125,000

A Trader Swaps: Puts in DAI, Gets out ETH

Scenario: Trader sends 5,000 DAI to the pool, wants to get ETH back.

Using the formula:

Before swap:
x = 5 ETH
y = 25,000 DAI
k = 125,000

After swap:
x = 5 - Δx  (Δx = amount of ETH trader gets)
y = 25,000 + 5,000 = 30,000 DAI

Equation:
(5 - Δx) × 30,000 = 125,000

Solving for Δx:
5 - Δx = 125,000 / 30,000
5 - Δx = 4.167
Δx = 5 - 4.167 = 0.833 ETH

Trader gets: 0.833 ETH

What price did the trader pay?

Price paid = DAI sent / ETH received
Price paid = 5,000 / 0.833 = ~6,000 DAI per ETH

Notice: Before swap price was 5,000 DAI/ETH
         After swap price is ~6,000 DAI/ETH

The price got worse for the trader!
This is called PRICE SLIPPAGE.

Why Does Price Slippage Happen?