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:

// 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

Last updated