Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

49 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

CEX - Centralized Exchange on Solana

A high-performance centralized cryptocurrency exchange built on Solana with MPC (Multi-Party Computation) wallet management. This exchange provides real-time order matching, depth management, and trade execution with low latency and high throughput.

🎯 Project Overview

This is a professional-grade centralized exchange (CEX) that provides:

  • Real-time order matching using an in-memory matching engine
  • MPC-based wallet management for enhanced security
  • WebSocket real-time updates for trades, order depth, and market data
  • High-performance architecture with async processing and Redis pub/sub
  • TimescaleDB for time-series data storage (trades, orders, klines)
  • Multiple market support with configurable precision and limits

πŸ—οΈ Architecture

The exchange follows a microservices architecture with four main services:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client    │────▢│  API Server │────▢│   Engine    │────▢│    WS       β”‚
β”‚  (Browser)  │◀────│  (REST)     │◀────│  (Matching) │────▢│  (Real-time)β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚                    β”‚                    β”‚
                           β–Ό                    β–Ό                    β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   Redis     β”‚     β”‚   Redis     β”‚     β”‚   Redis     β”‚
                    β”‚   (Queue)   β”‚     β”‚  (Pub/Sub)  β”‚     β”‚   (DB Q)    β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                 β”‚
                                                 β–Ό
                                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                          β”‚  Database   β”‚
                                          β”‚ (Timescale) β”‚
                                          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Data Flow

  1. User submits order β†’ API validates and queues to Engine
  2. Engine processes β†’ Matches order, updates balances, creates fills
  3. Real-time updates β†’ Engine publishes to Redis pub/sub β†’ WS broadcasts to clients
  4. Persistence β†’ Engine queues to DB processor β†’ TimescaleDB stores trades/orders

πŸ“ Project Structure

CEX/
β”œβ”€β”€ cex-be/                          # Backend services (Rust)
β”‚   β”œβ”€β”€ api/                         # REST API Server
β”‚   β”‚   └── src/
β”‚   β”‚       β”œβ”€β”€ main.rs             # Server entry point (port 3010)
β”‚   β”‚       β”œβ”€β”€ redismanager.rs     # Redis client for API-Engine communication
β”‚   β”‚       β”œβ”€β”€ auth_service.rs     # JWT authentication logic
β”‚   β”‚       β”œβ”€β”€ middleware.rs       # Auth middleware, request validation
β”‚   β”‚       β”œβ”€β”€ validation.rs       # Order validation, market checks
β”‚   β”‚       β”œβ”€β”€ types.rs            # Request/response types
β”‚   β”‚       └── routes/             # API endpoints
β”‚   β”‚           β”œβ”€β”€ auth.rs         # /api/v1/auth - login, register
β”‚   β”‚           β”œβ”€β”€ order.rs        # /api/v1/order - create, cancel, get open orders
β”‚   β”‚           β”œβ”€β”€ markets.rs      # /api/v1/markets - list markets
β”‚   β”‚           β”œβ”€β”€ depth.rs        # /api/v1/depth - order book snapshot
β”‚   β”‚           β”œβ”€β”€ trades.rs       # /api/v1/trades - trade history
β”‚   β”‚           β”œβ”€β”€ ticker.rs       # /api/v1/tickers - 24h stats
β”‚   β”‚           └── klines.rs       # /api/v1/klines - OHLCV candles
β”‚   β”‚
β”‚   β”œβ”€β”€ engine/                      # Matching Engine
β”‚   β”‚   └── src/
β”‚   β”‚       β”œβ”€β”€ main.rs             # Engine entry point - listens to Redis queue
β”‚   β”‚       β”œβ”€β”€ engine.rs           # Core matching logic (705 lines)
β”‚   β”‚       β”œβ”€β”€ orderbook.rs        # Order book data structure (bids/asks)
β”‚   β”‚       β”œβ”€β”€ redis_manager.rs    # Redis clients (3 instances: queue, pubsub, db)
β”‚   β”‚       └── types.rs            # Internal message types
β”‚   β”‚
β”‚   β”œβ”€β”€ ws/                          # WebSocket Server
β”‚   β”‚   └── src/
β”‚   β”‚       β”œβ”€β”€ main.rs             # WS server entry point (port 8000)
β”‚   β”‚       β”œβ”€β”€ subscription_manager.rs  # Manages user subscriptions to channels
β”‚   β”‚       β”œβ”€β”€ user_manager.rs     # Maps user IDs to WebSocket connections
β”‚   β”‚       β”œβ”€β”€ user.rs             # User connection state
β”‚   β”‚       └── types.rs            # WS message types
β”‚   β”‚
β”‚   β”œβ”€β”€ db/                          # Database Layer
β”‚   β”‚   └── src/
β”‚   β”‚       β”œβ”€β”€ lib.rs              # DB pool, message processing
β”‚   β”‚       β”œβ”€β”€ schema.rs           # Diesel ORM schema definitions
β”‚   β”‚       β”œβ”€β”€ model.rs            # Database models (User, Trade, Order, Market, UserAsset)
β”‚   β”‚       └── start/
β”‚   β”‚           └── db.rs           # DB processor main - consumes db_processor queue
β”‚   β”‚
β”‚   β”œβ”€β”€ docker/                      # Docker configuration
β”‚   β”‚   β”œβ”€β”€ docker-compose.yml      # TimescaleDB + Redis containers
β”‚   β”‚   └── clear_data.sh           # Script to truncate tables and flush Redis
β”‚   β”‚
β”‚   β”œβ”€β”€ env.example                  # Environment variables template
β”‚   └── Cargo.toml                  # Workspace configuration
β”‚
β”œβ”€β”€ cex-fe/                          # Frontend (Next.js + TypeScript)
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ page.tsx                # Landing page
β”‚   β”‚   β”œβ”€β”€ login/                  # Authentication pages
β”‚   β”‚   β”œβ”€β”€ trade/[market]/         # Dynamic trading page for each market
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ TradeView.tsx       # Main trading interface
β”‚   β”‚   β”‚   β”œβ”€β”€ SwapUI.tsx          # Swap interface
β”‚   β”‚   β”‚   β”œβ”€β”€ MarketBar.tsx       # Market selector
β”‚   β”‚   β”‚   β”œβ”€β”€ depth/              # Order book depth components
β”‚   β”‚   β”‚   └── home/Trades.tsx     # Recent trades display
β”‚   β”‚   β”œβ”€β”€ context/
β”‚   β”‚   β”‚   β”œβ”€β”€ MarketContext.tsx   # Global market state
β”‚   β”‚   β”‚   └── UserContext.tsx     # User authentication state
β”‚   β”‚   └── utils/
β”‚   β”‚       β”œβ”€β”€ httpClient.ts       # Axios wrapper for API calls
β”‚   β”‚       β”œβ”€β”€ wsClient.ts         # WebSocket client wrapper
β”‚   β”‚       β”œβ”€β”€ ChartManager.ts     # Trading chart integration
β”‚   β”‚       └── types.ts            # TypeScript type definitions
β”‚   └── components/ui/               # Reusable UI components (shadcn)
β”‚
└── README.md                        # This file

πŸ”§ Services Overview

1. API Server (cex-be/api/)

  • Purpose: HTTP REST API for all client requests
  • Port: 3010
  • Tech: Rust (Poem web framework)
  • Key Responsibilities:
    • User authentication (JWT)
    • Order submission and validation
    • Market data retrieval
    • Communicates with Engine via Redis queue (messages)
    • CORS enabled for frontend integration

2. Matching Engine (cex-be/engine/)

  • Purpose: Core order matching and trade execution
  • Tech: Rust
  • Key Responsibilities:
    • Listens to Redis queue for orders
    • Maintains in-memory order books per market
    • Matches buy/sell orders (price-time priority)
    • Manages user balances (available/locked)
    • Publishes real-time updates to WS via Redis pub/sub
    • Queues persistence events to DB processor
    • Supports: CREATE_ORDER, CANCEL_ORDER, GET_DEPTH, GET_OPEN_ORDERS

3. WebSocket Server (cex-be/ws/)

  • Purpose: Real-time data streaming to clients
  • Port: 8000
  • Tech: Rust (tokio-tungstenite)
  • Key Responsibilities:
    • Manages WebSocket connections per user
    • Subscribes to Redis channels (e.g., trade@BTC-USD, depth@BTC-USD)
    • Broadcasts trades, depth updates to subscribed clients
    • Handles subscription/unsubscription logic

4. Database (cex-be/db/)

  • Purpose: Data persistence and time-series storage
  • Tech: TimescaleDB (PostgreSQL extension), Diesel ORM
  • Key Responsibilities:
    • Consumes DB queue from Engine
    • Stores trades, orders, market data
    • Provides OHLCV data for charts (klines)
    • Used by API for historical queries

5. Frontend (cex-fe/)

  • Purpose: User-facing trading interface
  • Tech: Next.js 14, TypeScript, Tailwind CSS
  • Features:
    • Trading view with order book, charts, trade history
    • User authentication
    • Real-time market data via WebSocket
    • Responsive design

πŸ”„ Message Flow Examples

Creating an Order

1. Client β†’ POST /api/v1/order β†’ API Server
2. API validates order (price, quantity, market, user balance)
3. API β†’ LPUSH "messages" β†’ Redis Queue
4. Engine ← BRPOP "messages" ← Redis Queue
5. Engine matches order against orderbook
6. Engine β†’ PUBLISH "trade@BTC-USD" β†’ Redis Pub/Sub
7. Engine β†’ RPUSH "db_events" β†’ Redis DB Queue
8. WS ← Receives pub/sub message ← Redis
9. WS β†’ Broadcasts to all subscribed clients
10. Client ← Receives trade update via WebSocket

Getting Order Depth

1. Client β†’ GET /api/v1/depth?market=BTC-USD β†’ API
2. API β†’ LPUSH "messages" β†’ Redis Queue
3. Engine pops message, queries in-memory orderbook
4. Engine β†’ PUBLISH response to API's unique channel
5. API receives response, returns to client

πŸ—„οΈ Database Schema

Core Tables

  • users: User accounts with encrypted JWT tokens
  • markets: Supported trading pairs (e.g., BTC-USD) with precision/limits
  • orders: Historical and active orders
  • trades: Executed trades with fill details
  • user_assets: User balances per asset (base/quote balances)

πŸ” Security Features

  • JWT Authentication: All protected endpoints require valid JWT token
  • Order Validation: Price/quantity validation before processing
  • Balance Checks: Engine verifies sufficient funds before locking
  • MPC Wallet Management: (Planned) Secure multi-party computation for private keys
  • Rate Limiting: (Planned) Prevent abuse on public endpoints

πŸš€ Setup Instructions

  • Install Rust toolchain
  • Install Node.js and npm
  • Set up TimescaleDB
  • Configure Redis instances
  • Set environment variables
  • Run database migrations
  • Start backend services
  • Start frontend development server

πŸ“Š Performance Characteristics

  • Latency: Sub-millisecond order matching
  • Throughput: Handles thousands of orders per second
  • Order Book: In-memory for fast matching, updates published in real-time
  • Persistence: Async queue-based for non-blocking writes

πŸ› οΈ Technologies Used

Backend:

  • Rust (async with Tokio)
  • Redis (queues, pub/sub, caching)
  • TimescaleDB (time-series data)
  • Diesel ORM (type-safe SQL)
  • Poem (REST API framework)
  • JWT (authentication)

Frontend:

  • Next.js 14 (App Router)
  • TypeScript
  • Tailwind CSS
  • Recharts/TradingView (charts)
  • WebSocket (real-time updates)

πŸ“ Development Status

  • βœ… Core matching engine implemented
  • βœ… REST API endpoints functional
  • βœ… WebSocket real-time updates working
  • βœ… Frontend trading interface in progress
  • ⏳ MPC wallet integration (planned)
  • ⏳ Advanced order types (limit, stop-loss) (planned)
  • ⏳ Admin dashboard (planned)

🀝 Contributing

This is a developer-focused project. Contributions welcome!

πŸ“„ License

[Your License Here]

About

A high-performance centralized cryptocurrency exchange built on Solana with MPC (Multi-Party Computation) wallet management. This exchange provides real-time order matching, depth management, and trade execution with low latency and high throughput.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages