Section 5 of 18
TickBitmap: Finding the Next Tick
Key takeaway: The swap loop needs "next initialized tick from here, in this direction" to be cheap, so V3 packs tick initialization state into a bitmap: one bit per usable tick (
compressed = tick / tickSpacing, floored toward negative infinity for negative ticks), 256 bits per storage word, keyed bywordPos = compressed >> 8withbitPos = compressed % 256.flipTicktoggles a bit with XOR whenever a tick'sliquidityGrosscrosses zero, andnextInitializedTickWithinOneWordfinds the nearest set bit in one word with a single storage read: build a mask of bits at-or-below (searching down) or strictly-above (searching up) the current position, AND it with the word, then jump straight to the most/least significant set bit.
What You Are Building
The TickBitmap library: position, flipTick, and nextInitializedTickWithinOneWord. BitMath (branchless-ish MSB/LSB scans) is provided. This is the data structure that makes V3 swaps affordable: without it, every swap step would scan tick space one tick at a time; 60,000 ticks of empty space between two positions would cost 60,000 storage reads. With it, the swap loop covers 256 usable ticks per storage read.
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