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
  1. Pick starting reserves (e.g.,:10 ETH, 18,000 USDC) and a fee (e.g., 30 bps). Simulate a few trades; verify k increases.
  2. Add minOutput (slippage) calculation:And reject trades that would exceed user tolerance.
  3. Graph price impact vs:Trade size to visualize where slippage becomes painful.
  4. Emit events (Swap, Mint,:Burn) in your sim and confirm reserves in logs match your math.
  5. Optional:Derive a simple TWAP by tracking cumulative prices per block and query it in tests.
← Previous section
Next section →