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.
🎯 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
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 () and Token B ().
Reserves: x + y → Invariant Check
x * y >= k
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:
Where:
- is the reserve of Token A.
- is the reserve of Token B.
- is a constant value.
The Rule: The product must remain constant after the trade (ignoring fees).
Step-by-Step Mechanics
-
State 0: The pool has 10 ETH () and 20,000 USDC ().
- .
- Price of ETH = USDC.
-
The Trade: You want to buy 1 ETH. You remove 1 ETH from the pool.
- New ETH reserve () = .
-
The Constraint: To keep , we must solve for the new USDC reserve ().
- USDC.
-
The Payment:
- Old USDC () = 20,000.
- New USDC () = 22,222.22.
- Input required = USDC.
Result: You paid 2,222.22 USDC for 1 ETH. Effective Price: USDC/ETH. Spot Price was: USDC/ETH. Slippage: ~11%.
| Concept | Order Book | AMM |
|---|---|---|
| Price Discovery | Supply/Demand equilibrium | Mathematical curve |
| Counterparty | Another user | Smart Contract |
| Liquidity | Active orders | Passive pool deposits |
| Slippage | Depends on order depth | Depends 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 ():
If ETH goes up 4x ():
- Numerator:
- Denominator:
- Result: 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 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 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 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:
- How much USDC do you need to pair with your 10 ETH?
- If you deposit, what is the value of ?
Exercise 3: Curve vs. Uniswap (Advanced)
Scenario: You are designing an AMM for a Wrapped Bitcoin (WBTC) vs. Bitcoin (BTC) pair. Task: Explain why is a bad choice for this pair, and draw the shape of the curve you would want instead (flatter top).
Knowledge Check
- Why does an AMM typically have higher slippage than a centralized exchange for large trades?
- Does ever change?
- If you are an LP, do you want high volatility or low volatility?
- Who is the counterparty in an AMM trade?
- What happens to and reserves when a trade happens?
Answers
- Because liquidity is spread across the entire price curve , whereas CEX liquidity is concentrated around the spread.
- Yes, 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).
- 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).
- The Smart Contract (or strictly speaking, the mathematical formula).
- They slide along the hyperbola . If you buy , decreases and increases.
Summary
- Fundamentally: AMMs replace human order books with the conservation law .
- Determinism: Price is a function of the ratio of reserves. .
- 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