Skip to content

feat(defi): add order book example#41

Merged
mikemaccana merged 1 commit into
mainfrom
claude/order-book-skill-audit-U8lX3
Jun 2, 2026
Merged

feat(defi): add order book example#41
mikemaccana merged 1 commit into
mainfrom
claude/order-book-skill-audit-U8lX3

Conversation

@mikemaccana

@mikemaccana mikemaccana commented May 29, 2026

Copy link
Copy Markdown
Collaborator

Adds a central limit order book (CLOB) example at defi/order-book/anchor/. Complete Anchor 1.0 implementation with a zero-copy critbit slab order book ported from Openbook v2, a price-time priority matching engine, 23 LiteSVM Rust tests, and a README written for both finance beginners and Solana developers.

Program

Six instruction handlers:

  • initialize_market — creates a market for a base/quote token pair with market-owned base, quote, and fee vaults.
  • create_market_user — per-(user, market) PDA tracking open orders and unsettled balances; seeds ["market_user", market, owner].
  • place_order — limit order with price-time priority matching via remaining_accounts maker pairs; residual rests on the book.
  • cancel_order — owner-only cancel; locked funds credited to unsettled balance for retrieval via settle_funds.
  • settle_funds — withdraws unsettled base/quote from vault to user token accounts; checks-effects-interactions ordering (counters zeroed before CPIs).
  • withdraw_fees — market authority sweeps accumulated taker fees from the fee vault.

Market carries has_one constraints binding vaults and mints to their stored addresses, blocking account-substitution attacks.

Order book

Zero-copy critbit (binary radix trie) slab ported from openbook-dex/openbook-v2 — see src/state/slab/LICENSE-OPENBOOK. Each side holds up to 1024 leaves. Critbit is balanced-by-construction: depth is bounded by the bit width of the sort key (128 bits: price in the high 64, sequence number in the low 64), not by insertion order. This makes the monotonic-price DoS attack on a plain BST structurally impossible.

Money math

  • All balance arithmetic uses checked_* — no raw +/-/*// on money values.
  • Every product of two u64 money values is widened to u128 before multiplying, then narrowed back with try_into — prevents spurious overflow on large but arithmetically-valid trades.
  • fee_quote <= gross_quote enforced as a defence-in-depth invariant after each per-fill fee calculation.
  • All token movements use transfer_checked.

Tests

23 LiteSVM integration tests: setup, validation, cancel/settle round-trips, and full matching engine coverage (single fill, partial fill, remainder, multi-maker, price-time priority, price improvement, fee routing).

test result: ok. 23 passed; 0 failed

README

  • Finance background with Investopedia links on every term's first mention: limit order, bid, ask, maker/taker, liquidity, basis points, settlement, price improvement, bid-ask spread, and more.
  • "A real-world walkthrough: NVDAx/USDC" section — four participants with explicit motivations (Maria: fee revenue; Alice: bullish thesis on NVDAx; Bob: market-making the bid-ask spread; Carol: locking in profit), sample tokens (NVDAx and TSLAx tokenised equities priced in USDC), and a step-by-step trace through all seven instruction calls with exact accounts created or mutated at each step.
  • Full instruction lifecycle reference: accounts, PDAs, checks, token flows, state changes.
  • Step-by-step matching engine with worked numbers (taker bid, taker ask, partial fill, cancel/settle round-trip).
  • §8 "Why a balanced tree (critbit)?" — the monotonic-price DoS attack and why critbit's bit-bounded depth makes it structurally impossible.

Verification

From defi/order-book/anchor/:

anchor build && cargo test --manifest-path programs/order-book/Cargo.toml

All 23 tests pass. cargo check clean modulo two pre-existing lifetime-elision warnings inherited from the upstream Openbook v2 slab.

@mikemaccana mikemaccana force-pushed the claude/order-book-skill-audit-U8lX3 branch from 35851f4 to fcc49fd Compare May 31, 2026 14:33
@mikemaccana mikemaccana changed the title feat(defi/order-book): add CLOB example with critbit slab matching engine feat(defi): add order book example Jun 1, 2026
…b matching engine

Central Limit Order Book (CLOB) Anchor program for a single base/quote
token pair. Matches resting limit orders in price-time priority using a
critbit binary radix trie ported from Openbook v2, stored as a ~180 KB
zero-copy account.

Instruction handlers:
- initialize_market   — create Market PDA, three vaults, and OrderBook account
- create_market_user  — per-(user, market) PDA tracking open orders and unsettled balances
- place_order         — lock funds, match against caller-supplied maker pairs, rest remainder
- cancel_order        — credit unsettled balance, remove from book
- settle_funds        — transfer unsettled balances from vaults to user ATAs
- withdraw_fees       — authority-gated drain of the fee vault

Key design points:
- Funds lock into program-owned vaults on place_order; matching only
  updates unsettled_* counters; settle_funds is the single payout step
- Caller supplies maker pairs as remaining_accounts (Openbook v2 style);
  program enforces price-time order and ownership on what is passed
- OrderBook uses a critbit slab (balanced-by-construction binary radix
  trie) for O(log n) insert/lookup/delete, preventing degenerate-input
  attacks that would exhaust the compute budget
- Zero-copy AccountLoader for the ~180 KB OrderBook; two 1024-slot slabs
  back to back, well under Solana's per-account ceiling
- 23 LiteSVM integration tests covering matching, partial fills,
  price-time priority, cancel/settle round trips, and fee accounting

https://claude.ai/code/session_01G6iaAjzg8aoFwe8ZWWG9VR
@mikemaccana mikemaccana force-pushed the claude/order-book-skill-audit-U8lX3 branch from 961024d to d084fa3 Compare June 2, 2026 17:26
@mikemaccana mikemaccana merged commit c7c176a into main Jun 2, 2026
18 checks passed
@mikejhale mikejhale self-requested a review June 2, 2026 19:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants