Section 3 of 18
SqrtPriceMath: Amounts from Price Ranges
Key takeaway:
SqrtPriceMathis the engine room of V3: given liquidityLand two sqrt prices,getAmount0DeltacomputesΔx = L * (sqrtPb - sqrtPa) / (sqrtPb * sqrtPa)andgetAmount1DeltacomputesΔy = L * (sqrtPb - sqrtPa); given an amount, thegetNextSqrtPrice*functions invert those formulas to find where the price lands. Every function takes an explicit rounding direction, and the direction is a security property: amounts the user owes the pool round up, amounts the pool pays out round down, and price movement rounds so the swap never overshoots its target. Get one direction wrong and the pool leaks a wei per call — which an attacker will happily loop.
What You Are Building
The full SqrtPriceMath library: both amount-delta functions (with explicit rounding), their signed wrappers, and the four next-price functions the swap loop will call in Part 2. Provided at the top of the starter: FullMath (512-bit mulDiv, so L * price products can't overflow), UnsafeMath.divRoundingUp, FixedPoint96, and SafeCast. Everything below the "Your code" marker is yours.
Your Code
Requirements
Sign up free — keep reading + earn 15 Lynx
Zealynx Academy is free. Track your progress, earn Lynx, and climb the leaderboard.
Sign up free to continueAlready have an account? Log in