> For the complete documentation index, see [llms.txt](https://world-book.gitbook.io/worldbook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://world-book.gitbook.io/worldbook/technical-documentation/architecture-overview.md).

# 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 Calc      │
                   │ • Role Check    │
                   │ • Registration  │
                   │ • Pause Control │
                   └─────────────────┘
```

## System Components

### Manager Contract

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

**Core Responsibilities:**

* **Access Control**: Implements role-based permissions (DEFAULT\_ADMIN\_ROLE, ADMIN\_ROLE, PAUSER\_ROLE)
* **OrderBook Registry**: Validates and registers new orderbook contracts
* **Fee Management**: Handles sophisticated 4-tier fee structure with rebates and discounts
* **Emergency Controls**: Provides pause/unpause functionality across all orderbooks
* **Quote Token Whitelist**: Manages which tokens can be used as quote assets

**Key Features:**

* Bytecode verification for security
* Multi-tier fee system with user-specific discounts
* Emergency pause controls for risk management
* Permissionless or admin-controlled registration

### OrderBook Contract

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)
* FIFO matching within price levels
* Sophisticated gas limit controls
* Self-trade prevention mechanisms

##

## 📈 Skip List Implementation

### The Secret to Our Gas Efficiency

Worldbook's groundbreaking use of probabilistic skip lists enables logarithmic complexity for all order book operations:

### 🎯 Performance Characteristics

| Operation | Complexity | vs Linear Search |
| --------- | ---------- | ---------------- |
| Search    | O(log n)   | 90% reduction    |
| Insert    | O(log n)   | 85% reduction    |
| Delete    | O(log n)   | 88% reduction    |
| Traverse  | O(n)       | Same             |

### 🏗️ Visual Structure

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

Level 3: ♾️─────────────────────────────────────→ 0️⃣
         │                              │
Level 2: ♾️──────→ $2050 ───────────────────────→ 0️⃣
         │          │                   │
Level 1: ♾️──→ $2050 ──→ $2045 ─────────────────→ 0️⃣
         │     │          │             │
Level 0: ♾️─→ $2050 ─→ $2045 ─→ $2040 ─→ $2035 ─→ 0️⃣

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

## Order Matching Algorithm

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 doubly-linked lists for efficient queue management

**Matching Process:**

```
1. New Order → Validation
2. Validation → Collateral Lock
3. Collateral Lock → Order Storage
4. Order Storage → Matching Engine
5. Matching Engine → Fill Orders
6. Fill Orders → Settlement
7. Settlement → Event Emission
```

## Fee System Architecture

Worldbook implements a sophisticated 4-tier fee structure:

1. **Layer 1 (Base)**: Default maker/taker fees set by protocol
2. **Layer 2 (OrderBook)**: OrderBook-specific fee overrides
3. **Layer 3 (User %)**: User-specific percentage discounts
4. **Layer 4 (User Abs)**: User-specific absolute discounts

**Fee Calculation Logic:**

```solidity
// Maker Fee Calculation (supports rebates)
function _calculateMakerFeeRate(address orderbook, address user) internal view returns (int256) {
    // Step 1: Get base rate (orderbook override OR default)
    int256 baseRate = orderbookMakerFeeOverrides[orderbook] != 0 ? 
                      orderbookMakerFeeOverrides[orderbook] : 
                      makerFee;
    
    // Step 2: Apply percentage discount ONLY if base rate is positive
    int256 afterPercentageDiscount = baseRate;
    if (baseRate > 0) {
        uint256 discountFactor = userMakerFeeDiscountFactor[user];
        if (discountFactor > 0 && discountFactor < 10000000) {  // Allow up to 1000% amplification
            afterPercentageDiscount = int256(uint256(baseRate) * discountFactor / FEE_DENOM);
        }
    }
    
    // Step 3: Apply absolute discount (always applied, can turn positive fees negative)
    uint256 absoluteDiscount = userMakerFeeDiscountAbs[user];
    return afterPercentageDiscount - int256(absoluteDiscount);
}

// Taker Fee Calculation (always non-negative)
function _calculateTakerFeeRate(address orderbook, address user) internal view returns (uint256) {
    // Step 1: Get base rate (orderbook override OR default)
    uint256 baseRate = orderbookTakerFeeOverrides[orderbook] != 0 ? 
                       orderbookTakerFeeOverrides[orderbook] : 
                       takerFee;
    
    // Step 2: Apply percentage discount
    uint256 afterPercentageDiscount = baseRate;
    uint256 discountFactor = userTakerFeeDiscountFactor[user];
    if (discountFactor > 0 && discountFactor < 10000000) {  // Allow up to 1000% amplification
        afterPercentageDiscount = baseRate * discountFactor / FEE_DENOM;
    }
    
    // Step 3: Apply absolute discount (ensure result doesn't go below 0)
    uint256 absoluteDiscount = userTakerFeeDiscountAbs[user];
    if (absoluteDiscount >= afterPercentageDiscount) {
        return 0; // Minimum taker fee is 0
    }
    return afterPercentageDiscount - absoluteDiscount;
}
```

## Security Architecture

### Access Control Hierarchy

```
DEFAULT_ADMIN_ROLE (Role Management)
    │
    ▼
ADMIN_ROLE (Operational Control)
    │
    ▼
PAUSER_ROLE (Emergency Response)
```

### Security Features

* **Bytecode Verification**: Ensures only legitimate contracts are registered
* **Reentrancy Protection**: Prevents reentrancy attacks
* **Pausable Operations**: Emergency stop functionality
* **Role-Based Access**: Granular permission system
* **Input Validation**: Comprehensive parameter checking

## Gas Optimization

Worldbook is designed for gas efficiency:

**Optimization Techniques:**

* Skip lists for logarithmic complexity
* Batch operations where possible
* Efficient storage patterns
* Gas limit controls to prevent out-of-gas errors
* Minimal external calls

**Gas Threshold Management:**

* Configurable gas thresholds for matching loops
* Order behavior controls (Cancel vs PlaceAtLast)
* Protection against gas limit attacks

## Scalability Features

### Modular Design

* Independent orderbook contracts for each trading pair
* Horizontal scaling through multiple orderbook instances
* Shared infrastructure through Manager contract

### Performance Optimizations

* Cached best bid/ask prices for O(1) access
* Efficient price level cleanup
* Optimized data structures for high-frequency operations
