freecoding.school100% FREE · NO SIGNUP
Yield OceanISSUE #4 of 34

uniswap v4 · hooks · the singleton

Liquidity LuVSThe Sandwich Bot
Liquidity Lu saysUniswap v4 puts every pool in ONE singleton contract and lets each pool register hooks — callbacks before/after swaps, mints, and burns — for custom logic like on-chain limit orders.

Uniswap v4 makes two huge changes. First, the singleton: every pool lives in one contract instead of having a dedicated deployment per pool, killing inter-contract call gas. Second, hooks: at pool creation, each pool can register callbacks (beforeSwap, afterSwap, beforeAddLiquidity, etc.) into a hooks contract — letting protocols layer custom logic like dynamic fees, MEV-resistant ordering, or on-chain limit orders without forking Uniswap.

Singleton savings alone are large: 1000 pools deployed v2-style cost roughly 1000× as much as one singleton + per-pool metadata. The demo compares deployment cost.

Power-ups you unlock

The Sandwich Bot attacks — common mistakes

Boss battleCompare deployment gas for 1000 pools under v2 (per-pool contract) vs v4 (one singleton + per-pool metadata).

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>
const POOLS = 1000;
const V2_PER_POOL = 800000;
const V4_SINGLETON = 5000000;
const V4_PER_POOL = 30000;
const v2Total = V2_PER_POOL * POOLS;
const v4Total = V4_SINGLETON + V4_PER_POOL * POOLS;
const savings = v2Total - v4Total;
document.getElementById('o').textContent = [
  'deploying ' + POOLS + ' pools:',
  '  v2 (per-pool contract):     ' + v2Total.toLocaleString() + ' gas',
  '  v4 (singleton + metadata):  ' + v4Total.toLocaleString() + ' gas',
  '  savings:                    ' + savings.toLocaleString() + ' gas (' + Math.round(100*savings/v2Total) + '%)',
  '',
  'hook examples (registered per pool):',
  '  beforeSwap   → dynamic fees, MEV protection',
  '  afterSwap    → on-chain limit-order execution',
  '  beforeMint   → KYC gating, whitelist',
  '',
  'singleton + hooks = open protocol for custom AMM logic without forking'
].join('\n');
</script></body></html>
▶ Open the interactive comic issue
‹ Ticks · Ranges · Active LiquidityCurve · The Stableswap Invariant ›