Section 10 of 18
SwapMath: One Step of the Swap
Key takeaway:
computeSwapStepprices a swap over a single stretch of constant liquidity: given the current price, a target price that must not be exceeded, the liquidity, the remaining amount (positive = exact input, negative = exact output), and the fee, it returns the new price and the step'samountIn,amountOut, andfeeAmount. Direction is inferred from the price pair alone (zeroForOne = current >= target), the fee is stripped off the input before the price math, and every rounding decision — input up, output down, fee up — pushes the error toward the pool. The asymmetric fee formulamulDivRoundingUp(amountIn, feePips, 1e6 - feePips)grosses the fee back up from the net input; getting that denominator wrong is a classic fork bug.
What You Are Building
The pure function at the center of the swap loop. Section 11's while loop does nothing but call computeSwapStep repeatedly — once per stretch of constant liquidity — and book the results. All the economics of a single step live here, composed entirely from the SqrtPriceMath functions you built in section 3.
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