Advanced
AMMs Deep Dive — Hands-on lab
Build a minimal x·y=k AMM.
Developer Advanced
6/8 — AMMs Deep Dive — Hands-on lab
Simulate firstUse a spreadsheet or script to simulate swaps with 0.3% fees and verify outputs match x·y=k after fees.
Instrument everythingTrack reserves before/after, fee growth, and cumulative prices so you can assert invariants.
Output with fee
amountOut = (y · amountInAfterFee) ÷ (x + amountInAfterFee)
amountInAfterFee = amountIn × (1 − feeBps/10,000)
Steps
- Pick starting reserves (e.g.,:10 ETH, 18,000 USDC) and a fee (e.g., 30 bps). Simulate a few trades; verify k increases.
- Add minOutput (slippage) calculation:And reject trades that would exceed user tolerance.
- Graph price impact vs:Trade size to visualize where slippage becomes painful.
- Emit events (Swap, Mint,:Burn) in your sim and confirm reserves in logs match your math.
- Optional:Derive a simple TWAP by tracking cumulative prices per block and query it in tests.