The Order Book Data Structure
How Perpl achieves O(1) insert and cancel on a fully on-chain CLOB — while every sorted-tree alternative scales in cost with the size of the book.
Building a central limit order book entirely on-chain is the hardest engineering problem in DeFi. Every comparison, traversal, and structural update costs gas. Most perpetual DEXes responded by moving order matching off-chain entirely, sacrificing the transparency that makes a DEX meaningful. The ones that stayed on-chain paid in user-facing gas costs that make market-making economically punishing.
Perpl's CLOB achieves a complete post-and-cancel cycle at 100k gas — cheaper than a Uniswap V2 AMM swap at 200k gas. This is possible because of a purpose-built data structure that replaces sorted-tree traversal with direct bitmap lookup. Insert and cancel are O(1) constant time, always, regardless of how deep the book is.
The Industry Default: Sorted Trees
An order book must efficiently answer two questions: what is the best available price? and what orders exist at that price? The textbook answer for maintaining sorted access with fast insertion and deletion is a balanced binary search tree — a red-black tree or B-tree.
These structures work well in memory. Each internal node stores a price level. Insertion places the new price in its sorted position. The tree self-balances via rotations and recoloring to maintain logarithmic height. Finding the best bid or ask is simply reaching the minimum or maximum leaf.
On the EVM, this design is a gas disaster. Balanced tree operations require reading and writing multiple storage slots per operation, and the number grows with the size of the book:
rebalancing = O(log N) — rotations and recolors propagate up toward root
total SSTOREs = O(log N) — each structural change writes a storage slot N = number of active price levels. At N = 10,000: ~13 storage operations minimum per insert.
Rebalancing is the core problem. After inserting a new node, the tree's red-black invariants may be violated and must be restored by rotating subtrees and recoloring nodes — potentially propagating all the way to the root. Each rotation writes two nodes. Each recolor writes one. A delete triggers "double-black" fixup, which can be even more expensive.
Perpl's Bit-Index Tree: O(1) by Design
Perpl's key observation: prices are integers in a bounded range. They don't need to be maintained in a sorted tree — they can be indexed in a bitmap. If a price level has orders, its bit is set to 1. If empty, it's 0. Finding the best available price is finding the lowest or highest set bit — a single bitwise scan of a 256-bit word.
The bit-index tree scales this bitmap idea across three levels of hierarchy. Each level is a single 256-bit storage slot. A bit set at a higher level signals that at least one price in that sub-range is occupied. This structure covers over 16 million distinct price levels using exactly three slot reads to locate any price — and exactly three slot writes (at most) to insert or delete any order.
insert = set bit in leaf → propagate up if level was zero → O(1)
cancel = clear bit in leaf → propagate up if level is now zero → O(1) Each level is one 256-bit word. The maximum structural change is three bit-flips. Always.
Complexity at a Glance
The Gas Reality
Abstract complexity becomes concrete gas cost on the EVM. Every storage write (SSTORE) costs gas — 20,000 gas for a cold slot (first write in a transaction), and 2,900 gas for a warm slot (already accessed). A sorted tree with 10,000 price levels requires at minimum 13 traversal reads and several rebalancing writes on each insert — and this cost grows as more orders accumulate.
Perpl's post-and-cancel cycle runs at 100k gas total, including full solvency checks, order storage, and all other computation. Uniswap V2 — the baseline for "a lightweight DeFi swap" — costs 200k gas. Perpl's CLOB insert+cancel is cheaper than an AMM swap.
The gap compounds with frequency. A market maker running 200 requotes per hour faces 200 post+cancel cycles. On Perpl that's 20M gas per hour — a predictable, constant budget. On a sorted tree CLOB at N=10,000, the same 200 cycles consume 60M+ gas per hour, and the cost continues climbing as the book deepens. At scale, this difference determines whether tight-spread market making is economically viable.
Why This Defines Market Maker Quality
Market makers provide the liquidity that makes a CLOB useful. Their value is the spread: the gap between the best bid and best ask. Narrow spreads mean tighter prices for takers. But spreads are not set arbitrarily — they are bounded below by the cost of maintaining them.
A market maker's core loop is: post a quote → price moves → cancel → post new quote. The gas cost of that loop sets the minimum economically viable spread. Every requote must at minimum cover its gas cost through expected fee income. Higher gas per requote = wider minimum spread = worse prices for everyone.
The Change order compounds this further. Because Perpl's order storage slots are not tied to any specific price level, a market maker can move an order to a new price in a single transaction rather than canceling and reposting. The Change operation shifts the order's slot from one price partition to another — no deallocation, no reallocation. This eliminates half the storage cost of a requote entirely.
The Full Order Book Architecture
The bit-index tree handles price discovery. Orders at each price level are stored in a partition map list — a doubly-linked FIFO queue per price level, built on Solidity mappings. Orders at the same price execute in the order they were posted (price-time priority). The combined structure is two bit-index trees and one partition map list:
The result is a CLOB that supports over 16 million price levels, up to 65,535 simultaneous open orders per contract, and price-time priority matching — all fully on-chain, fully transparent, and at gas costs that make market making economically viable for the first time on an EVM chain.