Section 10 of 18

Build
+15 Lynx

SwapMath: One Step of the Swap

Key takeaway: computeSwapStep prices 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's amountIn, amountOut, and feeAmount. 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 formula mulDivRoundingUp(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

Solution.sol
Solidity
Loading editor...

Requirements

Write your implementation, then click Run Tests. Tests execute on the server.

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 continue

Already have an account? Log in