Core Idea of Uniswap V2 - constant product AMM
- Code and test cases : https://github.com/hiteshjoshi1/uni-v2-playground/tree/main
- Uniswap V2 is a decentralized exchange protocol that implements an automated market maker (AMM) model using a constant product market maker (CPMM) formula. The fundamental idea is to create permissionless, decentralized liquidity pools for token pairs (e.g., ETH/USDC) where anyone can provide liquidity or trade without relying on traditional order books or centralized intermediaries. Instead of matching buyers and sellers, the pool uses a mathematical invariant to determine prices and execute trades automatically. The key invariant is x * y = k, where:
- x is the reserve of token0 (one asset in the pair).
- y is the reserve of token1 (the other asset).
- k is a constant that remains unchanged during trades (but increases when liquidity is added and decreases when removed).
This formula ensures that trades adjust the reserves proportionally, causing the price (the ratio of reserves) to change dynamically based on supply and demand.
Swap’s math intuition
- xy = k, This invariant is maintained
- Example, token0 = 1 and token1 = 1000 Effectively, the liquidity provider is saying 1 token0 = 1000 token1 so x = 1, y 1000 and k = 1000
Example1: Swap 0.5 token0 in for token1
- Now let's say a user wants to Swap 0.5 token0 in for token1 Effective balance to swap = 0.5 * 0.997 ≈ 0.4985 (0.3% goes to fees) Now, we need to figure out how much 0.4985 token0 is equal to in token1 and return that to user
- This is "constant product" AMM, it maintains the product invariant, so
(x + Δx) * (y - Δy) = k
we want Δy, so
Δy = y - (k / (x + Δx))
= 1000 - (1000/ (1+ 0.4985) = 332.67 This is what the user will get 332.67 token1 for his 0.5 token0. New reserves: ~1.5 token0 AND ~667.33 token1 (k≈1000.5). 5. This means that after the swap, in the pool 1.5 token0 = 667.33 token1 or 1 token0 = 667.33/1.5 = 444.89 token1
So the price in the pool changed from 1 token0 = 1000 token1 to 1 token0 = 444.89 token1
Example2: Swap 500 token1 in for token0
Effective balance to be swapped = 500*0.997 = 498.5
new reserve1 = 1000+498.5
(x - Δx) * (y + Δy) = k