Section 11 of 18
Pool: The Swap Loop
Key takeaway: V3's
swapis a while loop that walks price space. Each iteration finds the next initialized tick via the bitmap, clamps the step's target to whichever comes first — that tick's price or the caller'ssqrtPriceLimitX96— and letscomputeSwapStepprice the stretch. Ending a step exactly on a tick boundary triggersTick.cross: the fee-growth-outside values flip, andliquidityNet(negated when moving down) adjusts the active liquidity before the next iteration. All working state lives in memory structs; storage is written once, after the loop. Settlement is pay-after-compute: send the output, demand the input insideuniswapV3SwapCallback, verify with a balance check ('IIA'). Every trade against the most-forked DEX engine in DeFi flows through the ~100 lines you are about to write.
What You Are Building
The full swap function. Everything the module has built so far was preparation: TickBitmap finds the ticks, SwapMath prices the stretches between them, Tick.cross rebalances liquidity at the boundaries, and the fee-growth machinery records who earned what. This section composes them. It is the longest function in the protocol and the hardest section of this module. Budget the time.
Your Code
Requirements
Sign up free — keep reading + earn 25 Lynx
Zealynx Academy is free. Track your progress, earn Lynx, and climb the leaderboard.
Sign up free to continueAlready have an account? Log in