DeepBook V3

repository·main·Indexed 42 days ago

https://github.com/mystenlabs/deepbookv3

A high-performance, decentralized central limit order book (CLOB) built on the Sui blockchain. It features low-latency trading via parallel execution, flashloans, governance, and a native $DEEP token. The ecosystem includes a server with Pyth Pro price adapter routes, an account identity model for fund custody, and DeepBook Margin for leveraged trading and lending pools.

Tokens
109.3K
Snippets
165
Records
452
Agent score
53%

What's inside DeepBook V3

  1. Overview of DeepBook Margin

    main

    DeepBook Margin is a decentralized margin trading protocol built on top of DeepBookV3 on Sui. It enables leveraged trading by allowing users to borrow assets against collateral to execute margin orders on DeepBook's central limit order book.

    Key features include:

    • Leveraged Trading: Borrow assets against collateral.
    • Risk Management: Advanced features like Take Profit and Stop Loss (TPSL) conditional orders.
    • Lending Pool: A mechanism where liquidity suppliers earn interest by providing assets for margin traders to borrow.
  2. Overview of Predict protocol

    main

    Predict is an on-chain protocol for European cash-settled binary options (digitals) on Sui. It allows users to trade range digitals based on an oracle feed at a fixed future expiry.

    Key Mechanics:

    • Range Digitals: A contract pays a fixed notional if the settlement price falls within a user-defined strike range; otherwise, it pays zero.
    • Liquidity Pool: A shared pool of liquidity providers writes every contract and earns the trading flow.

    Note: The protocol is currently in development and not yet deployed. There are no published package addresses, and the on-chain interface is subject to change. This repository describes the protocol design rather than providing an integration or SDK guide.

  3. Understand the Predict Predeploy workflow and system map

    main

    Predict uses a structured, machine-legible development process designed for stateless sessions (human or AI). The core workflow revolves around a single intake point for all work: open-items.md.

    The Pipeline:

    1. Intake: All bugs, suspicions, or questions must first be added to open-items.md.
    2. Measurement: If an item requires measurement, an experiment plan (question, harness strategy, and decision rule) must be written inline within the item before running.
    3. Evidence: Results of experiments are stored as immutable, dated records in evidence/.
    4. Resolution: Items are resolved by deletion in a PR. If a judgment call was made, the decision is recorded in response-policies.md as a 'tombstone' (a register entry titled resolves <id>).

    Authority Order (Highest to Lowest):

    1. sui move test (Ground truth)
    2. response-policies.md (Settled policy)
    3. open-items.md (Live work state)
    4. packages/predict/docs/design/decisions.md & .claude/rules/*.md (Design records/working rules)
    5. packages/predict/docs/ (Public disclosure)
  4. Understand the Predict protocol documentation

    main

    The Predict protocol documentation provides a technical overview of the protocol's mechanisms, design, and risks. It is intended for traders, liquidity providers, and evaluators.

    Note: This documentation is a conceptual guide and is not an integration or SDK guide. It does not contain transaction recipes or a function-by-function API reference.

    Current Protocol State (In Development):

    • Oracles: Live oracle data is read from standalone propbook Pyth and Block Scholes feeds (no in-package oracle).
    • Strikes: Strikes are represented as absolute integer ticks (raw_strike = tick × tick_size).
    • LP Layer: The Liquidity Provider (LP) layer is asynchronous. Supply and withdraw actions are queued and settled via a privileged periodic flush that marks the entire pool at a single, exact Net Asset Value (NAV).
    • Settlement: Terminal settlement is passive, preferring Propbook's exact Pyth history. It permits exact Block Scholes after a 30-second grace period when a normal redeem or pool-rebalance flow requires the settled branch.
  5. Understand Inventory-impact Charges and Rebates

    main

    Inventory impact is an optional mechanism that applies a layer of charges or rebates on top of the standard fee system to manage book liability. It is controlled by inventory_impact_max_rate (which defaults to 0 and is inert until enabled by an admin).

    The Mechanism

    The system uses a global state function $\phi(L)$ based on the book's payout liability $L$. The liability $L$ is calculated as: L = M + lambda * (T - M) Where:

    • M: Largest summed net payout at any one settlement price.
    • T: Sum of every live order's payout (quantity).
    • lambda: backing_buffer_lambda.

    Marginal Rate and Scaling

    The potential $\phi(L)$ scales based on a cadence max_expiry_allocation (scale $B$) and a maximum marginal rate $r_{max}$:

    • When $L \le B$: $\phi(L) = r_{max} \cdot L^2 / (2 \cdot B)$ (Rate rises linearly from 0 to $r_{max}$).
    • When $L > B$: $\phi(L) = r_{max} \cdot B / 2 + r_{max} \cdot (L - B)$ (Rate is capped at $r_{max}$).

    Charging and Rebating

    To ensure path-independence and prevent arbitrage, charges/rebates are calculated as the delta of the potential function:

    • Mint Charge: $\phi(L_{after}) - \phi(L_{before})$
    • Live-close Rebate: $\phi(L_{before}) - \phi(L_{after})$

    Accounting

    • Mint charges are held in ExpiryCash but earmarked in inventory_impact_reserve.
    • Live closes can only spend from this reserve.
    • Settlement releases any remaining reserve into ordinary expiry surplus.
  6. Understand the NAV Price-Memo optimization in DeepBook V3

    main

    The pricing::PriceMemo optimization changes how Net Asset Value (NAV) is calculated during a full-pool flush. Previously, the system performed redundant pricing evaluations for leveraged orders. The new mechanism caches each tick's up_price during an in-order linear walk. Subsequent correction walks for leveraged orders use a binary search to retrieve these cached values.

    Key technical details:

    • Exactness: The memo is bit-identical to the previous method; it caches rather than approximates.
    • Invariant: A 100% cache-hit invariant is enforced. If a tick is missing from the memo, the system aborts with the error ETickNotInPriceMemo (error code pricing:13).
    • Removals: The nav_interpolation_price_tolerance lever and its associated min_tick/max_tick machinery have been removed.
    • Performance: The optimization reduces the per-order flush gas slope by roughly half, shifting the bottleneck from pricing evaluations to the liquidation-book iteration (dynamic-field page walk).
  7. Use PauseCap for emergency protocol protections

    main

    A PauseCap is a revocable emergency capability minted into Registry.allowed_pause_caps by an admin. Holders of a PauseCap can trigger one-way emergency protections through the Registry:

    • Global Trading Pause: Forces trading_paused = true.
    • Per-Expiry Mint Pause: Forces mint_paused = true on a specific expiry.
    • Protocol-wide Freeze: Forces frozen = true.

    Key Characteristics:

    • One-way Engagement: PauseCap operations can only engage protections. They cannot be used to unpause or unfreeze.
    • Bypassing Version Gates: PauseCap operations bypass the version watermark, ensuring the kill switch remains functional even during a version freeze.
    • Recovery: Unpausing and unfreezing the protocol requires the AdminCap.
  8. Use Take Profit and Stop Loss (TPSL) orders

    main

    DeepBook Margin supports conditional orders that execute automatically when specific price conditions are met. These orders are stored on-chain and can be executed permissionlessly by anyone once the trigger price is reached.

    • Take Profit: Automatically closes a position when the price reaches a favorable target.
    • Stop Loss: Automatically closes a position to limit losses when the price moves against the user.
  9. Use Pyth Lazer feeds via PythFeed

    main

    A PythFeed is bound to a single Pyth Lazer feed (identified by a u32 feed id) and stores the latest source-native price payload.

    Key Concepts

    • Normalization: Predict uses normalized_spot() to convert raw Pyth data into a 1e9 fixed-point scale: price_1e9 = magnitude × 10^(exponent + 9).
    • Timestamps: Two distinct timestamps are tracked:
      • Generation Timestamp: The feedUpdateTimestamp from the Pyth payload (the true age of the price).
      • On-chain Landing Timestamp: The clock.timestamp_ms() when the update reached the blockchain.
    • Freshness: Predict compares the source_timestamp_ms in the returned OracleRead against the current clock and a configured freshness window. If a Pyth stall exceeds pyth_spot_freshness_ms, Predict falls back to the Block Scholes forward.

    Note: PythFeed does not decide authority or derive forwards; it only exposes raw and normalized facts.

  10. Manage Payout Tree node capacity limits

    main

    The max_payout_tree_nodes limit (RP-30) is designed to prevent flush-liveness attacks. However, an actor who fills a market's tree to its capacity (~960 boundary-creating min-size mints) will deny the creation of NEW strike ranges in that market until nodes are freed via closes or expiry.

    Mitigation Strategy: Future updates aim to collapse cheap node-minting shapes onto the free pos_inf_tick sentinel so that deep-OTM upper bounds stop minting nodes without hitting the hard capacity limit.

  11. Handle profit materialization at settlement

    main

    Profit is only recognized when it is cash-backed and irreversible (during the terminal cash flow from a settled expiry back to the pool). Marked profit in NAV is considered 'unmaterialized' and is excluded from protocol share calculations until materialization.

    Profit Calculation and Distribution

    The ledger tracks profit against a watermark. Profit is defined as new cash received above this watermark. It is first used to fill net_losses_to_fill (aggregate prior losses across all expiries). Any remaining profit is materialized and split:

    1. protocol_profit: floor(profit × protocol_reserve_profit_share) (where protocol_reserve_profit_share is a 1e9-scaled fraction).
    2. lp_profit: profit − protocol_profit (added to idle USDC, increasing NAV).

    Note on Protocol Cuts: If the protocol cut exceeds available idle USDC at the instant of settlement, the remainder is carried in pending_protocol_profit and drained during a later sweep. This prevents the settlement/flush process from aborting due to insufficient idle cash.

    protocol_profit = floor(profit × protocol_reserve_profit_share)
    
    // Remaining profit goes to LPs
    // lp_profit = profit − protocol_profit