# Architecture Overview

## Data Flow Architecture

```
                   ┌─────────────────┐
                   │     Users       │
                   └────────┬────────┘
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
        ▼                   ▼                   ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│   OrderBook   │   │   OrderBook   │   │   OrderBook   │
│   WETH/USDC   │   │   BTC/USDC    │   │   USDT/USDC   │
│               │   │               │   │               │
│• Order Create │   │• Order Create │   │• Order Create │
│• Matching     │   │• Matching     │   │• Matching     │
│• Settlement   │   │• Settlement   │   │• Settlement   │
│• Collateral   │   │• Collateral   │   │• Collateral   │
└───────┬───────┘   └───────┬───────┘   └───────┬───────┘
        │                   │                   │
        └───────────────────┼───────────────────┘
                            │
                            ▼
                   ┌─────────────────┐
                   │  Manager.sol    │
                   │                 │
                   │ • Fee Config    │
                   │ • Role Check    │
                   │ • Registration  │
                   │ • Pause Control │
                   └─────────────────┘
                   
```

## System Components

### Manager Contract

The `Manager.sol` contract serves as the central coordination layer for the entire dbook ecosystem:

**Core Responsibilities:**

* **Access Control**: Implements role-based permissions (DEFAULT\_ADMIN\_ROLE, ADMIN\_ROLE, PAUSER\_ROLE, FACTORY\_ROLE)
* **OrderBook Registry**: Validates and registers new OrderBook contracts after normalized-bytecode proofs and parameter checks
* **Fee Management**: Maintains a taker-only fee model with a protocol default plus per-orderbook overrides
* **Emergency Controls**: Provides pause/unpause functionality across all orderbooks
* **Token Policy**: Token whitelist for base/quote registration plus per-quote minimum notional settings

**Key Features:**

* Mandatory normalized-bytecode verification for security
* Simple two-layer taker-fee configuration (no user-specific tiers)
* Emergency pause controls for risk management
* Role-gated registration (no registration fees or public toggle)

#### OrderBook Contract <a href="#orderbook-contract" id="orderbook-contract"></a>

The `OrderBook.sol` contract implements the core trading engine:

**Core Responsibilities:**

* **Order Management**: Creates, stores, and manages all order lifecycles
* **Order Matching**: Efficient price-time priority matching algorithm
* **Skip List Implementation**: Optimized price level traversal and management
* **Collateral Management**: Handles token deposits and withdrawals
* **Trade Execution**: Processes fills and settlements

**Key Features:**

* Gas-optimized skip list data structures
* Advanced order types (Limit, Market, Post-Only, IOC/FOK) with configurable queue-unit granularity
* FIFO matching within price levels

### 📈 Skip List Implementation <a href="#skip-list-implementation" id="skip-list-implementation"></a>

Dbook's skip lists enables logarithmic complexity for all order book operations:

#### 🎯 Performance Characteristics <a href="#performance-characteristics" id="performance-characteristics"></a>

| Operation | Complexity |
| --------- | ---------- |
| Search    | O(log n)   |
| Insert    | O(log n)   |
| Delete    | O(log n)   |

#### 🏗️ Visual Structure <a href="#visual-structure" id="visual-structure"></a>

```
BUY SIDE (Descending)              SELL SIDE (Ascending)

Level 3: ...

Level 2: ♾️ → $128 ─────────────────────────────────────────────────────── → 0️⃣
                │                                                               
Level 1: ♾️ → $128 ─────────────────────→ $124 ─────────────────────→ $120 → 0️⃣
                │                           │                           │
Level 0: ♾️ → $128 → $127 → $126 → $125 → $124 → $123 → $122 → $121 → $120 → 0️⃣

♾️ = BUY_SENTINEL (MAX_UINT256)    0️⃣ = SELL_SENTINEL (0)

Active linked lists (`nextActive*Price` / `prevActive*Price`) keep best-bid/ask updates O(1), while the skip list arrays enable faster jumps during traversals.
```

### Order Matching Algorithm <a href="#order-matching-algorithm" id="order-matching-algorithm"></a>

The matching engine follows strict price-time priority:

1. **Price Priority**: Higher buy prices and lower sell prices get priority
2. **Time Priority**: Earlier orders at the same price level get filled first
3. **FIFO Execution**: Uses active price linked lists plus queue indices for efficient queue management

### Claim Range Settlement

Every resting order owns a continuous claim range—`(claimRangeStart, claimRangeEnd)`—that maps exactly to its slice of the execution queue at that price level. Each price level maintains a `cumulativeClaimable` counter, which advances whenever takers consume liquidity (moving the frontier forward).

Makers compute fills by intersecting their range with the latest frontier (including cancel adjustments):

```
filled = min(frontier, claimRangeEnd) - claimRangeStart
```

No iteration over other orders is required.

**No-delay cancel accounting**

* Per-price Fenwick trees track new-range increments (`fwEnd`) and cancelled amounts (`fwCancel`), plus a generation tag to invalidate stale indices.
* `queuePos { position, reserved }` keeps head/tail offsets stable even when orders are partially cancelled, reduced, or when a price level empties and later re-seeds.
* Frontier computation uses a single Fenwick “net upper bound,” keeping settlement stable across large fill counts.

**O(1) price-level matching**

* When takers match a price level, the engine never loops over makers. It only:
  * decrements volume
  * increments `cumulativeClaimable`
  * updates Fenwick trees
  * emits the aggregated trade
* Matching is O(1) per price level even with hundreds or thousands of resting maker orders inside that level.

**Instant maker withdrawals**

* Proceeds accrue to `withdrawableBase` (buy-side makers) or `withdrawableQuote` (sell-side makers).
* Claiming an order computes unclaimed fills from its claim range, updates remaining size, credits withdrawable balances, and can optionally execute an immediate token withdrawal.
* Makers can batch claims with constant-time gas behavior, regardless of book depth.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dbookio.gitbook.io/dbook/technical-documentation/architecture-overview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
