AMM Mechanics Deep Dive: Complete DEX Technical Reference
Automated Market Makers (AMM) Fundamentals
What is an AMM?
An Automated Market Maker replaces traditional order books with mathematical formulas to determine prices. Instead of matching buyers and sellers, liquidity providers deposit assets into pools, and traders swap against these pools.
Key Innovation
- No order matching needed - Trades execute instantly
- Permissionless liquidity - Anyone can become a market maker
- 24/7 trading - No market hours
- Composability - Other protocols can integrate
Constant Product Formula (x * y = k)
The Core Math
Pioneered by Uniswap V1/V2:
x * y = k
Where:
x = quantity of token A
y = quantity of token B
k = constant (product of reserves)
Price Derivation
Price of A in terms of B = y / x
Price of B in terms of A = x / y
Trade Execution
When trading Δx of token A for token B:
New state: (x + Δx) * (y - Δy) = k
Solving: Δy = y - k/(x + Δx)
Slippage
Price impact from trade size:
Price impact ≈ Δx / x (for small trades)
Larger trades = more slippage because:
- You're buying up the available liquidity
- Price moves against you as you trade
Impermanent Loss Formula
IL = 2 * sqrt(price_ratio) / (1 + price_ratio) - 1
Where price_ratio = new_price / initial_price
| Price Change | Impermanent Loss |
|---|---|
| 1.25x (25% up) | 0.6% |
| 1.5x (50% up) | 2.0% |
| 2x (100% up) | 5.7% |
| 3x (200% up) | 13.4% |
| 5x (400% up) | 25.5% |
Uniswap Evolution
Uniswap V1 (November 2018)
- ETH pairs only (TOKEN/ETH)
- No direct TOKEN/TOKEN swaps
- Simple constant product
- Foundation proof of concept
Uniswap V2 (May 2020)
Key Improvements:
- ERC20/ERC20 pairs: Any token pair possible
- Price oracles: TWAP (Time-Weighted Average Price)
- Flash swaps: Borrow without collateral (repay in same tx)
- Protocol fee switch: 0.05% to protocol (not activated)
Fee Structure: 0.30% to LPs
Key Contracts (Ethereum):
- Factory: 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f
- Router02: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
Uniswap V3 (May 2021)
Revolutionary Changes:
1. Concentrated Liquidity
LPs provide liquidity within custom price ranges:
Instead of: 0 to ∞
Choose: 1800-2200 USDC per ETH
Benefits:
- Up to 4000x capital efficiency
- Higher fees earned per dollar
- Active management required
2. Multiple Fee Tiers
| Tier | Use Case |
|---|---|
| 0.01% | Stablecoin pairs |
| 0.05% | Stable pairs, high volume |
| 0.30% | Most pairs |
| 1.00% | Exotic/volatile pairs |
3. NFT LP Positions
- Each position is unique NFT
- Tracks price range, liquidity amount
- Enables position as collateral
4. Oracle Improvements
- Up to 65,535 price observations
- More manipulation-resistant
Key Contracts (Ethereum):
- Factory: 0x1F98431c8aD98523631AE4a59f267346ea31F984
- SwapRouter: 0xE592427A0AEce92De3Edee1F18E0157C05861564
- Universal Router: 0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD
Uniswap V4 (2024)
Next Generation Features:
1. Hooks
Custom logic at key points:
- Before/after swap
- Before/after liquidity change
- Dynamic fees
- On-chain limit orders
2. Singleton Design
- All pools in one contract
- Gas savings from reduced calls
- Flash accounting
3. Native ETH Support
- No wrapping required
- Gas savings
4. Custom Implementations
Hooks enable:
- TWAMM (Time-Weighted AMM)
- Dynamic fees based on volatility
- MEV-aware pricing
- Custom oracles
Other Major DEXs
SushiSwap
Uniswap V2 fork with additions:
- SUSHI token incentives
- xSUSHI staking (fee sharing)
- Kashi lending integration
- Trident AMM (concentrated liquidity)
PancakeSwap (BNB Chain)
Dominant BNB Chain DEX:
- V2 and V3 (Uniswap-style)
- CAKE token staking
- IFO (Initial Farm Offerings)
- Prediction market, lottery
Key Contracts (BNB Chain):
- V2 Router: 0x10ED43C718714eb63d5aA57B78B54704E256024E
- V3 Router: 0x1b81D678ffb9C0263b24A97847620C99d213eB14
Curve Finance
Optimized for like-kind assets:
StableSwap Invariant
Modified formula for stablecoins:
A * n^n * sum(x_i) + D = A * D * n^n + D^(n+1) / (n^n * prod(x_i))
Result: Much lower slippage for stable pairs
Key Pools
| Pool | Assets | Use Case |
|---|---|---|
| 3pool | DAI/USDC/USDT | Stablecoin base |
| stETH | ETH/stETH | LST swaps |
| Tricrypto | USDT/WBTC/ETH | Volatile with low slippage |
| frxETH | ETH/frxETH | Frax LST |
veCRV and Gauge Wars
- Lock CRV for veCRV (voting power)
- Vote on liquidity gauge weights
- Protocols bribe voters (Votium, Hidden Hand)
- Creates "Curve Wars" dynamics
Balancer
Multi-asset pools with custom weights:
Weighted Pools:
V = Π (B_i)^(W_i)
Where:
B_i = balance of token i
W_i = weight of token i (sum = 1)
Use Cases:
- Index funds (80/20 pools)
- LBP (Liquidity Bootstrapping)
- Managed pools
1inch (Aggregator)
Not a DEX, but aggregates across DEXs:
- PathFinder algorithm finds best routes
- Splits orders across venues
- Fusion mode: MEV-protected limit orders
- Chi gas token savings
CowSwap
Batch auction model:
- Collect orders for ~30 seconds
- Solvers compete to find best settlement
- Coincidence of Wants (CoW) first
- Remaining via DEXs
Benefits:
- No MEV extraction
- Better prices from batch matching
- Surplus to users
AMM Math Deep Dive
Virtual Reserves (Uniswap V3)
With concentrated liquidity:
L = sqrt(x * y) // Liquidity
For a position in range [pa, pb]:
x = L * (1/sqrt(p) - 1/sqrt(pb)) when p < pb
y = L * (sqrt(p) - sqrt(pa)) when p > pa
Tick Math
Prices stored as ticks:
price = 1.0001^tick
tick = log(price) / log(1.0001)
Tick spacing by fee:
| Fee | Tick Spacing |
|---|---|
| 0.01% | 1 |
| 0.05% | 10 |
| 0.30% | 60 |
| 1.00% | 200 |
TWAP Oracles
Time-Weighted Average Price:
TWAP = (cumulative_price_B - cumulative_price_A) / (time_B - time_A)
Manipulation resistance: Attacker must hold manipulated price for the entire window
Price Impact Calculation
For constant product:
Price impact = Δy/y - Δx/x
≈ 2 * Δx / (x + Δx) // for large trades
For stableswap (Curve): Much lower due to amplification factor A
LP Strategy Considerations
Passive LP (Uniswap V2 / full range V3)
- Set and forget
- Collects fees from all trades
- Subject to impermanent loss
- Best for: Correlated pairs, stable markets
Active LP (Concentrated liquidity)
- Requires rebalancing
- Higher fee capture in range
- Zero fees if price exits range
- Best for: Active managers, volatile pairs where range predictable
Just-In-Time (JIT) Liquidity
MEV strategy targeting LPs:
- Detect large swap
- Add liquidity in exact tick range
- Capture majority of fees
- Remove liquidity immediately
Controversial: Extracts value from passive LPs
Impermanent Loss Mitigation
- Correlated pairs: ETH/stETH has low IL
- Stablecoin pairs: DAI/USDC minimal IL
- Covered calls: Options strategies
- Incentives: Token rewards can offset IL
DEX Selection for Trading
When to Use Each
| Scenario | Best DEX |
|---|---|
| Stablecoin swaps | Curve (lowest slippage) |
| Large trades | Aggregator (1inch, CowSwap) |
| Fast meme trades | Uniswap (most liquidity) |
| MEV-sensitive | CowSwap (no MEV) |
| Low-cap tokens | Check liquidity on Uniswap/Sushi |
Aggregator Comparison
| Aggregator | Specialty |
|---|---|
| 1inch | Best routes, Fusion mode |
| CowSwap | MEV protection |
| Paraswap | Good rates, gas optimization |
| 0x API | Developer-focused |
MEV Extraction Points
DEX-Specific MEV
Uniswap V2:
- Sandwich attacks (most common)
- Simple arbitrage between pools
- Backrun large trades
Uniswap V3:
- JIT liquidity provision
- Tick crossing arbitrage
- Range order fills
Curve:
- Stablecoin depeg arbitrage
- Cross-pool arbitrage
- Virtual price manipulation
Multi-DEX:
- Cross-DEX arbitrage
- Route optimization MEV
- Bridge arbitrage
Flash Loan DEX Patterns
// Example: Arbitrage pattern
1. Flash loan USDC from Aave
2. Buy ETH on Uniswap (lower price)
3. Sell ETH on Sushiswap (higher price)
4. Repay flash loan + fee
5. Keep profit
Router Analysis for MEV
Monitor router transactions:
- Universal Router (complex swaps)
- V2/V3 specific routers
- Aggregator routers
Key Takeaways for DarkZen
- Know the math: Price impact, IL formulas critical
- Monitor multiple DEXs: Arb opportunities across venues
- Understand fee tiers: Affects profit calculations
- Watch liquidity distribution: V3 concentration matters
- Track big swaps: Backrun opportunities
- Oracle mechanics: Flash loan manipulation risks
- Gas optimization: Router choice affects profitability