A production-ready, native Rust Solana orderbook implementing deferred settlement architecture with zero-copy data structures and comprehensive security features.
This orderbook implements a deferred settlement architecture similar to production DEXs like Serum/OpenBook, providing:
- Real token custody during order placement
- Virtual settlement through authority-controlled event processing
- User-controlled withdrawal of settled tokens
- Production-grade security with comprehensive mint checks
- Zero-copy architecture using
bytemuckfor maximum performance - Memory-efficient large data structures with
#[repr(C)]
The orderbook follows a 3-phase deferred settlement model with zero-copy data access:
- Users transfer real SPL tokens to market vaults
- Orders are matched using price-time priority
- Fill events are logged for later settlement
- Remaining orders are added to the orderbook
- Authority-controlled batch processing (max 7 events)
- Updates both maker and taker balances per fill event
- Transfers:
locked_balanceโpending_balance - Efficient event array compaction
- User-initiated real token withdrawals
- Market authority PDA-signed transfers
- Transfers: Market vaults โ User token accounts
- Resets
pending_balanceto zero
- Mint Verification: Prevents wrong token deposits/withdrawals
- Vault Validation: Ensures correct market vault usage
- PDA Verification: Authority-based access control
- Account Validation: Comprehensive ownership checks
- Zero-Copy Architecture: Direct memory access using
bytemuck - Memory Layout Control:
#[repr(C, packed)]for optimal data structures - Batch Processing: Handle multiple events efficiently
- Gas Efficiency: Authority pays for settlement
- Memory Management: Efficient event array compaction
- Capital Efficiency: Perfect for high-frequency trading
- Modular Design: Clean separation of concerns
- Error Handling: Detailed error messages for debugging
- Flexible Deposits: Separate base/quote token deposits
- Account Management: Automatic PDA account creation
- Order Cancellation: Full cancel order functionality
- Comprehensive Testing: 8 test suites with 78+ assertions
User Places Order โ Real Token Transfer โ Event Logging
โ
Authority Processes Events โ Virtual Balance Updates โ Event Cleanup
โ
User Settles Balance โ Real Token Withdrawal โ Balance Reset
- Gas Efficiency: Authority batch processes events
- User Control: Withdraw tokens when convenient
- Scalability: Handle multiple trades efficiently
- Capital Efficiency: Optimal for high-frequency scenarios
#[repr(C, packed)]
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
pub struct Order {
pub owner: Pubkey,
pub market: Pubkey,
pub timestamp: i64,
pub order_id: u64,
pub price: u64,
pub quantity: u64,
pub filled_quantity: u64,
pub side: Side,
}
#[repr(C, packed)]
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
pub struct OrderBook {
pub orders: [Order; MAX_ORDERS], // 1024 orders
pub market: Pubkey,
pub active_orders_count: u64,
pub side: Side,
}// Zero-copy access to large data structures
let mut bids_data = bids_info.data.borrow_mut();
let bids: &mut OrderBook = bytemuck::from_bytes_mut(&mut bids_data);
let mut events_data = market_events_info.data.borrow_mut();
let events: &mut MarketEvents = bytemuck::from_bytes_mut(&mut events_data);- OrderBook: 107,561 bytes (~105KB) - Supports 1,024 orders
- MarketEvents: 50,232 bytes (~49KB) - Supports 512 events
- Order: 105 bytes per order
- Event: 98 bytes per event
// Verifies user token accounts contain correct mints
user_token_mint == market_state.expected_mint// Ensures operations use correct market vaults
vault_account.key == market_state.vault_key// Only authorized crank can process events
signer == market_state.consume_events_authority| Instruction | Description | Authority Required |
|---|---|---|
InitializeMarket |
Create new trading market | Market Creator |
DepositQuoteTokens |
Deposit quote tokens (creates account if needed) | User |
DepositBaseTokens |
Deposit base tokens | User |
PlaceOrder |
Place buy/sell order | User |
CancelOrder |
Cancel existing order | Order Owner |
ConsumeEvents |
Process settlement events | Crank Authority |
SettleBalance |
Withdraw settled tokens | User |
// Cancel order generates EventType::Out event
let cancel_event = Event {
event_type: EventType::Out,
maker: user_key,
taker: Pubkey::default(),
maker_order_id: order_id,
quantity: remaining_quantity,
price: order_price,
timestamp: clock.unix_timestamp,
side: order_side,
};pub struct MarketState {
pub authority: Pubkey, // Market creator
pub consume_events_authority: Pubkey, // Crank authority
pub base_mint: Pubkey, // Base token mint
pub quote_mint: Pubkey, // Quote token mint
pub base_vault: Pubkey, // Base token vault
pub quote_vault: Pubkey, // Quote token vault
pub market_events: Pubkey, // Events account
pub bids: Pubkey, // Bids orderbook
pub asks: Pubkey, // Asks orderbook
pub min_order_size: u64, // Minimum order size
pub tick_size: u64, // Price tick size
pub next_order_id: u64, // Order ID counter
pub last_price: u64, // Last trade price
pub volume_24h: u64, // 24h volume
pub fee_rate_bps: u16, // Fee rate (basis points)
pub bump: u8, // PDA bump
pub is_initialized: bool, // Initialization flag
}pub struct UserBalance {
pub owner: Pubkey, // User public key
pub market: Pubkey, // Market public key
pub available_base_balance: u64, // Available for new orders
pub available_quote_balance: u64, // Available for new orders
pub locked_base_balance: u64, // Locked in sell orders
pub locked_quote_balance: u64, // Locked in buy orders
pub pending_base_balance: u64, // Earned tokens (virtual)
pub pending_quote_balance: u64, // Earned tokens (virtual)
}#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EventType {
Fill = 0, // Order fill event
Out = 1, // Order cancellation event
}
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Side {
Buy = 1, // Buy order
Sell = 2, // Sell order
}Market: ["market", base_mint, quote_mint]
UserBalance: ["user_balance", user_key, market_key]
Vaults: ["base_vault", market_key] / ["quote_vault", market_key]
FeeAccount: ["fee_account", market_key]The project includes 8 comprehensive test suites with 78+ assertions:
- Initialize Market - Market creation and setup
- User Balance Management - Deposit quote and base tokens
- Order Placement & Matching - Buy/sell orders with event consumption
- Complex Multi-User Trading - Deep orderbook, market sweeps, partial fills
- Balance Settlement - Complex settlement scenarios and edge cases
- Extreme Order Scenarios - Micro-orders, large volumes, price extremes
- Comprehensive Stress Test - Deep orderbook with batch event processing
- Error Handling - Graceful handling of insufficient funds and edge cases
- โ Order placement and matching logic
- โ Event generation and consumption
- โ Balance settlement mechanisms
- โ Multi-user trading scenarios
- โ Market sweep operations
- โ Partial fill handling
- โ Error conditions and edge cases
- โ Memory safety and data integrity
- Rust 1.70+
- Solana CLI 1.16+
- Bun (for testing)
# Clone repository
git clone <repository-url>
cd Onchain-Orderbook
# Build program
cd program
cargo build-sbf
# Run comprehensive tests
cd ../client
bun test# Deploy to devnet
solana program deploy target/deploy/orderbook.so --url devnet
# Or deploy to localnet for testing
solana-test-validator
solana program deploy target/deploy/orderbook.so --url localhostOnchain-Orderbook/
โโโ program/
โ โโโ src/
โ โ โโโ lib.rs # Program entry point
โ โ โโโ state.rs # Zero-copy state definitions
โ โ โโโ instructions/
โ โ โโโ mod.rs # Instruction exports
โ โ โโโ initialize_market.rs # Market creation
โ โ โโโ create_user_account.rs # Token deposits
โ โ โโโ place_order.rs # Order placement & matching
โ โ โโโ cancel_order.rs # Order cancellation
โ โ โโโ consume_events.rs # Event processing
โ โ โโโ settle_balance.rs # Token withdrawal
โ โโโ Cargo.toml
โโโ client/
โ โโโ src/
โ โ โโโ orderbook.test.ts # Comprehensive test suite
โ โ โโโ states.ts # TypeScript state schemas
โ โโโ package.json
โโโ README.md
- โ Order Cancellation: Full cancel order functionality with EventType::Out
- โ Zero-Copy Architecture: Memory-efficient data structures using bytemuck
- โ Comprehensive Testing: 8 test suites covering all functionality
- โ Error Handling: Graceful handling of edge cases and insufficient funds
- โ Memory Safety: Proper order removal without unsafe operations
- โ Event Processing: Robust event consumption with batch processing
- Advanced order types (stop-loss, take-profit)
- Fee collection mechanism
- Referral program integration
- Cross-program invocation support
- Governance token integration
- Order book compression for even larger capacity
Please feel free to submit a Pull Request if you find any mistakes in my implementation.
**Built with โค๏ธ on Solana **
