# From Econia's AVL Queue to a Framework-Level Trading Engine # Decibel Evolution — Interactive Research Presentation # URL: https://decibel-presentation.vercel.app # Last updated: 2026-03-31 > How one of three crankless on-chain CLOBs ever built became a framework primitive on Aptos. > 7 chapters covering AVL queues, BigOrderedMap, async matching, and security research. --- ## Introduction From Econia's AVL queue to a framework-level trading engine. How one of three crankless on-chain CLOBs ever built became a framework primitive — the secret sauce behind Econia, why it hit its limits, and how AIP-120 solved them. Sections: 01 Econia's AVL Queue · 02 Decibel Spotlight · 03 Matching Engine · 04 Code Evolution · 05 New Primitives · 06 Gas Economics · 07 Security --- ## Section 01 — Data Structure: Econia's AVL Queue ### Phase 1: Why on-chain order books are hard **Diagram — THE PROBLEM** ``` THE PROBLEM: an on-chain order book needs two things at once ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. SORTED ACCESS ── find the best bid/ask instantly 2. TIME PRIORITY ── at the same price, first order gets filled first Standard BSTs can't handle duplicate prices efficiently. Regular queues can't give fast price-range lookups. Hash maps? Fast lookup, but no ordering. Red-black trees? 2x the height of AVL = more gas on Aptos. Econia's answer: a HYBRID ── AVL tree + doubly linked list One structure that solves BOTH problems. ``` **Body text:** Building a fully on-chain order book is one of the hardest problems in crypto. You need sorted access to find the best price instantly, and you need FIFO ordering so that at any given price level, the first order placed is the first one filled. Hash maps give you O(1) lookup but no ordering. Sorted arrays give you ordering but O(n) inserts. Red-black trees work but have 2x the height of AVL trees, meaning more storage reads and higher gas on Aptos. Econia invented a new hybrid data structure called the AVL queue to solve both problems in a single structure. It became one of only three exchanges to ever achieve fully atomic, crankless on-chain matching, alongside Phoenix and Manifest on Solana. --- ### Phase 2: How Econia solved it: the AVL Queue **Diagram — THE AVL QUEUE** ``` THE AVL QUEUE ── AVL tree for prices, linked list for time priority ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ BID SIDE (descending price order): 100 (best bid) ╱ ╲ 98 102 ╱ ╲ ╱ ╲ 95 99 101 103 Each price node holds a doubly-linked FIFO queue: Price 100 → [Order A (earliest) ↔ Order B ↔ Order C (newest)] Price 98 → [Order D ↔ Order E] Price 95 → [Order F] HOW MATCHING WORKS: 1. Best price = root of AVL tree ────────────── O(1) 2. Best order = head of linked list at that price ── O(1) 3. Match & dequeue from list head ───────────── O(1) 4. If list empties → remove node, rebalance ─── O(log n) ALL IN ONE TRANSACTION. No crank. No second step. Atomic. ⚡ One of only 3 crankless on-chain CLOBs ever (+ Phoenix, Manifest) ``` **Body text:** The AVL queue is a self-balancing binary tree where each node represents a price level, and each price node contains a doubly linked list of orders in time-priority order. Finding the best price means reading the tree root, which is O(1). Finding the best order at that price means reading the list head, also O(1). Matching and removing that order is O(1) because you just dequeue from the list. Only when a list empties do you need to remove the tree node and rebalance, which is O(log n). Every tree node is bit-packed into a single u128 value, using all 128 bits with zero waste. On Aptos, 15 function calls cost the same gas as a single storage read, so Econia hand-inlined every bit operation. No function calls, no abstraction layers, just raw bit shifts. Dead nodes get recycled through an inactive stack instead of being deallocated, saving the expensive per-item creation cost. The result: 11,295 bytes of hand-rolled Move code across 9,064 lines in avl_queue.move. All matching happens in a single transaction with no crank and no second step. --- ### Phase 3: Where Econia hit its limits **Body text:** Econia hit hard limits. The 14-bit node IDs cap capacity at 16,383 orders per side, and when the AVL tree reaches its critical height of 18, it involuntarily evicts the lowest-priority resting order without the owner's consent. The protocol only supports spot trading with no perpetuals, no margin, and no leverage. Within a single market, all makers on the same side contend for the same AVL queue, so Block-STM parallelism only helps across different markets, not within one. Gas scales linearly with the number of fills, so a large taker order walking a deep book risks hitting the transaction gas ceiling. When Aptos needed a perpetuals engine with margin checks, funding rates, liquidation cascades, and auto-deleveraging, Econia's atomic single-transaction model could not handle the computational complexity. Key limits: - CAPACITY: 16,383 orders per side (14-bit node IDs, max 2^14 - 1 = 16,383 per type, tree height 18 → involuntary EVICTION) - SPOT ONLY: no perps, no margin, no leverage, no native funding rates, liquidation, or auto-deleveraging - INTRA-MARKET CONTENTION: single AVL queue per side, all BTC/USD bid makers contend for the same data structure - GAS: linear in fill count, no work budgets — deep taker order → O(n) state mutations → gas limit risk - ATOMIC = GAS BOMB: match + settle + fees all in one TX Stats: Econia (Aptos): 16,383 orders, $500M volume, ARCHIVED. Phoenix (Solana): unlimited, $75B+ volume, ACTIVE. --- ### Phase 4: How AIP-120 replaced it with BigOrderedMap **Diagram — AIP-120: BigOrderedMap** ``` AIP-120: BigOrderedMap 0 bytes custom code ────────────────────────────────────────────────────────────────────────────── // Aptos Framework stdlib B+ tree BigOrderedMap // asks: lowest first BigOrderedMap // bids: highest first +-----------------------------+ | root: inner (degree = 64) | +------+---------------+------+ | | +------------+--+ +------+-------------+ | leaf: 10->ask | | leaf: 52->bid | | 22->bid | | 60->ask 95->bid | | 35->ask | | 103->ask 118->bid | | (degree = 32) | | (degree = 32) | +---------------+ +---------------------+ ✓ UNLIMITED capacity -- B+ tree grows dynamically, no eviction ✓ Block-STM parallel: different leaves = no conflict ✓ Framework-maintained: auto-optimized on every Aptos upgrade ✓ reuse_slots + allocate_spare → predictable gas ────────────────────────────────────────────────────────────────────────────── Econia: 30,858B (market + avl_queue) AIP-120: 13,144B (order_book + single + price_time) -57% ``` **Body text:** AIP-120 replaced the AVL queue with BigOrderedMap, a B+ tree from the Aptos standard library. It requires zero custom code because the framework team at Aptos Labs maintains and optimizes it. Capacity is unlimited because B+ tree leaf nodes automatically split and merge as they grow. There is no eviction. Under Block-STM, orders at different price levels land in different leaf storage slots and execute in parallel without conflicts. The orderbook configuration uses inner_degree=64 and leaf_degree=32 with rebalance_on_insert enabled, and supports reuse_slots plus allocate_spare_slots for predictable gas costs. Econia's core orderbook was 30,858 bytes across two modules. AIP-120's equivalent is 13,144 bytes across three modules, a 57% reduction in bytecode size, while adding bulk orders, TWAP, dead man's switch, and pre-cancellation that Econia never had. --- ## Section 02 — Decibel Spotlight ### Phase 1: Everything Econia did right, but better **Diagram — DECIBEL = AIP-120 ORDERBOOK + PERPETUALS ENGINE** ``` DECIBEL = AIP-120 ORDERBOOK + PERPETUALS ENGINE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ The AIP-120 orderbook is a framework primitive ── part of Aptos itself. Decibel is the FIRST and ONLY exchange built on it. WHAT DECIBEL INHERITED FROM ECONIA'S VISION: ✓ Fully on-chain order matching ── no off-chain components ✓ Price-time priority CLOB ── same fairness guarantees ✓ Block-STM parallelism ── different markets run in parallel ✓ Sub-second finality ── trades settle in under 1 second WHAT DECIBEL ADDED: ✓ Perpetual futures ── margin, leverage, funding rates ✓ Unlimited order capacity ── BigOrderedMap vs 16K cap ✓ Bulk orders, TWAP, dead man's switch, pre-cancellation ✓ 9-callback clearinghouse ── generic book, pluggable settlement ✓ Async matching ── handles perp complexity without gas bombs ✓ $39.5M TVL ── real money, real trading, real volume ``` **Body text:** Decibel is not just a replacement for Econia. It is the realization of everything Econia proved was possible, built directly into the Aptos framework by the same team that built the chain. The AIP-120 orderbook lives inside aptos-core itself, authored primarily by Sital Kedia, Aptos Founding Engineer and former Meta/Facebook tech lead. It gets optimized at the VM level and benefits from every Aptos framework upgrade automatically. Decibel is the first and only exchange built on this primitive, running 78 compiled modules across 362,728 bytes of deployed bytecode. It processes 6.1 million transactions per day, holds $39.5M in vault TVL, supports 15 perpetual markets with up to 40x leverage, and has generated over $986 million in cumulative trading volume since launching on February 25, 2026. --- ### Phase 2: The Aptos advantage — why no other chain could do this **Diagram — THE APTOS ADVANTAGE** ``` THE APTOS ADVANTAGE ── why this couldn't be built anywhere else ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ BLOCK-STM ── optimistic parallel execution Different markets execute concurrently. BTC/USD and ETH/USD never block each other. Decibel runs 6.1M tx/day because of this. MOVE LANGUAGE ── resource safety + linear types Assets can't be duplicated or lost. The compiler enforces it. No reentrancy attacks. No double-spend bugs. By construction. FRAMEWORK-LEVEL ORDERBOOK (AIP-120) The CLOB isn't a smart contract ── it's part of the chain itself. Optimized at the VM level. Gets faster with every Aptos upgrade. Sital Kedia (Aptos Founding Engineer) built it personally. ``` **Body text:** Aptos gives Decibel capabilities that no other blockchain can offer. Block-STM is an optimistic parallel execution engine that lets different markets run concurrently. A trade on BTC/USD never blocks a trade on ETH/USD because they touch different storage slots. This is why Decibel can handle 6.1 million transactions per day on a general-purpose L1. The Move language enforces resource safety through linear types at compile time, meaning assets cannot be duplicated, lost, or double-spent. Reentrancy attacks are impossible by construction because Move does not allow recursive calls into mutable references. The framework-level orderbook means the matching engine is not a smart contract running on top of the VM. It is part of the VM itself, compiled and optimized alongside the core execution layer. The Aptos gas schedule directly accounts for orderbook operations, and future native code optimizations can make matching even cheaper without changing a single line of Decibel's application code. --- ### Phase 3: What's coming — the roadmap that makes Decibel unstoppable **Diagram — WHAT'S COMING** ``` WHAT'S COMING ── the Aptos roadmap makes Decibel even more powerful ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ BLOCK-STM v2 ── next-gen parallel execution Even more parallelism for orderbook operations ZAPTOS ── sub-100ms latency Pipelining consensus for near-instant finality CONFIDENTIAL ASSETS (AIP-143) Encrypted balances on-chain. Trade without revealing your size. Twisted ElGamal + Bulletproofs ── zero-knowledge transfers. ARCHON ── fair ordering protocol MEV protection at the consensus layer Could eliminate the sandwich attack surface we documented ENCRYPTED MEMPOOLS Orders invisible until execution ── no front-running ORDERLESS TRANSACTIONS Gas abstraction ── users don't need APT to trade Decibel is positioned to absorb ALL of these upgrades because AIP-120 is a framework primitive, not a standalone contract. ``` **Body text:** The Aptos roadmap will make Decibel significantly more powerful over the coming months. Block-STM v2 introduces deeper parallelism that benefits high-contention orderbook operations. Zaptos is a pipelining approach to consensus that targets sub-100ms transaction latency, bringing Aptos closer to centralized exchange speeds. Confidential Assets, defined in AIP-143, enable encrypted on-chain balances using Twisted ElGamal encryption and Bulletproof range proofs, allowing traders to execute transfers without revealing their position sizes to other participants. Archon is a fair ordering protocol being developed for the Aptos consensus layer that could provide MEV protection by enforcing ordering fairness at the validator level, potentially eliminating the sandwich attack surface that our security research documented. Encrypted mempools would make pending orders invisible to other participants until they are included in a block, removing front-running entirely. Orderless transactions provide gas abstraction so users do not need to hold APT to trade. Because AIP-120 is a framework primitive and not a standalone contract, Decibel will absorb every single one of these upgrades automatically with zero contract migration. --- ## Section 03 — Matching Engine ### Phase 1: Econia — atomic matching in one transaction **Diagram — HOW ECONIA MATCHES** ``` HOW ECONIA MATCHES: everything in ONE transaction ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ You submit an order. In that SAME transaction: 1. FIND BEST PRICE ──── walk the AVL tree to the best bid/ask 2. FILL THE ORDER ───── transfer coins directly: your quote for their base 3. CHECK SELF-TRADE ─── if you're matching against yourself: cancel one side 4. CHARGE FEES ──────── split between protocol, integrator (7 tiers), maker 5. UPDATE THE BOOK ──── post unfilled remainder as a resting limit order 6. EMIT EVENTS ──────── on-chain proof of every fill When you call swap_coins, coins go in, coins come out. That's it. No waiting. No second step. No crank. This is what made Econia special: ATOMIC COMPOSABILITY. Any smart contract could call swap_coins and get instant settlement. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚡ One of only 3 exchanges that ever achieved this (with Phoenix on Solana) ✓ Atomic: submit → match → settle → done ✓ No MEV from delayed matching ✓ swap_coins composable: coins in, coins out ✗ Deep book walk → gas O(n) with fill count ✗ Can't handle perp complexity in one TX ✗ Liquidation cascade = transaction abort ``` **Chart — Atomic Gas Profile** ``` match() loop ╢██████████████████████████████████████████████████ coin xfer ╢███████████████████████ fees ╢████████████ events ╢█████████ book update ╢██████████████ self-match ╢██████ ╚══════════════════════════════════════════════════ ``` **Body text:** Econia's matching was fully atomic and crankless. When you submitted an order, the matching function looped through the AVL queue head, filled at each price level, transferred coins between maker and taker in-place, assessed fees, posted any unfilled remainder to the book, and returned. All in one transaction. The swap_coins function was beautifully composable: pass in base coins, get back quote coins, atomically settled. No external process needed to finalize anything. This was Econia's greatest achievement and what made it comparable to Phoenix on Solana. There was no MEV from delayed matching because there was nothing to delay. The trade was done the moment you submitted it. --- ### Phase 2: Decibel — async queue with permissionless crank **Diagram — AIP-120: ASYNC QUEUE + PERMISSIONLESS CRANK** ``` AIP-120: ASYNC QUEUE + PERMISSIONLESS CRANK ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ PENDING QUEUE BigOrderedMap key: (time: u64, priority: u8, tie_breaker: u128) P0 BackstopLiquidation 0xaf3d.. BTC/USD ← liquidation (urgent) P0 MarginCall 0x3b91.. ETH/USD ← margin call P0 CheckADL 0x____.. BTC/USD ← auto-deleverage check P2 TakerOrder 0xc1e7.. BTC/USD ← taker sell 0.5 BTC P2 TakerOrder 0xd7a2.. SOL/USD ← taker buy 100 SOL P2 TwapSlice 0x92f0.. APT/USD ← TWAP T3/6 executing P2 ContinuedOrder 0x55b8.. ETH/USD ← partial fill cont. ▼ process_perp_market_pending_requests(market, work_units) → PERMISSIONLESS: anyone can call this function → Pops front, processes up to the configured match limit per call → Multiple calls drain full queue ── no single-TX gas bomb → tie_breaker = monotonically_increasing_counter() ``` **Chart — Queue Priority** ``` P0 Liquidation ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ P0 MarginCall ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ P0 CheckADL ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ P2 TakerOrder ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ P2 TwapSlice ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ P2 Continued ╢▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ╚══════════════════════════════════════════════════ ``` **Body text:** Decibel introduced a crank on purpose. Perpetual futures require margin validation, funding rate computation, liquidation cascades, position updates, and auto-deleveraging checks. All of that is too computationally expensive to fit in a single atomic transaction without hitting the gas ceiling. So AIP-120 decouples order placement from matching using an async pending queue. When you place a taker order, it enters a BigOrderedMap keyed by time, priority, and a monotonic tiebreaker counter. Liquidations receive priority 0, which means they always process before regular trades. Taker orders receive priority 2. A permissionless crank function pops entries from the front of the queue and processes them up to the configured match limit per call. Multiple crank calls can drain the full queue. This was the necessary tradeoff to support perpetuals on a fully on-chain CLOB. --- ### Phase 3: How the 9-callback settlement works **Diagram — settle_trade() — 1 of 9 clearinghouse callbacks** ``` settle_trade() ── 1 of 9 clearinghouse callbacks ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✓ validate taker margin ─────────────── sufficient collateral? ✓ validate maker margin ─────────────── still solvent after fill? ✓ execute at MAKER price ────────────── taker gets improvement ✓ commit positions ──────────────────── update both accounts ✓ distribute fees + TP/SL ───────────── trading + builder + referral Fills: 5/5 → STOP_MATCHING (margin exhausted) Self-trade → cancels MAKER (not taker) Orders execute at MAKER's price ⚠ Anyone calls crank → controls timing ⚠ This enables sandwich attacks ``` **Chart — Clearinghouse Callbacks** ``` settle_trade ╢██████████████████████████████████████████████████ validate_ord ╢█████████████████████████ validate_blk ╢█████████████████████████ place_maker ╢████████████████████ cleanup ╢██████████████ decrease_sz ╢█████████ place_bulk ╢█████████████████ cleanup_blk ╢█████████ get_metadata ╢█████ ╚══════════════════════════════════════════════════ ``` **Body text:** The crank invokes nine callback functions registered by Decibel's clearinghouse module. These nine callbacks handle settlement, order validation, bulk validation, maker placement, order cleanup, bulk cleanup, bulk placement, size reduction, and metadata serialization. If the clearinghouse signals to stop matching because a trader's margin is exhausted or a position is invalid, the matching loop halts immediately. Orders always execute at the maker's resting price, which means takers receive price improvement compared to their limit. Self-trade prevention cancels the maker side, not the taker. The critical security tradeoff is that the crank function is permissionless, meaning anyone can call it and control exactly when matching occurs. This is the foundation of the sandwich attack we documented in our security research, where an attacker triggers vault closing orders at predictable prices. --- ## Section 04 — Code Evolution ### Phase 1: Testnet — two separate contracts with callbacks **Diagram — TESTNET: TWO SEPARATE CONTRACTS** ``` TESTNET: TWO SEPARATE CONTRACTS ────────────────────────────────────────────────────────────────────────────── 0x1b3f.. (AIP-120 ORDERBOOK) 0x9f83.. (DECIBEL PERPS) ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ ◆ order_book ◆ perp_engine ◆ order_placement ◆ clearinghouse_perp ◆ market_types <-8-> ◆ vault ◆ single_order_book cbs ◆ liquidation ◆ price_time_index ◆ accounts_collateral ◆ dead_mans_switch ◆ oracle 27 modules · 116KB 51 modules · 159KB ────────────────────────────────────────────────────────────────────────────── 18 modules contain hard-coded refs to 0x1b3f.. cross-contract call on EVERY order: settle · validate · place · cleanup ``` **Body text:** On testnet, Decibel imported the AIP-120 orderbook as an external dependency deployed at a separate contract address (0x1b3fa27b). Eighteen of Decibel's modules contained hard-coded bytecode references to this external address. The orderbook handled all matching logic and invoked Decibel's code through eight callback functions: settlement, validation, maker placement, cleanup, and four more. This was a clean architectural separation, but it meant cross-contract calls happened on every single order placement, adding latency and gas overhead. --- ### Phase 2: January 2026 — the orderbook gets absorbed **Diagram — ABSORPTION: Jan 21, 2026** ``` ABSORPTION: Jan 21, 2026 ────────────────────────────────────────────────────────────────────────────── 0xd0b2.. (UNIFIED) 57 modules · ZERO external references INLINED INTO EXISTING MODULES: ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ async_matching_engine .......... +4,045 bytes perp_engine .................... +2,710 bytes perp_positions ................. +4,340 bytes clearinghouse_perp ............. +3,122 bytes order_placement ................ +2,887 bytes ✓ No more cross-contract calls ✓ Full upgrade control over matching logic ✓ Callback architecture preserved internally ``` **Body text:** In January 2026, Decibel absorbed the orderbook into its own contract. The testnet v2 deployment at address 0xd0b2dd contained 57 modules with zero external bytecode references. The orderbook code was inlined directly into existing Decibel modules. The async matching engine module grew by 4,045 bytes, the perp engine grew by 2,710 bytes, and the positions module grew by 4,340 bytes. This eliminated all cross-contract call overhead and gave the Decibel team full upgrade control over the matching logic without depending on a separate deployment. --- ### Phase 3: 77 modules re-modularized under one address **Diagram — RE-MODULARIZED: 77 modules** ``` RE-MODULARIZED: 77 modules ────────────────────────────────────────────────────────────────────────────── ██ order_book ✓ ██ perp_engine ✓ ██ vault ✓ ██ liquidation ✓ ██ oracle ✓ ██ accounts ✓ ██ async_match ✓ ██ fees ✓ ────────────────────────────────────────────────────────────────────────────── 9 callback hooks connect orderbook → perps clearinghouse ``` **Body text:** By February's testnet v3, the orderbook was re-modularized. The 77-module deployment included 12 named orderbook modules published under Decibel's own package address, including the core order book, single order book, price-time index, bulk order book, and pending order book index. This restored clean internal boundaries while keeping everything in a single deployment unit. The nine-callback architecture survived this restructuring, connecting the generic orderbook framework to Decibel's perpetuals clearinghouse through the same function-pointer pattern. --- ### Phase 4: Mainnet launch — 78 modules, 362KB, fully self-contained **Diagram — MAINNET LIVE** ``` MAINNET LIVE: 0x50ead22a..dfdb06 ══════════════════════════════════════════════════════════════════════════════ ◆ 78 modules ◆ 362,728 bytes ◆ 162 entry functions ◆ 15 markets ◆ $39.5M TVL ◆ upgrade #11 ◆ 6.1M tx/day ◆ 45.2% of all Aptos gas ────────────────────────────────────────────────────────────────────────────── orderbook: byte-for-byte stable across 11 upgrades perp layer: rapidly evolving (v11 = isolated margin) source: aptos-labs/etna (PRIVATE repository) ══════════════════════════════════════════════════════════════════════════════ ``` **Body text:** Mainnet launched on February 25, 2026 with 78 modules totaling 362,728 bytes of deployed bytecode. The contract is fully self-contained with zero references to any external address. The application code lives in a private repository at aptos-labs/etna, maintained by Aptos Labs engineers. The public orderbook framework lives in aptos-core under the Innovation-Enabling Source Code License. After eleven on-chain upgrades, the core orderbook modules remain byte-for-byte identical to the initial deployment, while the perpetuals layer has evolved rapidly, adding isolated margin, withdrawal rate limiting, and batch oracle updates in version 11 alone. --- ## Section 05 — New Primitives ### Phase 1: Bulk orders — atomic two-sided quotes **Diagram — BULK ORDERS** ``` BULK ORDERS -- atomic two-sided quote ────────────────────────────────────────────────────────────────────────────── BTC/USD Order Book Depth BID 11 8 6 3 SPR 3 6 8 11 ASK ────────────────────────────────────────────────────────────────────────────── Econia: 9 TXs x 22 gas = 198 gas · 9 round trips AIP-120: 1 TX x 26 gas = 26 gas · 1 round trip ``` **Body text:** Bulk orders let market makers post bids and asks at multiple price levels in a single atomic operation. Four vectors define the entire two-sided quote: bid prices, bid sizes, ask prices, and ask sizes. On Econia, a market maker quoting seven price levels needed to submit seven separate transactions, each costing 22 gas and requiring its own round trip. On AIP-120, the entire quote is processed as one unit. Validation, placement, and margin checks happen once, not per-level. A single bulk order costs 26 gas total. This is why Decibel's market makers submit 1.5 million bulk order transactions per day, accounting for 27.5% of all Decibel activity and making it the single most-called function on the protocol. --- ### Phase 2: TWAP — time-weighted execution built into the engine **Diagram — TWAP** ``` TWAP -- time-sliced execution ────────────────────────────────────────────────────────────────────────────── Order: 3.0 BTC Start: 14:00 Freq: 5min End: 14:30 T1 14:00 T2 14:05 T3 14:10 T4 14:15 T5 14:20 T6 14:25 ────────────────────────────────────────────────────────────────────────────── Native to async matching engine -- not a wrapper contract ``` **Body text:** TWAP orders split a large order into time-sliced sub-orders to minimize market impact. You specify a start time, frequency in seconds, and end time. The async matching engine automatically schedules each slice as a pending request at the specified interval. Each slice enters the queue as a regular taker order and matches at the best available price at execution time. This is native to the matching engine itself, not a wrapper contract or external scheduler. If a slice rounds to zero size due to integer math, the TWAP skips that slice and continues with the next one. The entire TWAP lifecycle, including scheduling, execution, and partial fill continuation, runs through the same async queue as regular orders. --- ### Phase 3: Dead man's switch — enforcing market maker liveness **Diagram — DEAD MAN'S SWITCH** ``` DEAD MAN'S SWITCH -- MM liveness ────────────────────────────────────────────────────────────────────────────── keep_alive(market_id: 0, timeout: 30s) Status: ✕ EXPIRED -- ALL ORDERS INVALIDATED HEARTBEAT MONITOR: [flatline pattern — all orders invalidated] ✕ Timeout resets on each keep_alive() call ✕ cleanup_expired_orders() → PERMISSIONLESS ✕ Anyone can batch-cancel 100 orders at once ⚠ Griefing: brief keep_alive lapse → entire book wiped ``` **Body text:** The dead man's switch enforces market maker liveness to prevent ghost liquidity from crashed or abandoned bots. Traders call the keep-alive function with a configurable timeout to maintain an active session. If the timeout expires without renewal, every order placed during that session is automatically invalidated. The cleanup function is permissionless, meaning anyone can call the cleanup function to cancel up to 100 stale orders for any account. This creates a deliberate griefing surface: if a market maker's keep-alive lapses for even a brief moment, any external party can batch-cancel their entire resting book. The minimum keep-alive duration is configurable per market by the protocol admin. --- ### Phase 4: Pre-cancellation — winning the 500ms race **Diagram — PRE-CANCELLATION** ``` PRE-CANCELLATION -- cancel before order arrives ────────────────────────────────────────────────────────────────────────────── TIMELINE: t=0ms MM sends CANCEL(client_id: "abc-123") --> arrives instantly, stored in tracker t=500ms ORDER(client_id: "abc-123") arrives --> book checks pre-cancellation tracker --> client_id "abc-123" FOUND --> REJECTED ✗ -- never touches the book ✓ Eliminates 500ms cancel race condition ✓ Separate Table storage → no Block-STM conflicts ✓ Econia had NONE of these four features ``` **Body text:** Pre-cancellation lets you cancel an order before it even arrives on-chain. You submit a cancel request keyed by a client order ID. When the order transaction eventually lands and the book tries to place it, it checks the pre-cancellation tracker first and rejects the order immediately if a matching ID is found. This eliminates the roughly 500-millisecond race condition between when a market maker sees their order confirmed and when they can submit a cancel. The pre-cancellation tracker is stored in a separate Table from the order book specifically to avoid storage slot conflicts under Block-STM, ensuring that pre-cancel and order-place transactions can execute in parallel without contention. --- ## Section 06 — Gas Economics ### Phase 1: Decibel burns 45.2% of all Aptos gas **Chart — Aptos Mainnet Gas: Who Burns It** ``` Decibel ╢███████████████████████████████████████████████████████ 12 ╢███████████████ 8 ╢██████████ 6 ╢████████ 5 ╢███████ 4 ╢█████ 3 ╢████ 3 ╢████ 2 ╢███ Other ╢███████████████ ╚═══════════════════════════════════════════════════════ 45.2% -- single largest consumer on ALL of Aptos ``` **Body text:** Decibel consumes 45.2% of all Aptos mainnet gas, making it the single largest gas consumer on the entire network. That translates to 333 million gas units per day across 6.1 million transactions, costing 333 APT or approximately $3,370 at current prices. Oracle price updates from Chainlink and the internal oracle fire roughly once per second for each of the 15 supported markets. These oracle transactions alone account for 74.4% of Decibel's total gas consumption, which means oracle updates represent approximately one-third of all gas burned on the entire Aptos blockchain. --- ### Phase 2: Where the 6.1 million daily transactions go **Chart — Decibel Gas Breakdown** ``` Oracle 74.4% ╢███████████████████████████████████████████████████████ ║███████████████████████████████████████████████████████ ║ Trading 22.3% ╢█████████████████ ║█████████████████ ║ Cranks 3.1% ╢███ ║███ ║ Vault 0.2% ╢█ ║█ ╚═══════════════════════════════════════════════════════ 6.1M transactions/day · 333M gas units · 333 APT ($3,370) ``` **Body text:** The per-transaction efficiency is remarkable despite the volume. A bulk order placement costs only 26 gas units. A single limit order costs between 22 and 116 gas depending on whether it includes take-profit or stop-loss attachments. Processing the matching engine crank costs 14 gas. Processing a collateral withdrawal costs just 7 gas, the cheapest recurring operation on the protocol. The bottleneck is not per-operation cost but raw volume. The protocol generates 3.4 million oracle transactions per day, 2 million trading transactions including bulk orders and single orders, and 700,000 crank calls to process the matching queue. The top five wallet addresses account for 89.1% of all transactions, representing the oracle bot, cranker, and three market maker bots. --- ### Phase 3: AIP-141 — what happens when gas costs 10x more **Chart — AIP-141 Impact** ``` Current /day ╢█████ ║█████ ║█████ ║█████ ║ AIP-141 /day ╢██████████████████████████████████████████████████ ║██████████████████████████████████████████████████ ║██████████████████████████████████████████████████ ║██████████████████████████████████████████████████ ╚══════════════════════════════════════════════════ ⚠ Oracle updates alone: $9.15M/year after AIP-141 → MUST batch across markets or move to native code ``` **Body text:** AIP-141 is a governance proposal to increase the gas unit price from 100 to 1,000 octas, a tenfold increase. For Decibel, this means daily operating costs jump from $3,370 to $33,700. Annual cost rises to $12.3 million. Oracle updates alone would cost $9.15 million per year. This creates enormous economic pressure to fundamentally rethink oracle infrastructure. The most likely responses are batching oracle updates across all 15 markets into fewer transactions, reducing update frequency from once per second to once per few seconds, or moving oracle price computation to native Aptos framework code that bypasses the gas metering system entirely. The AIP-120 architecture was designed with exactly this kind of optimization path in mind. --- ## Section 07 — Security Research ### Phase 1: OtterSec — 91 findings across 4 audits **Chart — OtterSec Audits** ``` Orderbook ╢■■■■■■■■■■■■■■■■■■■■■■ ║■■■■■■■■■■■■■■■■■■■■■■ ║ Perps ╢■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ║■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ║ Liq+Vaults ╢■■■■■■■■■■■■■■■■■■■ ║■■■■■■■■■■■■■■■■■■■ ║ Predeposit ╢■■■■■■■■ ║■■■■■■■■ ╚══════════════════════════════════════════════════ 0 CRITICAL · 3 HIGH · 27 MEDIUM · ALL RESOLVED Source: aptos-core (public) + aptos-labs/etna (private) ``` **Body text:** OtterSec, one of the leading blockchain security firms, audited four separate components between October 2025 and February 2026. The AIP-120 orderbook received 20 findings. The perpetuals exchange received 47 findings. The liquidation and vaults module received 17 findings. The predeposit system received 7 findings. Grand total: 91 findings across more than 75 pages of audit reports. Zero were rated critical severity. Three were rated high. Twenty-seven were rated medium. All 91 findings were marked as resolved. The audited code lives in two repositories: the public aptos-labs/aptos-core for the orderbook framework, and the private aptos-labs/etna for the exchange application layer. The same two lead auditors, Bartlomiej Wierzbinski and Dimitri Shishniashvili, worked on all four engagements. --- ### Phase 2: Our independent research — 12 new findings **Chart — Independent Research Findings** ``` CRITICAL ╢████████████ ║████████████ ║████████████ ║ HIGH ╢██████████████████ ║██████████████████ ║██████████████████ ║ MEDIUM ╢████████████████████████████████████████ ║████████████████████████████████████████ ║████████████████████████████████████████ ╚════════════════════════════════════════ 2 CRITICAL · 3 HIGH · 7 MEDIUM ``` **Body text:** Our independent security research found 12 vulnerabilities not present in OtterSec's reports. Two are rated critical: permissionless crank functions that allow anyone to control matching timing, and predictable vault closing orders with hardcoded 2% slippage on the public order book. Three are rated high: vault-backstop coupling where the protocol vault and backstop liquidator share the same account creating reflexive risk, deposit-redeem asymmetry with 3-day lockups on deposits but instant redemptions, and the ADL unrealized PnL direction inversion. Seven are rated medium, including three new findings from the v11 isolated margin feature: a margin check bypass when transferring collateral from cross to isolated positions, a global rate limit that can be exhausted via multiple subaccounts, and an admin callback that can censor pending withdrawals. --- ### Phase 3: The ADL regression — marked resolved, still broken **Diagram — THE ADL REGRESSION** ``` THE ADL REGRESSION ══════════════════════════════════════════════════════════════════════════════ OtterSec: OS-DLQ-ADV-00 "Incorrect Loss Attribution in ADL" Severity: HIGH Status: ✓ RESOLVED Date: Feb 2026 ────────────────────────────────────────────────────────────────────────────── OUR V11 BYTECODE ANALYSIS (Mar 30, 2026): backstop_liquidator_profit_tracker.mv: BYTE-FOR-BYTE IDENTICAL to v10 liquidation.mv:566 -- track_position_update(): passes user is_long (WRONG) should pass !is_long (backstop direction) FIX WAS NEVER APPLIED ══════════════════════════════════════════════════════════════════════════════ ⚠ Vault safety valve operates IN REVERSE ``` **Body text:** The ADL direction bug is our most significant finding because it reveals a gap between audit resolution and actual deployment. OtterSec independently discovered the same issue and labeled it OS-DLQ-ADV-00, Incorrect Loss Attribution in ADL, rated HIGH severity, and marked it as RESOLVED in their February 2026 report. However, our bytecode analysis of the v11 mainnet deployment on March 30, 2026 proves that the backstop profit tracker module is byte-for-byte identical to v10. The position tracking call in the liquidation module at line 266 still passes the liquidated user's is_long direction instead of the backstop's actual direction. The fix was either never applied or regressed during a subsequent deployment. The practical impact is that the vault's only automated safety valve against insolvency operates with an inverted trigger condition, meaning it fails to fire when the backstop is losing money and fires unnecessarily when the backstop is profiting. --- ## Conclusion Econia proved the concept. AIP-120 made it infrastructure. A custom AVL queue became a framework B+ tree. Atomic matching became async with 9 callbacks. 16,383 orders became unlimited. 8 modules became 78. And the orderbook is now part of Aptos itself. --- ## Key Facts at a Glance - Econia: one of only 3 crankless on-chain CLOBs ever built (with Phoenix on Solana and Manifest) - AVL queue: 11,295 bytes, 9,064 lines, bit-packed u128 nodes, 16,383 order cap per side - AIP-120: BigOrderedMap (B+ tree), 13,144 bytes (-57%), unlimited capacity, zero custom code - Decibel mainnet: 78 modules, 362,728 bytes, 162 entry functions, 15 markets, upgrade #11 - Live stats: $39.5M TVL, $986M all-time volume, 6.1M tx/day, 45.2% of all Aptos gas - OtterSec audits: 4 audits, 91 findings total, 0 critical, 3 high, all resolved - Independent research: 12 findings, 2 critical, 3 high, 7 medium - ADL bug: OS-DLQ-ADV-00 marked RESOLVED in Feb 2026 audit, confirmed NOT PATCHED in v11 bytecode (Mar 30, 2026) - AIP-141 impact: gas cost 10x increase → oracle costs alone reach $9.15M/year - Mainnet contract: 0x50ead22afd6ffd9769e3b3d6e0e64a2a350d68e8b102c4e72e33d0b8cfdfdb06