Usage of AMMs Explained: Automated Market Makers

Uniswap, Curve, and x*y=k. Learn how decentralized exchanges work without order books, from the constant product formula to impermanent loss mechanics.

Intermediate 40 min read Expert Version →

🎯 What You'll Learn

  • Understand the mathematical determinism of liquidity pools
  • Implement the Constant Product Formula in Python
  • Calculate Impermanent Loss down to the decimal
  • Analyze the MEV surface area of an AMM swap
  • Compare CPMM vs. StableSwap invariants

📚 Prerequisites

Before this lesson, you should understand:

Introduction

In traditional finance, liquidity is human. Market makers are institutions that actively place buy and sell orders. If they unplug their servers, the market freezes.

In DeFi, liquidity is mathematical. An Automated Market Maker (AMM) is a smart contract that holds assets and trades against anyone who asks, at a price determined purely by a formula. It never sleeps, never discriminates, and never cancels an order.

But this automation comes at a cost: Impermanent Loss and Slippage. In this lesson, we will deconstruct the physics of the AMM, write the pricing code yourself, and verify why “providing liquidity” is effectively selling volatility.


What Is an AMM?

An AMM is a robot that is always willing to quote a price between two assets. Unlike an order book, where you need a counterparty (another human) to match your trade, an AMM is the counterparty.

The Problem It Solves

Order books are expensive to run on a blockchain. Every time a maker posts an order, cancels it, or updates it, they pay gas fees. This makes high-frequency market making impossible on L1 Ethereum.

The AMM solves this by passive liquidity. Users deposit tokens into a contract (a “Pool”), and the contract executes trades according to a conservation function.


The Fundamentals: Liquidity Pools

A liquidity pool is a smart contract holding reserves of two tokens, Token A (xx) and Token B (yy).

User Funds Liquidity Pool
Reserves: x + y
Invariant Check
x * y >= k
New Price

When you trade, you are adding one token to the pool and removing the other. The pool accepts your trade only if the mathematical “invariant” remains satisfied.


How It Works: The Constant Product Formula

The most famous AMM model (Uniswap V2) uses the Constant Product Formula:

xy=kx \cdot y = k

Where:

  • xx is the reserve of Token A.
  • yy is the reserve of Token B.
  • kk is a constant value.

The Rule: The product kk must remain constant after the trade (ignoring fees).

Step-by-Step Mechanics

  1. State 0: The pool has 10 ETH (xx) and 20,000 USDC (yy).

    • k=10×20,000=200,000k = 10 \times 20,000 = 200,000.
    • Price of ETH = y/x=2,000y / x = 2,000 USDC.
  2. The Trade: You want to buy 1 ETH. You remove 1 ETH from the pool.

    • New ETH reserve (xnewx_{new}) = 101=910 - 1 = 9.
  3. The Constraint: To keep k=200,000k = 200,000, we must solve for the new USDC reserve (ynewy_{new}).

    • 9×ynew=200,0009 \times y_{new} = 200,000
    • ynew=22,222.22y_{new} = 22,222.22 USDC.
  4. The Payment:

    • Old USDC (yy) = 20,000.
    • New USDC (ynewy_{new}) = 22,222.22.
    • Input required = 22,222.2220,000=2,222.2222,222.22 - 20,000 = 2,222.22 USDC.

Result: You paid 2,222.22 USDC for 1 ETH. Effective Price: 2,222.222,222.22 USDC/ETH. Spot Price was: 2,0002,000 USDC/ETH. Slippage: ~11%.

ConceptOrder BookAMM
Price DiscoverySupply/Demand equilibriumMathematical curve
CounterpartyAnother userSmart Contract
LiquidityActive ordersPassive pool deposits
SlippageDepends on order depthDepends on pool size (and formula)

AMM in Practice: Python implementation

Let’s simulate a swap to see exactly how slippage scales with trade size.

def calculate_swap(reserve_x, reserve_y, amount_in_x):
    """
    Simulates a swap of X for Y using x * y = k.
    Fees are ignored for simplicity.
    """
    k = reserve_x * reserve_y
    new_reserve_x = reserve_x + amount_in_x
    
    # x_new * y_new = k  =>  y_new = k / x_new
    new_reserve_y = k / new_reserve_x
    
    amount_out_y = reserve_y - new_reserve_y
    
    effective_price = amount_in_x / amount_out_y
    spot_price = reserve_x / reserve_y # Price of Y in terms of X
    
    return {
        "amount_out": round(amount_out_y, 4),
        "effective_price": round(effective_price, 4),
        "slippage_percent": round(((effective_price - spot_price) / spot_price) * 100, 2)
    }

# Pool: 100 ETH, 200,000 USDC
# Spot price: 2000 USDC/ETH
print(calculate_swap(200000, 100, 2000)) # Swap 2000 USDC for ETH
print(calculate_swap(200000, 100, 20000)) # Swap 20000 USDC for ETH (Large trade)

Expected Output:

{'amount_out': 0.9901, 'effective_price': 2020.0, 'slippage_percent': 1.0}
{'amount_out': 9.0909, 'effective_price': 2200.0, 'slippage_percent': 10.0}

Notice that increasing the trade size by 10x increased the slippage by 10x. This is linear slippage, a property of the constant product formula (for small trades).


Deep Dive: Impermanent Loss (IL)

This is the most misunderstood concept in DeFi. Impermanent Loss is not about losing money compared to your deposit. It is about losing money compared to holding.

When you provide liquidity, you are effectively selling your winners and buying losers to keep the pool balanced.

The Mechanics of Loss

If the price of ETH goes up, people buy ETH from the pool (giving you USDC).

  • You end up with less ETH and more USDC.
  • Since ETH went up, you would have been better off holding that ETH.

The formula for Impermanent Loss as a function of price ratio change (r=Pnew/Poldr = P_{new} / P_{old}):

IL(r)=2r1+r1IL(r) = \frac{2 \sqrt{r}}{1+r} - 1

If ETH goes up 4x (r=4r=4):

  • 4=2\sqrt{4} = 2
  • Numerator: 2×2=42 \times 2 = 4
  • Denominator: 1+4=51 + 4 = 5
  • Result: 4/51=0.24/5 - 1 = -0.2 or -20%

You have 20% less portfolio value than if you had just held the tokens in your wallet.


Common Mistakes and How to Avoid Them

❌ Mistake 1: Ignoring Gas Costs in APY

Wrong: “The pool pays 10% APY, and I have 100toinvest."Right:Executingtheapproveanddeposittransactionsmightcost100 to invest." **Right:** Executing the `approve` and `deposit` transactions might cost 20-50 in gas on Ethereum L1. You are instantly down 50%. Only LP on L1 with significant capital, or use L2s.

❌ Mistake 2: Thinking Stablecoin Pairs Have Zero Risk

Wrong: “USDC-USDT has no impermanent loss because they are both 1."Right:Ifonestablecoindepegs(dropsto1." **Right:** If one stablecoin de-pegs (drops to 0.90), the AMM will sell all the good coins for the bad coins until the pool is 100% filled with the failed token. This is called the “death spiral.”

❌ Mistake 3: Misunderstanding “Impermanent”

Wrong: “It’s only a loss if I withdraw.” Right: “Impermanent” means “recoverable if price returns to entry.” If the price change is permanent (e.g., ETH goes to $10k and stays there), the loss is permanent.


Practice Exercises

Exercise 1: The Arb Bot (Beginner)

Scenario: A pool has 1000 USDC and 10 ETH. Spot price is 100.BinancepriceforETHpumpsto100. Binance price for ETH pumps to 110. Task: Calculate how much ETH you need to buy from the pool to move the AMM price to $110.

Exercise 2: Liquidity Planning (Intermediate)

Scenario: You have 10 ETH and want to provide liquidity in a Uniswap V2 pool. The current price is 2000 USDC/ETH. Task:

  1. How much USDC do you need to pair with your 10 ETH?
  2. If you deposit, what is the value of kk?

Exercise 3: Curve vs. Uniswap (Advanced)

Scenario: You are designing an AMM for a Wrapped Bitcoin (WBTC) vs. Bitcoin (BTC) pair. Task: Explain why xy=kx \cdot y = k is a bad choice for this pair, and draw the shape of the curve you would want instead (flatter top).


Knowledge Check

  1. Why does an AMM typically have higher slippage than a centralized exchange for large trades?
  2. Does kk ever change?
  3. If you are an LP, do you want high volatility or low volatility?
  4. Who is the counterparty in an AMM trade?
  5. What happens to xx and yy reserves when a trade happens?
Answers
  1. Because liquidity is spread across the entire price curve (0,)(0, \infty), whereas CEX liquidity is concentrated around the spread.
  2. Yes, kk increases when fees are added to the pool reserves (technically growing the pool), or when LPs add/remove liquidity. It is only constant during a swap (ignoring fees).
  3. Low volatility. High volatility increases Impermanent Loss. Ideally, you want the price to oscillate heavily (generating fees) but return to exactly your entry price (erasing IL).
  4. The Smart Contract (or strictly speaking, the mathematical formula).
  5. They slide along the hyperbola xy=kx \cdot y = k. If you buy xx, xx decreases and yy increases.

Summary

  • Fundamentally: AMMs replace human order books with the conservation law xy=kx \cdot y = k.
  • Determinism: Price is a function of the ratio of reserves. PA=y/xP_A = y / x.
  • Cost: Traders pay slippage; LPs pay Impermanent Loss.
  • Incentive: LPs are indispensable. They are compensated with trading fees (e.g., 0.3%) to offset the risk of IL.

Questions about this lesson? Working on related infrastructure?

Let's discuss