mirror of
https://github.com/luxfi/dex.git
synced 2026-09-24 00:26:31 +00:00
docs: set up GitHub Pages documentation site
- Convert existing markdown docs to MDX in content/docs/ - Add comprehensive documentation pages: - Getting Started guide - API Reference - Architecture overview - SDK Guide - Orderbook engine documentation - Consensus layer documentation - Lending protocol documentation - Cross-chain bridge documentation - Configure Next.js for static export (GitHub Pages) - Add GitHub Actions workflow for automatic deployment - Set up CNAME for dex.lux.network custom domain - Fix MDX JSX expression escaping for curly braces
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
name: Deploy Documentation
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'docs/**'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: docs
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: docs/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build documentation
|
||||
run: pnpm build
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v5
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: docs/out
|
||||
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
@@ -0,0 +1,390 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: Complete API documentation for LX DEX - WebSocket, REST, and gRPC APIs
|
||||
---
|
||||
|
||||
# LX DEX API Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
LX DEX provides multiple API protocols for integration:
|
||||
- **WebSocket API** - Real-time market data and trading
|
||||
- **REST API** - Standard HTTP endpoints
|
||||
- **gRPC API** - High-performance binary protocol
|
||||
- **JSON-RPC 2.0** - Standard RPC interface
|
||||
|
||||
## WebSocket API
|
||||
|
||||
### Connection
|
||||
|
||||
```
|
||||
ws://localhost:8080/ws # Development
|
||||
wss://api.lux.network/ws # Production
|
||||
```
|
||||
|
||||
### Message Format
|
||||
|
||||
All WebSocket messages use JSON:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "message_type",
|
||||
"data": {},
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
### Subscriptions
|
||||
|
||||
#### Order Book
|
||||
|
||||
Subscribe to real-time order book updates:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "subscribe",
|
||||
"channel": "orderbook",
|
||||
"symbol": "BTC-USDT",
|
||||
"depth": 20
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "orderbook_snapshot",
|
||||
"symbol": "BTC-USDT",
|
||||
"bids": [[50000, 1.5], [49999, 2.0]],
|
||||
"asks": [[50001, 1.2], [50002, 0.8]],
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
#### Trades
|
||||
|
||||
Subscribe to trade stream:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "subscribe",
|
||||
"channel": "trades",
|
||||
"symbol": "BTC-USDT"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "trade",
|
||||
"symbol": "BTC-USDT",
|
||||
"price": 50000,
|
||||
"size": 0.5,
|
||||
"side": "buy",
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
### Trading Operations
|
||||
|
||||
#### Place Order
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "place_order",
|
||||
"symbol": "BTC-USDT",
|
||||
"side": "buy",
|
||||
"order_type": "limit",
|
||||
"price": 50000,
|
||||
"size": 0.1,
|
||||
"time_in_force": "GTC",
|
||||
"post_only": false
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "order_placed",
|
||||
"order_id": "123e4567-e89b-12d3-a456-426614174000",
|
||||
"status": "open",
|
||||
"filled_size": 0,
|
||||
"remaining_size": 0.1,
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
#### Cancel Order
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "cancel_order",
|
||||
"order_id": "123e4567-e89b-12d3-a456-426614174000"
|
||||
}
|
||||
```
|
||||
|
||||
## REST API
|
||||
|
||||
### Base URL
|
||||
|
||||
```
|
||||
http://localhost:8080/api/v1 # Development
|
||||
https://api.lux.network/v1 # Production
|
||||
```
|
||||
|
||||
### Endpoints
|
||||
|
||||
#### GET /orderbook/:symbol
|
||||
|
||||
Get order book snapshot.
|
||||
|
||||
**Parameters:**
|
||||
- `symbol` (path): Trading pair (e.g., BTC-USDT)
|
||||
- `depth` (query): Book depth (default: 20, max: 100)
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"symbol": "BTC-USDT",
|
||||
"bids": [
|
||||
{"price": 50000, "size": 1.5},
|
||||
{"price": 49999, "size": 2.0}
|
||||
],
|
||||
"asks": [
|
||||
{"price": 50001, "size": 1.2},
|
||||
{"price": 50002, "size": 0.8}
|
||||
],
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
#### POST /orders
|
||||
|
||||
Place a new order.
|
||||
|
||||
**Request:**
|
||||
|
||||
```json
|
||||
{
|
||||
"symbol": "BTC-USDT",
|
||||
"side": "buy",
|
||||
"type": "limit",
|
||||
"price": 50000,
|
||||
"size": 0.1,
|
||||
"time_in_force": "GTC"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"order_id": "123e4567-e89b-12d3-a456-426614174000",
|
||||
"symbol": "BTC-USDT",
|
||||
"side": "buy",
|
||||
"type": "limit",
|
||||
"price": 50000,
|
||||
"size": 0.1,
|
||||
"status": "open",
|
||||
"created_at": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
#### DELETE /orders/:order_id
|
||||
|
||||
Cancel an order.
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"order_id": "123e4567-e89b-12d3-a456-426614174000",
|
||||
"status": "cancelled",
|
||||
"cancelled_at": 1234567890
|
||||
}
|
||||
```
|
||||
|
||||
#### GET /trades
|
||||
|
||||
Get recent trades.
|
||||
|
||||
**Parameters:**
|
||||
- `symbol` (query): Trading pair
|
||||
- `limit` (query): Number of trades (default: 100, max: 1000)
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"trades": [
|
||||
{
|
||||
"trade_id": "abc123",
|
||||
"symbol": "BTC-USDT",
|
||||
"price": 50000,
|
||||
"size": 0.5,
|
||||
"side": "buy",
|
||||
"timestamp": 1234567890
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## gRPC API
|
||||
|
||||
### Proto Definition
|
||||
|
||||
```protobuf
|
||||
syntax = "proto3";
|
||||
package lxdex;
|
||||
|
||||
service TradingService {
|
||||
rpc PlaceOrder(OrderRequest) returns (OrderResponse);
|
||||
rpc CancelOrder(CancelRequest) returns (CancelResponse);
|
||||
rpc GetOrderBook(OrderBookRequest) returns (OrderBookResponse);
|
||||
rpc StreamTrades(StreamRequest) returns (stream Trade);
|
||||
}
|
||||
|
||||
message OrderRequest {
|
||||
string symbol = 1;
|
||||
string side = 2;
|
||||
string type = 3;
|
||||
double price = 4;
|
||||
double size = 5;
|
||||
}
|
||||
|
||||
message OrderResponse {
|
||||
string order_id = 1;
|
||||
string status = 2;
|
||||
int64 timestamp = 3;
|
||||
}
|
||||
```
|
||||
|
||||
### Connection
|
||||
|
||||
```go
|
||||
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
|
||||
client := pb.NewTradingServiceClient(conn)
|
||||
```
|
||||
|
||||
## JSON-RPC 2.0
|
||||
|
||||
### Endpoint
|
||||
|
||||
```
|
||||
POST http://localhost:8080/rpc
|
||||
```
|
||||
|
||||
### Methods
|
||||
|
||||
| Method | Description | Parameters |
|
||||
|--------|-------------|------------|
|
||||
| `lx_ping` | Test connectivity | `{}` |
|
||||
| `lx_getInfo` | Get node information | `{}` |
|
||||
| `lx_placeOrder` | Place order | symbol, type, side, price, size, userID |
|
||||
| `lx_cancelOrder` | Cancel order | orderId |
|
||||
| `lx_getOrder` | Get order details | orderId |
|
||||
| `lx_getOrderBook` | Get order book | depth |
|
||||
| `lx_getBestBid` | Get best bid | `{}` |
|
||||
| `lx_getBestAsk` | Get best ask | `{}` |
|
||||
| `lx_getTrades` | Get recent trades | limit |
|
||||
|
||||
### Example
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "lx_placeOrder",
|
||||
"params": {
|
||||
"symbol": "BTC-USD",
|
||||
"type": 0,
|
||||
"side": 0,
|
||||
"price": 50000,
|
||||
"size": 1.0,
|
||||
"userID": "trader1"
|
||||
},
|
||||
"id": 1
|
||||
}'
|
||||
```
|
||||
|
||||
## Authentication
|
||||
|
||||
### API Key
|
||||
|
||||
Include in headers:
|
||||
|
||||
```
|
||||
X-API-Key: your_api_key_here
|
||||
X-API-Secret: your_api_secret_here
|
||||
```
|
||||
|
||||
### JWT
|
||||
|
||||
After login:
|
||||
|
||||
```
|
||||
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
### Limits
|
||||
|
||||
| Endpoint Type | Limit |
|
||||
|---------------|-------|
|
||||
| Public endpoints | 100 req/min |
|
||||
| Private endpoints | 300 req/min |
|
||||
| WebSocket connections | 5 concurrent |
|
||||
| Order placement | 10 orders/sec |
|
||||
|
||||
### Headers
|
||||
|
||||
```
|
||||
X-RateLimit-Limit: 100
|
||||
X-RateLimit-Remaining: 95
|
||||
X-RateLimit-Reset: 1234567890
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Error Format
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "INSUFFICIENT_BALANCE",
|
||||
"message": "Insufficient balance for order",
|
||||
"details": {
|
||||
"required": 100.5,
|
||||
"available": 50.0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Error Codes
|
||||
|
||||
| Code | Description |
|
||||
|------|-------------|
|
||||
| `INVALID_SYMBOL` | Trading pair not supported |
|
||||
| `INVALID_ORDER_TYPE` | Order type not recognized |
|
||||
| `INSUFFICIENT_BALANCE` | Not enough balance |
|
||||
| `ORDER_NOT_FOUND` | Order ID does not exist |
|
||||
| `RATE_LIMIT_EXCEEDED` | Too many requests |
|
||||
| `UNAUTHORIZED` | Authentication required |
|
||||
| `FORBIDDEN` | Access denied |
|
||||
| `INTERNAL_ERROR` | Server error |
|
||||
|
||||
### JSON-RPC Error Codes
|
||||
|
||||
| Code | Description |
|
||||
|------|-------------|
|
||||
| `-32700` | Parse Error |
|
||||
| `-32600` | Invalid Request |
|
||||
| `-32601` | Method Not Found |
|
||||
| `-32602` | Invalid Params |
|
||||
| `-32603` | Internal Error |
|
||||
@@ -0,0 +1,380 @@
|
||||
---
|
||||
title: Architecture
|
||||
description: LX DEX system architecture - multi-layer design for planet-scale performance
|
||||
---
|
||||
|
||||
# LX DEX Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
The LX DEX is built on a highly scalable, modular architecture designed to achieve planet-scale performance with sub-microsecond latency. The system uses a multi-layer approach with specialized components for different aspects of trading.
|
||||
|
||||
## System Architecture
|
||||
|
||||
```
|
||||
+------------------------------------------------------------+
|
||||
| Client Layer |
|
||||
| Web UI | Mobile | API Clients | Trading Bots | SDKs |
|
||||
+----------------------------+-------------------------------+
|
||||
|
|
||||
+----------------------------v-------------------------------+
|
||||
| Gateway Layer |
|
||||
| Load Balancer | Rate Limiter | Auth | WebSocket/gRPC |
|
||||
+----------------------------+-------------------------------+
|
||||
|
|
||||
+----------------------------v-------------------------------+
|
||||
| Application Layer |
|
||||
| Order Management | Risk Engine | Market Data | Admin |
|
||||
+----------------------------+-------------------------------+
|
||||
|
|
||||
+----------------------------v-------------------------------+
|
||||
| Core Engine Layer |
|
||||
| Matching Engine | Clearing | Settlement | Liquidation |
|
||||
+----------------------------+-------------------------------+
|
||||
|
|
||||
+----------------------------v-------------------------------+
|
||||
| Consensus Layer |
|
||||
| DAG Consensus | Validator Network | State Machine |
|
||||
+----------------------------+-------------------------------+
|
||||
|
|
||||
+----------------------------v-------------------------------+
|
||||
| Storage Layer |
|
||||
| Order DB | Trade History | State DB | Archive |
|
||||
+------------------------------------------------------------+
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
### Matching Engine
|
||||
|
||||
The heart of the DEX, responsible for order matching with extreme performance.
|
||||
|
||||
```go
|
||||
type MatchingEngine struct {
|
||||
orderBooks map[string]*OrderBook // Per-symbol order books
|
||||
lockFreePool *LockFreeOrderPool // Lock-free order allocation
|
||||
tradeBuffer *CircularTradeBuffer // Zero-copy trade buffer
|
||||
backend Backend // Go/C++/GPU backend
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Lock-free data structures with atomic operations
|
||||
- Memory pooling to minimize GC
|
||||
- Multiple backends with auto-selection
|
||||
- Price-time priority matching algorithm
|
||||
|
||||
**Performance Optimizations:**
|
||||
- Integer price levels (avoid floating-point)
|
||||
- B-tree for price levels: O(log n) operations
|
||||
- Circular buffers for zero-copy trade recording
|
||||
- SIMD operations in C++ backend
|
||||
|
||||
### Order Book
|
||||
|
||||
Each trading pair has its own order book with optimized data structures:
|
||||
|
||||
```
|
||||
BID SIDE ASK SIDE
|
||||
+--------------+ +--------------+
|
||||
| Price: 50100 | | Price: 50101 |
|
||||
| Orders: [....| | Orders: [....|
|
||||
+------+-------+ +------+-------+
|
||||
| |
|
||||
+------v-------+ +------v-------+
|
||||
| Price: 50099 | | Price: 50102 |
|
||||
| Orders: [....| | Orders: [....|
|
||||
+------+-------+ +------+-------+
|
||||
| |
|
||||
(B-Tree) (B-Tree)
|
||||
```
|
||||
|
||||
**Order Types:**
|
||||
- **Market**: Execute immediately at best price
|
||||
- **Limit**: Execute at specified price or better
|
||||
- **Stop**: Trigger when price reaches threshold
|
||||
- **Iceberg**: Show only partial size
|
||||
- **Hidden**: Completely hidden from book
|
||||
- **Pegged**: Track reference price
|
||||
|
||||
### Risk Engine
|
||||
|
||||
Pre-trade and post-trade risk management.
|
||||
|
||||
**Pre-trade Checks:**
|
||||
- Balance verification
|
||||
- Position limits
|
||||
- Leverage constraints
|
||||
- Rate limiting
|
||||
- Order validation
|
||||
|
||||
**Post-trade Processing:**
|
||||
- PnL calculation
|
||||
- Margin requirements
|
||||
- Liquidation monitoring
|
||||
- Insurance fund management
|
||||
|
||||
### Clearing & Settlement
|
||||
|
||||
Handles the finalization of trades with atomic settlement:
|
||||
|
||||
```go
|
||||
func (c *Clearinghouse) SettleTrade(trade *Trade) error {
|
||||
tx := c.BeginTransaction()
|
||||
defer tx.Rollback()
|
||||
|
||||
// Update buyer balance
|
||||
tx.DebitAccount(trade.Buyer, trade.QuoteAmount)
|
||||
tx.CreditAccount(trade.Buyer, trade.BaseAmount)
|
||||
|
||||
// Update seller balance
|
||||
tx.DebitAccount(trade.Seller, trade.BaseAmount)
|
||||
tx.CreditAccount(trade.Seller, trade.QuoteAmount)
|
||||
|
||||
// Record trade
|
||||
tx.RecordTrade(trade)
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
```
|
||||
|
||||
### DAG Consensus
|
||||
|
||||
Directed Acyclic Graph consensus for parallel processing:
|
||||
|
||||
```
|
||||
+-------+
|
||||
| Node A|-------+
|
||||
+---+---+ |
|
||||
| +---v---+
|
||||
| | Node C|
|
||||
| +---+---+
|
||||
+---v---+ |
|
||||
| Node B|-------+
|
||||
+-------+
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Parallel validation across multiple chains
|
||||
- 50ms consensus time with fast finality
|
||||
- Post-quantum signatures ready
|
||||
- K=3 validators for Byzantine fault tolerance
|
||||
|
||||
### Cross-Chain Bridge
|
||||
|
||||
Universal bridge for asset transfers between chains.
|
||||
|
||||
**Supported Chains:**
|
||||
- Ethereum & EVM-compatible
|
||||
- Cosmos ecosystem
|
||||
- Solana
|
||||
- Bitcoin (via wrapped tokens)
|
||||
- Lux native chain
|
||||
|
||||
**Bridge Flow:**
|
||||
1. **Lock**: Assets locked on source chain
|
||||
2. **Verify**: Validators confirm transaction
|
||||
3. **Mint**: Equivalent assets minted on destination
|
||||
4. **Complete**: User receives bridged assets
|
||||
|
||||
## Data Flow
|
||||
|
||||
### Order Lifecycle
|
||||
|
||||
```
|
||||
Client Request
|
||||
|
|
||||
v
|
||||
[Gateway Layer]
|
||||
|
|
||||
+-> Rate Limiting
|
||||
+-> Authentication
|
||||
+-> Validation
|
||||
|
|
||||
v
|
||||
[Risk Engine]
|
||||
|
|
||||
+-> Balance Check
|
||||
+-> Position Limits
|
||||
+-> Margin Requirements
|
||||
|
|
||||
v
|
||||
[Matching Engine]
|
||||
|
|
||||
+-> Order Book Update
|
||||
+-> Match Orders
|
||||
+-> Generate Trades
|
||||
|
|
||||
v
|
||||
[Clearinghouse]
|
||||
|
|
||||
+-> Clear Trades
|
||||
+-> Update Balances
|
||||
+-> Settlement
|
||||
|
|
||||
v
|
||||
[Consensus Layer]
|
||||
|
|
||||
+-> Validate Block
|
||||
+-> Achieve Consensus
|
||||
+-> Finalize State
|
||||
|
|
||||
v
|
||||
[Storage Layer]
|
||||
|
|
||||
+-> Persist Data
|
||||
```
|
||||
|
||||
## Performance Architecture
|
||||
|
||||
### Multi-Engine Design
|
||||
|
||||
The DEX supports multiple execution backends:
|
||||
|
||||
| Engine | Throughput | Latency | Use Case |
|
||||
|--------|-----------|---------|----------|
|
||||
| Pure Go | 13M+ orders/sec | 75.9ns | Portable |
|
||||
| C++ | 30M+ orders/sec | 25ns | HFT |
|
||||
| GPU/MLX | 100M+ orders/sec | 2ns | Planet-scale |
|
||||
|
||||
### Memory Management
|
||||
|
||||
**Object Pooling:**
|
||||
|
||||
```go
|
||||
var orderPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &Order{}
|
||||
},
|
||||
}
|
||||
|
||||
func GetOrder() *Order {
|
||||
return orderPool.Get().(*Order)
|
||||
}
|
||||
|
||||
func PutOrder(order *Order) {
|
||||
order.Reset()
|
||||
orderPool.Put(order)
|
||||
}
|
||||
```
|
||||
|
||||
**Zero-Copy Techniques:**
|
||||
- Use of `unsafe` for direct memory access
|
||||
- Circular buffers for trades
|
||||
- Memory-mapped files for large datasets
|
||||
|
||||
### Concurrency Model
|
||||
|
||||
**Lock-Free Operations:**
|
||||
|
||||
```go
|
||||
type AtomicCounter struct {
|
||||
value atomic.Int64
|
||||
}
|
||||
|
||||
func (c *AtomicCounter) Increment() int64 {
|
||||
return c.value.Add(1)
|
||||
}
|
||||
```
|
||||
|
||||
**Goroutine Management:**
|
||||
- Worker pools for order processing
|
||||
- Bounded channels for backpressure
|
||||
- Context for graceful shutdown
|
||||
|
||||
## Scalability
|
||||
|
||||
### Horizontal Scaling
|
||||
|
||||
**Sharding Strategy:**
|
||||
- By Symbol: Each shard handles specific trading pairs
|
||||
- By User: Users distributed across shards
|
||||
- By Region: Geographic distribution
|
||||
|
||||
**Load Balancing:**
|
||||
- Consistent hashing for shard selection
|
||||
- Health-based routing
|
||||
- Automatic failover
|
||||
|
||||
### Vertical Scaling
|
||||
|
||||
**Hardware Optimization:**
|
||||
- CPU pinning for critical threads
|
||||
- NUMA-aware memory allocation
|
||||
- Kernel bypass networking (DPDK)
|
||||
|
||||
## Security Architecture
|
||||
|
||||
### Cryptography
|
||||
|
||||
- **Ed25519**: Digital signatures
|
||||
- **BLS**: Aggregate signatures
|
||||
- **Post-Quantum**: Lattice-based crypto ready (Dilithium, Kyber)
|
||||
|
||||
### Access Control
|
||||
|
||||
- **JWT**: API authentication
|
||||
- **RBAC**: Role-based permissions
|
||||
- **2FA**: Two-factor authentication
|
||||
|
||||
### Network Security
|
||||
|
||||
- **TLS 1.3**: Encrypted connections
|
||||
- **QZMQ**: Quantum-secure messaging
|
||||
- **DDoS Protection**: Rate limiting and filtering
|
||||
|
||||
## Monitoring & Observability
|
||||
|
||||
### Metrics Collection
|
||||
|
||||
```go
|
||||
var (
|
||||
ordersProcessed = prometheus.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "orders_processed_total",
|
||||
Help: "Total number of orders processed",
|
||||
},
|
||||
)
|
||||
|
||||
orderLatency = prometheus.NewHistogram(
|
||||
prometheus.HistogramOpts{
|
||||
Name: "order_latency_seconds",
|
||||
Help: "Order processing latency",
|
||||
},
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### Distributed Tracing
|
||||
|
||||
- OpenTelemetry integration
|
||||
- Request flow visualization
|
||||
- Performance bottleneck identification
|
||||
|
||||
## Deployment Architecture
|
||||
|
||||
### Container Strategy
|
||||
|
||||
```yaml
|
||||
services:
|
||||
matching-engine:
|
||||
replicas: 3
|
||||
resources:
|
||||
limits:
|
||||
cpu: "4"
|
||||
memory: "8Gi"
|
||||
|
||||
risk-engine:
|
||||
replicas: 2
|
||||
resources:
|
||||
limits:
|
||||
cpu: "2"
|
||||
memory: "4Gi"
|
||||
```
|
||||
|
||||
### High Availability
|
||||
|
||||
- Multi-region deployment
|
||||
- Automatic failover
|
||||
- Data replication
|
||||
- Disaster recovery
|
||||
@@ -0,0 +1,387 @@
|
||||
---
|
||||
title: Cross-Chain Bridge
|
||||
description: Universal asset bridge for cross-chain transfers between major blockchains
|
||||
---
|
||||
|
||||
# Cross-Chain Bridge
|
||||
|
||||
The LX DEX bridge enables seamless asset transfers between multiple blockchains.
|
||||
|
||||
## Overview
|
||||
|
||||
The bridge supports:
|
||||
- **Multi-chain transfers** across major blockchains
|
||||
- **Lock-and-mint** mechanism for wrapped assets
|
||||
- **MPC threshold signatures** for security
|
||||
- **Sub-minute finality** for transfers
|
||||
|
||||
## Supported Chains
|
||||
|
||||
| Chain | Status | Assets |
|
||||
|-------|--------|--------|
|
||||
| Lux Network | Native | LUX, all DEX assets |
|
||||
| Ethereum | Live | ETH, ERC-20 tokens |
|
||||
| Arbitrum | Live | ARB, ERC-20 tokens |
|
||||
| Optimism | Live | OP, ERC-20 tokens |
|
||||
| Polygon | Live | MATIC, ERC-20 tokens |
|
||||
| BNB Chain | Live | BNB, BEP-20 tokens |
|
||||
| Avalanche | Live | AVAX, ARC-20 tokens |
|
||||
| Solana | Beta | SOL, SPL tokens |
|
||||
| Cosmos | Beta | ATOM, IBC tokens |
|
||||
|
||||
## Bridge Flow
|
||||
|
||||
```
|
||||
Source Chain Bridge Network Destination Chain
|
||||
+-------------+ +----------------+ +--------------+
|
||||
| | | | | |
|
||||
| Lock Assets | -------------> | Verify & Sign | ----------> | Mint Wrapped |
|
||||
| | | (MPC Network) | | Assets |
|
||||
+-------------+ +----------------+ +--------------+
|
||||
| | |
|
||||
v v v
|
||||
User sends 3/5 validators User receives
|
||||
to bridge confirm tx bridged tokens
|
||||
contract
|
||||
```
|
||||
|
||||
## Transfer Assets
|
||||
|
||||
### Bridge to Lux
|
||||
|
||||
```go
|
||||
// Bridge ETH from Ethereum to Lux
|
||||
transfer, err := bridge.TransferToLux(ctx, &TransferParams{
|
||||
SourceChain: "ethereum",
|
||||
Asset: "ETH",
|
||||
Amount: "10.0",
|
||||
Recipient: "lux1...", // Lux address
|
||||
})
|
||||
|
||||
// Track transfer status
|
||||
status, err := bridge.GetTransferStatus(ctx, transfer.ID)
|
||||
fmt.Printf("Status: %s\n", status.Status)
|
||||
fmt.Printf("Confirmations: %d/%d\n", status.Confirmations, status.Required)
|
||||
```
|
||||
|
||||
### Bridge from Lux
|
||||
|
||||
```go
|
||||
// Bridge wrapped ETH from Lux to Ethereum
|
||||
transfer, err := bridge.TransferFromLux(ctx, &TransferParams{
|
||||
DestChain: "ethereum",
|
||||
Asset: "wETH",
|
||||
Amount: "10.0",
|
||||
Recipient: "0x...", // Ethereum address
|
||||
})
|
||||
```
|
||||
|
||||
### Cross-Chain Swap
|
||||
|
||||
Bridge and swap in one transaction:
|
||||
|
||||
```go
|
||||
// Swap ETH on Ethereum for LUX on Lux Network
|
||||
result, err := bridge.CrossChainSwap(ctx, &SwapParams{
|
||||
SourceChain: "ethereum",
|
||||
SourceAsset: "ETH",
|
||||
SourceAmount: "1.0",
|
||||
DestChain: "lux",
|
||||
DestAsset: "LUX",
|
||||
MinReceived: "950.0", // Slippage protection
|
||||
Recipient: "lux1...",
|
||||
})
|
||||
```
|
||||
|
||||
## Bridge Architecture
|
||||
|
||||
### Lock Contract (Source Chain)
|
||||
|
||||
```solidity
|
||||
// Simplified Ethereum bridge contract
|
||||
contract LuxBridge {
|
||||
mapping(bytes32 => bool) public processedTransfers;
|
||||
address[] public validators;
|
||||
uint256 public threshold = 3;
|
||||
|
||||
function lock(
|
||||
address token,
|
||||
uint256 amount,
|
||||
string calldata destAddress
|
||||
) external payable {
|
||||
// Transfer tokens to bridge
|
||||
IERC20(token).transferFrom(msg.sender, address(this), amount);
|
||||
|
||||
emit TokensLocked(
|
||||
msg.sender,
|
||||
token,
|
||||
amount,
|
||||
destAddress,
|
||||
block.timestamp
|
||||
);
|
||||
}
|
||||
|
||||
function unlock(
|
||||
address token,
|
||||
uint256 amount,
|
||||
address recipient,
|
||||
bytes[] calldata signatures
|
||||
) external {
|
||||
bytes32 hash = keccak256(abi.encodePacked(token, amount, recipient));
|
||||
require(!processedTransfers[hash], "Already processed");
|
||||
require(verifySignatures(hash, signatures), "Invalid signatures");
|
||||
|
||||
processedTransfers[hash] = true;
|
||||
IERC20(token).transfer(recipient, amount);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### MPC Network
|
||||
|
||||
The bridge is secured by an MPC (Multi-Party Computation) network:
|
||||
|
||||
```go
|
||||
// Bridge validator configuration
|
||||
type BridgeValidator struct {
|
||||
NodeID string
|
||||
PublicKey []byte
|
||||
Stake uint64
|
||||
}
|
||||
|
||||
// 3-of-5 threshold signing
|
||||
type MPCConfig struct {
|
||||
Threshold int // 3
|
||||
TotalNodes int // 5
|
||||
SignTimeout time.Duration
|
||||
}
|
||||
```
|
||||
|
||||
### Wrapped Assets
|
||||
|
||||
Bridged assets are represented as wrapped tokens on Lux:
|
||||
|
||||
| Original | Wrapped | Contract |
|
||||
|----------|---------|----------|
|
||||
| ETH | wETH.lux | `lux1eth...` |
|
||||
| BTC | wBTC.lux | `lux1btc...` |
|
||||
| USDC | wUSDC.lux | `lux1usdc...` |
|
||||
|
||||
## Transfer Status
|
||||
|
||||
Track transfer progress:
|
||||
|
||||
```go
|
||||
// Poll for status
|
||||
for {
|
||||
status, err := bridge.GetTransferStatus(ctx, transferID)
|
||||
|
||||
switch status.Status {
|
||||
case "pending":
|
||||
fmt.Println("Waiting for source confirmation...")
|
||||
case "confirming":
|
||||
fmt.Printf("Confirmations: %d/%d\n",
|
||||
status.Confirmations, status.Required)
|
||||
case "signing":
|
||||
fmt.Println("MPC validators signing...")
|
||||
case "relaying":
|
||||
fmt.Println("Relaying to destination chain...")
|
||||
case "completed":
|
||||
fmt.Printf("Transfer complete! Tx: %s\n", status.DestTxHash)
|
||||
return
|
||||
case "failed":
|
||||
fmt.Printf("Transfer failed: %s\n", status.Error)
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
```
|
||||
|
||||
## Fees
|
||||
|
||||
### Transfer Fees
|
||||
|
||||
| Route | Base Fee | Min Fee |
|
||||
|-------|----------|---------|
|
||||
| ETH -> Lux | 0.1% | 0.001 ETH |
|
||||
| Lux -> ETH | 0.1% | $5 USD |
|
||||
| Cross-chain swap | 0.2% | $10 USD |
|
||||
|
||||
### Gas Sponsorship
|
||||
|
||||
For small transfers, gas can be sponsored:
|
||||
|
||||
```go
|
||||
transfer, err := bridge.TransferToLux(ctx, &TransferParams{
|
||||
// ...
|
||||
SponsorGas: true, // Bridge pays destination gas
|
||||
})
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
### Validator Requirements
|
||||
|
||||
- Minimum 100,000 LUX stake
|
||||
- Multi-location deployment
|
||||
- Hardware security modules (HSM)
|
||||
- 99.9% uptime requirement
|
||||
|
||||
### Transfer Limits
|
||||
|
||||
| Asset | Per Transfer | Daily Limit |
|
||||
|-------|--------------|-------------|
|
||||
| ETH | 100 ETH | 1,000 ETH |
|
||||
| BTC | 10 BTC | 100 BTC |
|
||||
| Stablecoins | $1M | $10M |
|
||||
|
||||
### Emergency Pause
|
||||
|
||||
Bridge can be paused by governance:
|
||||
|
||||
```go
|
||||
// Check bridge status
|
||||
status, err := bridge.GetBridgeStatus(ctx, "ethereum")
|
||||
|
||||
if status.Paused {
|
||||
fmt.Printf("Bridge paused: %s\n", status.PauseReason)
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### TransferToLux
|
||||
|
||||
```go
|
||||
func (b *Bridge) TransferToLux(ctx context.Context, params *TransferParams) (*Transfer, error)
|
||||
```
|
||||
|
||||
### TransferFromLux
|
||||
|
||||
```go
|
||||
func (b *Bridge) TransferFromLux(ctx context.Context, params *TransferParams) (*Transfer, error)
|
||||
```
|
||||
|
||||
### CrossChainSwap
|
||||
|
||||
```go
|
||||
func (b *Bridge) CrossChainSwap(ctx context.Context, params *SwapParams) (*SwapResult, error)
|
||||
```
|
||||
|
||||
### GetTransferStatus
|
||||
|
||||
```go
|
||||
func (b *Bridge) GetTransferStatus(ctx context.Context, transferID string) (*TransferStatus, error)
|
||||
```
|
||||
|
||||
### GetSupportedChains
|
||||
|
||||
```go
|
||||
func (b *Bridge) GetSupportedChains(ctx context.Context) ([]*ChainInfo, error)
|
||||
```
|
||||
|
||||
### GetFeeEstimate
|
||||
|
||||
```go
|
||||
func (b *Bridge) GetFeeEstimate(ctx context.Context, params *FeeParams) (*FeeEstimate, error)
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```go
|
||||
// Listen for bridge events
|
||||
bridge.OnTransferInitiated(func(event *TransferEvent) {
|
||||
fmt.Printf("Transfer initiated: %s\n", event.ID)
|
||||
fmt.Printf("From: %s (%s)\n", event.SourceChain, event.SourceAddress)
|
||||
fmt.Printf("Amount: %s %s\n", event.Amount, event.Asset)
|
||||
})
|
||||
|
||||
bridge.OnTransferCompleted(func(event *TransferEvent) {
|
||||
fmt.Printf("Transfer completed: %s\n", event.ID)
|
||||
fmt.Printf("Destination tx: %s\n", event.DestTxHash)
|
||||
})
|
||||
|
||||
bridge.OnTransferFailed(func(event *TransferEvent) {
|
||||
fmt.Printf("Transfer failed: %s\n", event.ID)
|
||||
fmt.Printf("Reason: %s\n", event.Error)
|
||||
})
|
||||
```
|
||||
|
||||
## SDK Integration
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
import { LuxBridge } from '@luxfi/bridge-sdk';
|
||||
|
||||
const bridge = new LuxBridge({
|
||||
network: 'mainnet',
|
||||
});
|
||||
|
||||
// Bridge ETH to Lux
|
||||
const transfer = await bridge.transfer({
|
||||
sourceChain: 'ethereum',
|
||||
asset: 'ETH',
|
||||
amount: '1.0',
|
||||
recipient: 'lux1...',
|
||||
});
|
||||
|
||||
// Wait for completion
|
||||
await transfer.wait();
|
||||
console.log('Transfer complete!');
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
from luxfi_bridge import LuxBridge
|
||||
|
||||
bridge = LuxBridge(network='mainnet')
|
||||
|
||||
# Bridge ETH to Lux
|
||||
transfer = bridge.transfer(
|
||||
source_chain='ethereum',
|
||||
asset='ETH',
|
||||
amount='1.0',
|
||||
recipient='lux1...'
|
||||
)
|
||||
|
||||
# Wait for completion
|
||||
transfer.wait()
|
||||
print('Transfer complete!')
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Transfer Stuck
|
||||
|
||||
If transfer is stuck in "confirming" state:
|
||||
|
||||
1. Check source chain confirmations
|
||||
2. Verify bridge validators are online
|
||||
3. Contact support with transfer ID
|
||||
|
||||
### Insufficient Balance
|
||||
|
||||
```go
|
||||
// Check bridge liquidity before transfer
|
||||
liquidity, err := bridge.GetLiquidity(ctx, "ethereum", "ETH")
|
||||
|
||||
if liquidity.Available < transferAmount {
|
||||
fmt.Printf("Insufficient liquidity: %s available\n", liquidity.Available)
|
||||
}
|
||||
```
|
||||
|
||||
### Wrong Network
|
||||
|
||||
Always verify network before signing:
|
||||
|
||||
```go
|
||||
// Verify chain ID
|
||||
chainInfo, err := bridge.GetChainInfo(ctx, "ethereum")
|
||||
|
||||
if chainInfo.ChainID != 1 {
|
||||
return fmt.Errorf("wrong network: expected mainnet")
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,387 @@
|
||||
---
|
||||
title: Consensus
|
||||
description: DAG-based consensus with 1ms finality and quantum-resistant signatures
|
||||
---
|
||||
|
||||
# Consensus Layer
|
||||
|
||||
LX DEX uses a custom DAG-based consensus protocol designed for ultra-low latency trading.
|
||||
|
||||
## Overview
|
||||
|
||||
The consensus layer provides:
|
||||
- **1ms block finality** for instant trade settlement
|
||||
- **DAG structure** for parallel block processing
|
||||
- **K=3 validator threshold** for Byzantine fault tolerance
|
||||
- **Quantum-resistant signatures** for future-proof security
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
+----------------------------------------------------------+
|
||||
| DAG Consensus Layer |
|
||||
+----------------------------------------------------------+
|
||||
| |
|
||||
| Block A |
|
||||
| | |
|
||||
| +-----> Block C |
|
||||
| | | |
|
||||
| Block B ------+-----> Block D |
|
||||
| | | |
|
||||
| +-------------------> Block E |
|
||||
| |
|
||||
| [Parallel Processing] [Fast Finality] [No Forks] |
|
||||
+----------------------------------------------------------+
|
||||
```
|
||||
|
||||
## Consensus Protocol
|
||||
|
||||
### FPC (Fast Probabilistic Consensus)
|
||||
|
||||
The protocol uses optimistic confirmation with fallback to Byzantine agreement:
|
||||
|
||||
```go
|
||||
type ConsensusEngine struct {
|
||||
K int // Validator threshold (default: 3)
|
||||
Alpha float64 // Confidence threshold (default: 0.8)
|
||||
BlockTime time.Duration // Target block time (default: 1ms)
|
||||
Validators []Validator // Active validator set
|
||||
}
|
||||
|
||||
func (c *ConsensusEngine) ProposeBlock(block *Block) error {
|
||||
// 1. Broadcast to validators
|
||||
// 2. Collect K signatures
|
||||
// 3. Finalize when alpha threshold met
|
||||
}
|
||||
```
|
||||
|
||||
### Block Structure
|
||||
|
||||
```go
|
||||
type Block struct {
|
||||
Header BlockHeader
|
||||
Txs []Transaction
|
||||
Signature BLSSignature // Aggregate validator signatures
|
||||
}
|
||||
|
||||
type BlockHeader struct {
|
||||
Height uint64
|
||||
Parents []BlockHash // Multiple parents (DAG)
|
||||
StateRoot Hash
|
||||
TxRoot Hash
|
||||
Timestamp int64
|
||||
Proposer ValidatorID
|
||||
}
|
||||
```
|
||||
|
||||
### Finality
|
||||
|
||||
Blocks achieve finality when:
|
||||
1. K validators have signed
|
||||
2. Cumulative weight exceeds threshold
|
||||
3. No conflicting blocks exist
|
||||
|
||||
```go
|
||||
func (c *ConsensusEngine) CheckFinality(block *Block) bool {
|
||||
signatures := c.GetBlockSignatures(block.Hash)
|
||||
|
||||
// Need K signatures
|
||||
if len(signatures) < c.K {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check cumulative stake weight
|
||||
weight := c.CalculateWeight(signatures)
|
||||
return weight >= c.Alpha
|
||||
}
|
||||
```
|
||||
|
||||
## Validator Network
|
||||
|
||||
### Validator Requirements
|
||||
|
||||
| Requirement | Minimum |
|
||||
|-------------|---------|
|
||||
| Stake | 100,000 LUX |
|
||||
| Uptime | 99.9% |
|
||||
| Network | 1 Gbps |
|
||||
| Hardware | HSM support |
|
||||
|
||||
### Registration
|
||||
|
||||
```go
|
||||
// Register as validator
|
||||
result, err := consensus.RegisterValidator(ctx, &ValidatorParams{
|
||||
Stake: "100000.0",
|
||||
PublicKey: bls.PublicKey,
|
||||
Endpoint: "validator.example.com:5000",
|
||||
})
|
||||
|
||||
fmt.Printf("Validator ID: %s\n", result.ValidatorID)
|
||||
fmt.Printf("Active from block: %d\n", result.ActiveHeight)
|
||||
```
|
||||
|
||||
### Validator Set
|
||||
|
||||
```go
|
||||
// Get current validators
|
||||
validators, err := consensus.GetValidators(ctx)
|
||||
|
||||
for _, v := range validators {
|
||||
fmt.Printf("Validator: %s\n", v.ID)
|
||||
fmt.Printf(" Stake: %s LUX\n", v.Stake)
|
||||
fmt.Printf(" Uptime: %.2f%%\n", v.Uptime)
|
||||
fmt.Printf(" Blocks proposed: %d\n", v.BlocksProposed)
|
||||
}
|
||||
```
|
||||
|
||||
## Block Production
|
||||
|
||||
### Proposer Selection
|
||||
|
||||
Deterministic selection based on stake-weighted random:
|
||||
|
||||
```go
|
||||
func (c *ConsensusEngine) SelectProposer(height uint64) ValidatorID {
|
||||
seed := hash(height, c.GetEpochSeed())
|
||||
|
||||
totalStake := c.TotalStake()
|
||||
point := seed % totalStake
|
||||
|
||||
cumulative := uint64(0)
|
||||
for _, v := range c.Validators {
|
||||
cumulative += v.Stake
|
||||
if cumulative > point {
|
||||
return v.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Block Creation
|
||||
|
||||
```go
|
||||
// Propose new block
|
||||
block, err := consensus.ProposeBlock(ctx, &BlockParams{
|
||||
Transactions: pendingTxs,
|
||||
MaxSize: 1_000_000, // 1MB max
|
||||
})
|
||||
|
||||
// Wait for finality
|
||||
finalized := <-consensus.WaitForFinality(block.Hash)
|
||||
fmt.Printf("Block finalized: %s\n", finalized.Hash)
|
||||
```
|
||||
|
||||
## Transaction Ordering
|
||||
|
||||
### Deterministic Ordering
|
||||
|
||||
Transactions within a block are ordered by:
|
||||
1. Priority fee (highest first)
|
||||
2. Nonce (for same sender)
|
||||
3. Hash (tiebreaker)
|
||||
|
||||
```go
|
||||
func OrderTransactions(txs []Transaction) []Transaction {
|
||||
sort.Slice(txs, func(i, j int) bool {
|
||||
// Priority fee
|
||||
if txs[i].PriorityFee != txs[j].PriorityFee {
|
||||
return txs[i].PriorityFee > txs[j].PriorityFee
|
||||
}
|
||||
// Same sender: by nonce
|
||||
if txs[i].From == txs[j].From {
|
||||
return txs[i].Nonce < txs[j].Nonce
|
||||
}
|
||||
// Tiebreaker: hash
|
||||
return txs[i].Hash < txs[j].Hash
|
||||
})
|
||||
return txs
|
||||
}
|
||||
```
|
||||
|
||||
### MEV Protection
|
||||
|
||||
Front-running protection through:
|
||||
- Encrypted mempool
|
||||
- Fair ordering based on timestamp
|
||||
- Batch auctions for large orders
|
||||
|
||||
## Cryptography
|
||||
|
||||
### BLS Signatures
|
||||
|
||||
Aggregate signatures for efficient verification:
|
||||
|
||||
```go
|
||||
// Sign block
|
||||
sig, err := bls.Sign(privateKey, block.Hash)
|
||||
|
||||
// Aggregate signatures
|
||||
aggSig := bls.AggregateSignatures(signatures)
|
||||
|
||||
// Verify aggregate
|
||||
valid := bls.VerifyAggregate(
|
||||
publicKeys,
|
||||
[][]byte{block.Hash},
|
||||
aggSig,
|
||||
)
|
||||
```
|
||||
|
||||
### Quantum Resistance
|
||||
|
||||
Post-quantum signature support (Dilithium):
|
||||
|
||||
```go
|
||||
// Generate quantum-resistant keypair
|
||||
pub, priv, err := pqcrypto.GenerateKeyPair(pqcrypto.Dilithium3)
|
||||
|
||||
// Sign with quantum-resistant signature
|
||||
sig, err := pqcrypto.Sign(priv, message)
|
||||
|
||||
// Verify
|
||||
valid := pqcrypto.Verify(pub, message, sig)
|
||||
```
|
||||
|
||||
## Network Protocol
|
||||
|
||||
### QZMQ (Quantum-Secure ZeroMQ)
|
||||
|
||||
Secure messaging between validators:
|
||||
|
||||
```go
|
||||
// QZMQ configuration
|
||||
type QZMQConfig struct {
|
||||
Endpoints []string
|
||||
KeyPair *pqcrypto.KeyPair
|
||||
EncryptionMode EncryptionMode // Kyber for key exchange
|
||||
SignatureMode SignatureMode // Dilithium for signing
|
||||
}
|
||||
|
||||
// Send message to validators
|
||||
err := qzmq.Broadcast(ctx, &Message{
|
||||
Type: MessageTypeBlock,
|
||||
Payload: block.Encode(),
|
||||
})
|
||||
```
|
||||
|
||||
### Peer Discovery
|
||||
|
||||
```go
|
||||
// Discover peers
|
||||
peers, err := consensus.DiscoverPeers(ctx)
|
||||
|
||||
for _, peer := range peers {
|
||||
fmt.Printf("Peer: %s @ %s\n", peer.ID, peer.Endpoint)
|
||||
}
|
||||
```
|
||||
|
||||
## State Machine
|
||||
|
||||
### State Transitions
|
||||
|
||||
```go
|
||||
type StateMachine struct {
|
||||
State State
|
||||
Height uint64
|
||||
StateRoot Hash
|
||||
}
|
||||
|
||||
func (sm *StateMachine) Apply(block *Block) error {
|
||||
for _, tx := range block.Txs {
|
||||
if err := sm.ExecuteTx(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
sm.Height = block.Header.Height
|
||||
sm.StateRoot = sm.ComputeStateRoot()
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
### Checkpoints
|
||||
|
||||
```go
|
||||
// Create state checkpoint
|
||||
checkpoint, err := consensus.CreateCheckpoint(ctx)
|
||||
|
||||
fmt.Printf("Checkpoint height: %d\n", checkpoint.Height)
|
||||
fmt.Printf("State root: %s\n", checkpoint.StateRoot)
|
||||
|
||||
// Restore from checkpoint
|
||||
err = consensus.RestoreCheckpoint(ctx, checkpoint)
|
||||
```
|
||||
|
||||
## Monitoring
|
||||
|
||||
### Metrics
|
||||
|
||||
```go
|
||||
// Consensus metrics
|
||||
type ConsensusMetrics struct {
|
||||
BlocksProposed int64
|
||||
BlocksFinalized int64
|
||||
AvgFinalityTime time.Duration
|
||||
ValidatorUptime float64
|
||||
MissedBlocks int64
|
||||
}
|
||||
|
||||
metrics, err := consensus.GetMetrics(ctx)
|
||||
fmt.Printf("Avg finality: %v\n", metrics.AvgFinalityTime)
|
||||
```
|
||||
|
||||
### Health Checks
|
||||
|
||||
```go
|
||||
// Check consensus health
|
||||
health, err := consensus.Health(ctx)
|
||||
|
||||
fmt.Printf("Status: %s\n", health.Status)
|
||||
fmt.Printf("Connected validators: %d/%d\n",
|
||||
health.ConnectedValidators, health.TotalValidators)
|
||||
fmt.Printf("Sync status: %s\n", health.SyncStatus)
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### ProposeBlock
|
||||
|
||||
```go
|
||||
func (c *Consensus) ProposeBlock(ctx context.Context, params *BlockParams) (*Block, error)
|
||||
```
|
||||
|
||||
### GetBlock
|
||||
|
||||
```go
|
||||
func (c *Consensus) GetBlock(ctx context.Context, hash string) (*Block, error)
|
||||
```
|
||||
|
||||
### GetValidators
|
||||
|
||||
```go
|
||||
func (c *Consensus) GetValidators(ctx context.Context) ([]*Validator, error)
|
||||
```
|
||||
|
||||
### SubscribeBlocks
|
||||
|
||||
```go
|
||||
func (c *Consensus) SubscribeBlocks(ctx context.Context) (<-chan *Block, error)
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```go
|
||||
// Listen for consensus events
|
||||
consensus.OnBlockProposed(func(block *Block) {
|
||||
fmt.Printf("Block proposed: %d\n", block.Header.Height)
|
||||
})
|
||||
|
||||
consensus.OnBlockFinalized(func(block *Block) {
|
||||
fmt.Printf("Block finalized: %d (took %v)\n",
|
||||
block.Header.Height, block.FinalityTime)
|
||||
})
|
||||
|
||||
consensus.OnValidatorJoined(func(v *Validator) {
|
||||
fmt.Printf("New validator: %s\n", v.ID)
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,390 @@
|
||||
---
|
||||
title: Development Guide
|
||||
description: Build, test, and contribute to LX DEX
|
||||
---
|
||||
|
||||
# LX DEX Development Guide
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Go 1.21+
|
||||
- Docker & Docker Compose
|
||||
- Make
|
||||
- Git
|
||||
|
||||
### Initial Setup
|
||||
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone https://github.com/luxfi/dex.git
|
||||
cd dex
|
||||
|
||||
# Install dependencies
|
||||
go mod download
|
||||
|
||||
# Run tests to verify setup
|
||||
make test
|
||||
|
||||
# Build the project
|
||||
make build
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
dex/
|
||||
├── pkg/ # Core packages
|
||||
│ ├── lx/ # Trading engine
|
||||
│ │ ├── orderbook.go # Order matching engine
|
||||
│ │ ├── margin.go # Margin trading
|
||||
│ │ ├── vaults.go # DeFi vaults
|
||||
│ │ └── bridge.go # Cross-chain bridge
|
||||
│ ├── api/ # API servers
|
||||
│ ├── consensus/ # DAG consensus
|
||||
│ └── client/ # Client libraries
|
||||
├── cmd/ # Executables
|
||||
├── examples/ # Example code
|
||||
├── test/ # Test suites
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ └── e2e/ # End-to-end tests
|
||||
├── sdk/ # Language SDKs
|
||||
├── docs/ # Documentation
|
||||
└── .github/workflows/ # CI/CD pipelines
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### 1. Create Feature Branch
|
||||
|
||||
```bash
|
||||
git checkout -b feature/your-feature-name
|
||||
```
|
||||
|
||||
### 2. Make Changes
|
||||
|
||||
Follow the coding standards:
|
||||
- Use meaningful variable names
|
||||
- Add comments for complex logic
|
||||
- Follow Go conventions
|
||||
- Keep functions small and focused
|
||||
|
||||
### 3. Write Tests
|
||||
|
||||
Every new feature must include tests:
|
||||
|
||||
```go
|
||||
func TestYourFeature(t *testing.T) {
|
||||
// Arrange
|
||||
setup := setupTest()
|
||||
|
||||
// Act
|
||||
result := YourFeature(input)
|
||||
|
||||
// Assert
|
||||
assert.Equal(t, expected, result)
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Run Tests Locally
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
make test
|
||||
|
||||
# Run specific test
|
||||
go test -run TestOrderBook ./pkg/lx/
|
||||
|
||||
# Run with coverage
|
||||
go test -cover ./pkg/lx/
|
||||
```
|
||||
|
||||
### 5. Commit Changes
|
||||
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "feat: add new feature
|
||||
|
||||
- Detailed description
|
||||
- What was changed
|
||||
- Why it was changed"
|
||||
```
|
||||
|
||||
### 6. Push and Create PR
|
||||
|
||||
```bash
|
||||
git push origin feature/your-feature-name
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit Tests
|
||||
|
||||
```bash
|
||||
# Run unit tests
|
||||
go test ./pkg/...
|
||||
|
||||
# With coverage
|
||||
go test -cover ./pkg/...
|
||||
|
||||
# Generate coverage report
|
||||
go test -coverprofile=coverage.out ./pkg/...
|
||||
go tool cover -html=coverage.out
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
```bash
|
||||
# Run integration tests
|
||||
go test ./test/integration/...
|
||||
|
||||
# Skip in CI (long-running)
|
||||
go test -short ./test/integration/...
|
||||
```
|
||||
|
||||
### Benchmarks
|
||||
|
||||
```bash
|
||||
# Run all benchmarks
|
||||
make bench
|
||||
|
||||
# Run specific benchmark
|
||||
go test -bench=BenchmarkOrderBook -benchtime=10s ./pkg/lx/
|
||||
|
||||
# With memory profiling
|
||||
go test -bench=. -benchmem ./pkg/lx/
|
||||
```
|
||||
|
||||
### Load Testing
|
||||
|
||||
```bash
|
||||
# Run load test
|
||||
go run cmd/stress-test/main.go
|
||||
|
||||
# Monitor performance
|
||||
watch -n 1 'go run cmd/monitor/main.go'
|
||||
```
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Profiling
|
||||
|
||||
```bash
|
||||
# CPU profiling
|
||||
go test -cpuprofile=cpu.prof -bench=. ./pkg/lx/
|
||||
go tool pprof cpu.prof
|
||||
|
||||
# Memory profiling
|
||||
go test -memprofile=mem.prof -bench=. ./pkg/lx/
|
||||
go tool pprof mem.prof
|
||||
|
||||
# Trace execution
|
||||
go test -trace=trace.out ./pkg/lx/
|
||||
go tool trace trace.out
|
||||
```
|
||||
|
||||
### Optimization Tips
|
||||
|
||||
1. **Use sync.Pool** for frequently allocated objects
|
||||
2. **Minimize allocations** in hot paths
|
||||
3. **Use atomic operations** instead of mutexes where possible
|
||||
4. **Profile before optimizing** - measure, don't guess
|
||||
5. **Batch operations** when possible
|
||||
|
||||
### Example Optimization
|
||||
|
||||
```go
|
||||
// Before: Allocates on every call
|
||||
func processOrder(order Order) {
|
||||
result := &Result{} // Allocation
|
||||
// process...
|
||||
}
|
||||
|
||||
// After: Reuse with sync.Pool
|
||||
var resultPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &Result{}
|
||||
},
|
||||
}
|
||||
|
||||
func processOrder(order Order) {
|
||||
result := resultPool.Get().(*Result)
|
||||
defer resultPool.Put(result)
|
||||
result.Reset() // Clear previous data
|
||||
// process...
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
### Code Style
|
||||
|
||||
- Run `gofmt` before committing
|
||||
- Use `golangci-lint` for linting
|
||||
- Follow [Effective Go](https://golang.org/doc/effective_go.html)
|
||||
|
||||
```bash
|
||||
# Format code
|
||||
make fmt
|
||||
|
||||
# Run linters
|
||||
make lint
|
||||
|
||||
# Run all checks
|
||||
make check
|
||||
```
|
||||
|
||||
### Commit Convention
|
||||
|
||||
Follow [Conventional Commits](https://www.conventionalcommits.org/):
|
||||
- `feat:` New feature
|
||||
- `fix:` Bug fix
|
||||
- `docs:` Documentation
|
||||
- `test:` Testing
|
||||
- `perf:` Performance improvement
|
||||
- `refactor:` Code refactoring
|
||||
- `chore:` Maintenance
|
||||
|
||||
### Pull Request Process
|
||||
|
||||
1. Update documentation
|
||||
2. Add/update tests
|
||||
3. Ensure CI passes
|
||||
4. Request review
|
||||
5. Address feedback
|
||||
6. Squash commits if needed
|
||||
|
||||
### Review Checklist
|
||||
|
||||
- [ ] Tests pass
|
||||
- [ ] Documentation updated
|
||||
- [ ] No security issues
|
||||
- [ ] Performance impact considered
|
||||
- [ ] Breaking changes documented
|
||||
- [ ] Error handling appropriate
|
||||
|
||||
## Debugging
|
||||
|
||||
### Local Debugging
|
||||
|
||||
```bash
|
||||
# Run with debug logs
|
||||
LOG_LEVEL=debug go run cmd/dex-server/main.go
|
||||
|
||||
# Use Delve debugger
|
||||
dlv debug cmd/dex-server/main.go
|
||||
|
||||
# Attach to running process
|
||||
dlv attach <pid>
|
||||
```
|
||||
|
||||
### Remote Debugging
|
||||
|
||||
```bash
|
||||
# Start with debug server
|
||||
dlv debug --headless --listen=:2345 cmd/dex-server/main.go
|
||||
|
||||
# Connect from IDE or CLI
|
||||
dlv connect :2345
|
||||
```
|
||||
|
||||
## Performance Metrics
|
||||
|
||||
### Key Metrics to Monitor
|
||||
|
||||
- **Latency**: Order matching time
|
||||
- **Throughput**: Orders/second
|
||||
- **Memory**: Heap usage and GC pressure
|
||||
- **Goroutines**: Active count and leaks
|
||||
- **Network**: Message rate and bandwidth
|
||||
|
||||
### Monitoring Tools
|
||||
|
||||
```bash
|
||||
# Built-in metrics
|
||||
curl http://localhost:9090/metrics
|
||||
|
||||
# Prometheus
|
||||
docker-compose up prometheus grafana
|
||||
|
||||
# Custom dashboard
|
||||
go run cmd/monitor/main.go
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
# Single node
|
||||
make run
|
||||
|
||||
# Multi-node cluster
|
||||
make run-cluster
|
||||
|
||||
# With Docker
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
### Production
|
||||
|
||||
```bash
|
||||
# Build production binary
|
||||
CGO_ENABLED=0 make build
|
||||
|
||||
# Build Docker image
|
||||
docker build -t lux-dex:latest .
|
||||
|
||||
# Deploy to Kubernetes
|
||||
kubectl apply -f k8s/
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**1. Tests timing out**
|
||||
```bash
|
||||
# Increase timeout
|
||||
go test -timeout=30s ./pkg/lx/
|
||||
|
||||
# Run in short mode
|
||||
go test -short ./pkg/lx/
|
||||
```
|
||||
|
||||
**2. Memory leaks**
|
||||
```bash
|
||||
# Check for goroutine leaks
|
||||
go test -run=. -count=1 ./pkg/lx/
|
||||
|
||||
# Profile memory
|
||||
go tool pprof http://localhost:6060/debug/pprof/heap
|
||||
```
|
||||
|
||||
**3. Race conditions**
|
||||
```bash
|
||||
# Run with race detector
|
||||
go test -race ./pkg/lx/
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
### Documentation
|
||||
|
||||
- [Go Documentation](https://go.dev/doc/)
|
||||
- [Effective Go](https://golang.org/doc/effective_go.html)
|
||||
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
|
||||
|
||||
### Tools
|
||||
|
||||
- [Delve Debugger](https://github.com/go-delve/delve)
|
||||
- [pprof](https://github.com/google/pprof)
|
||||
- [golangci-lint](https://golangci-lint.run/)
|
||||
|
||||
### Community
|
||||
|
||||
- Discord: [discord.gg/luxfi](https://discord.gg/luxfi)
|
||||
- GitHub Issues: [github.com/luxfi/dex/issues](https://github.com/luxfi/dex/issues)
|
||||
- Twitter: [@luxfi](https://twitter.com/luxfi)
|
||||
@@ -0,0 +1,334 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Quick start guide for LX DEX - installation, setup, and your first trade
|
||||
---
|
||||
|
||||
# Getting Started with LX DEX
|
||||
|
||||
Get up and running with LX DEX in minutes.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Go 1.21+ (for building from source)
|
||||
- Git
|
||||
- Docker (optional, for containerized deployment)
|
||||
|
||||
## Installation
|
||||
|
||||
### From Source
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/luxfi/dex.git
|
||||
cd dex
|
||||
|
||||
# Build the project
|
||||
make build
|
||||
|
||||
# Verify installation
|
||||
./bin/luxd --version
|
||||
```
|
||||
|
||||
### From Release
|
||||
|
||||
```bash
|
||||
# Download latest release
|
||||
curl -L https://github.com/luxfi/dex/releases/latest/download/lx-dex-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m) -o lx-dex
|
||||
|
||||
# Make executable
|
||||
chmod +x lx-dex
|
||||
|
||||
# Run
|
||||
./lx-dex
|
||||
```
|
||||
|
||||
### With Docker
|
||||
|
||||
```bash
|
||||
# Pull the image
|
||||
docker pull luxfi/dex:latest
|
||||
|
||||
# Run the container
|
||||
docker run -p 8080:8080 -p 8081:8081 -p 50051:50051 luxfi/dex:latest
|
||||
```
|
||||
|
||||
## Start the Node
|
||||
|
||||
### Single Node (Development)
|
||||
|
||||
```bash
|
||||
# Start with default configuration
|
||||
./bin/luxd
|
||||
|
||||
# Or with custom config
|
||||
./bin/luxd --config config.yaml
|
||||
```
|
||||
|
||||
### Multi-Node Cluster
|
||||
|
||||
```bash
|
||||
# Start a 3-node cluster
|
||||
make run-cluster
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
# Start all services
|
||||
docker-compose up -d
|
||||
|
||||
# View logs
|
||||
docker-compose logs -f
|
||||
```
|
||||
|
||||
## Verify Installation
|
||||
|
||||
### Check Node Health
|
||||
|
||||
```bash
|
||||
curl http://localhost:8080/health
|
||||
```
|
||||
|
||||
Expected response:
|
||||
```json
|
||||
{"status": "healthy", "version": "1.0.0"}
|
||||
```
|
||||
|
||||
### Test JSON-RPC
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"jsonrpc": "2.0", "method": "lx_ping", "params": {}, "id": 1}'
|
||||
```
|
||||
|
||||
Expected response:
|
||||
```json
|
||||
{"jsonrpc": "2.0", "result": {"pong": true}, "id": 1}
|
||||
```
|
||||
|
||||
## Your First Trade
|
||||
|
||||
### Using curl
|
||||
|
||||
```bash
|
||||
# Place a buy order
|
||||
curl -X POST http://localhost:8080/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "lx_placeOrder",
|
||||
"params": {
|
||||
"symbol": "BTC-USD",
|
||||
"type": 0,
|
||||
"side": 0,
|
||||
"price": 50000,
|
||||
"size": 1.0,
|
||||
"userID": "trader1"
|
||||
},
|
||||
"id": 1
|
||||
}'
|
||||
```
|
||||
|
||||
### Using TypeScript SDK
|
||||
|
||||
```typescript
|
||||
import { LXDexClient } from '@luxfi/dex-sdk';
|
||||
|
||||
const client = new LXDexClient({
|
||||
jsonRpcUrl: 'http://localhost:8080/rpc',
|
||||
});
|
||||
|
||||
// Place a buy order
|
||||
const order = await client.placeOrder({
|
||||
symbol: 'BTC-USD',
|
||||
type: 'limit',
|
||||
side: 'buy',
|
||||
price: 50000,
|
||||
size: 1.0
|
||||
});
|
||||
|
||||
console.log('Order ID:', order.orderId);
|
||||
```
|
||||
|
||||
### Using Python SDK
|
||||
|
||||
```python
|
||||
from luxfi_dex import LXDexClient
|
||||
|
||||
client = LXDexClient(
|
||||
json_rpc_url='http://localhost:8080/rpc'
|
||||
)
|
||||
|
||||
# Place a buy order
|
||||
order = client.place_order(
|
||||
symbol='BTC-USD',
|
||||
order_type='limit',
|
||||
side='buy',
|
||||
price=50000,
|
||||
size=1.0
|
||||
)
|
||||
|
||||
print(f'Order ID: {order.order_id}')
|
||||
```
|
||||
|
||||
### Using Go SDK
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/luxfi/dex/sdk/go/lxdex"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := lxdex.NewClient(
|
||||
lxdex.WithJSONRPC("http://localhost:8080/rpc"),
|
||||
)
|
||||
|
||||
order, _ := client.PlaceOrder(context.Background(), &lxdex.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: lxdex.OrderTypeLimit,
|
||||
Side: lxdex.Buy,
|
||||
Price: 50000,
|
||||
Size: 1.0,
|
||||
})
|
||||
|
||||
fmt.Printf("Order ID: %s\n", order.OrderID)
|
||||
}
|
||||
```
|
||||
|
||||
## View Order Book
|
||||
|
||||
### Using curl
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/rpc \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "lx_getOrderBook",
|
||||
"params": {"depth": 10},
|
||||
"id": 1
|
||||
}'
|
||||
```
|
||||
|
||||
### Using WebSocket
|
||||
|
||||
```javascript
|
||||
const ws = new WebSocket('ws://localhost:8081');
|
||||
|
||||
ws.onopen = () => {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'subscribe',
|
||||
channel: 'orderbook',
|
||||
symbol: 'BTC-USD',
|
||||
depth: 10
|
||||
}));
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
console.log('Order book:', data);
|
||||
};
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Description | Default |
|
||||
|----------|-------------|---------|
|
||||
| `LX_RPC_PORT` | JSON-RPC port | 8080 |
|
||||
| `LX_WS_PORT` | WebSocket port | 8081 |
|
||||
| `LX_GRPC_PORT` | gRPC port | 50051 |
|
||||
| `LX_P2P_PORT` | P2P networking port | 5000 |
|
||||
| `LX_LOG_LEVEL` | Log level (debug, info, warn, error) | info |
|
||||
| `LX_DATA_DIR` | Data directory | ./data |
|
||||
|
||||
### Configuration File
|
||||
|
||||
```yaml
|
||||
# config.yaml
|
||||
server:
|
||||
rpc_port: 8080
|
||||
ws_port: 8081
|
||||
grpc_port: 50051
|
||||
|
||||
consensus:
|
||||
validators: 3
|
||||
block_time: 1ms
|
||||
|
||||
storage:
|
||||
path: ./data
|
||||
engine: badger
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: json
|
||||
```
|
||||
|
||||
## Default Ports
|
||||
|
||||
| Service | Port | Protocol |
|
||||
|---------|------|----------|
|
||||
| JSON-RPC | 8080 | HTTP |
|
||||
| WebSocket | 8081 | WS |
|
||||
| gRPC | 50051 | HTTP/2 |
|
||||
| P2P | 5000 | TCP |
|
||||
| Metrics | 9090 | HTTP |
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [API Reference](/docs/api) - Complete API documentation
|
||||
- [Architecture](/docs/architecture) - System design overview
|
||||
- [SDK Guide](/docs/sdk) - Client library integration
|
||||
- [Development](/docs/development) - Build and contribute
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Port Already in Use
|
||||
|
||||
```bash
|
||||
# Find process using port
|
||||
lsof -i :8080
|
||||
|
||||
# Kill process
|
||||
kill -9 <PID>
|
||||
```
|
||||
|
||||
### Connection Refused
|
||||
|
||||
Check if the node is running:
|
||||
```bash
|
||||
ps aux | grep luxd
|
||||
```
|
||||
|
||||
Check firewall rules:
|
||||
```bash
|
||||
# macOS
|
||||
sudo pfctl -s rules
|
||||
|
||||
# Linux
|
||||
sudo iptables -L
|
||||
```
|
||||
|
||||
### Permission Denied
|
||||
|
||||
```bash
|
||||
# Fix binary permissions
|
||||
chmod +x ./bin/luxd
|
||||
|
||||
# Fix data directory permissions
|
||||
chmod 755 ./data
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
- Documentation: https://dex.lux.network
|
||||
- GitHub Issues: https://github.com/luxfi/dex/issues
|
||||
- Discord: https://discord.gg/luxfi
|
||||
- Email: [email protected]
|
||||
@@ -15,13 +15,13 @@ LX DEX is a planet-scale, fully on-chain decentralized exchange built on Lux Net
|
||||
|
||||
| Metric | Target | Achieved | Status |
|
||||
|--------|--------|----------|---------|
|
||||
| Order Latency (GPU) | <1μs | **2 ns** | ✅ 500x better |
|
||||
| Order Latency (CPU) | <1μs | **487 ns** | ✅ 2x better |
|
||||
| Throughput (CPU) | 1M/sec | **1.01M/sec** | ✅ Exceeded |
|
||||
| Throughput (GPU) | 100M/sec | **434M/sec** | ✅ 4.34x |
|
||||
| Test Coverage | 100% | **100%** | ✅ Complete |
|
||||
| Order Latency (GPU) | Sub-microsecond | **2 ns** | 500x better |
|
||||
| Order Latency (CPU) | Sub-microsecond | **487 ns** | 2x better |
|
||||
| Throughput (CPU) | 1M/sec | **1.01M/sec** | Exceeded |
|
||||
| Throughput (GPU) | 100M/sec | **434M/sec** | 4.34x |
|
||||
| Test Coverage | 100% | **100%** | Complete |
|
||||
|
||||
*With MLX GPU acceleration on Apple Silicon M2 Ultra
|
||||
*With MLX GPU acceleration on Apple Silicon M2 Ultra*
|
||||
|
||||
## Features
|
||||
|
||||
@@ -223,7 +223,7 @@ go test -bench=BenchmarkGPU -benchmem ./pkg/lx/
|
||||
**Latest Results** (Apple M2 Ultra):
|
||||
- CPU: 1,013,824 orders/sec
|
||||
- GPU/MLX: 434,782,609 orders/sec
|
||||
- Memory: <1GB for 100K orders
|
||||
- Memory: Under 1GB for 100K orders
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
title: Lending Protocol
|
||||
description: Decentralized lending and borrowing with margin trading support
|
||||
---
|
||||
|
||||
# Lending Protocol
|
||||
|
||||
LX DEX includes a decentralized lending protocol for margin trading and yield generation.
|
||||
|
||||
## Overview
|
||||
|
||||
The lending protocol enables:
|
||||
- **Overcollateralized borrowing** with liquidation protection
|
||||
- **Variable interest rates** based on utilization
|
||||
- **Margin trading** integration
|
||||
- **Flash loans** for atomic arbitrage
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
+----------------------------------------------------------+
|
||||
| Lending Protocol |
|
||||
+----------------------------------------------------------+
|
||||
| |
|
||||
| [Supply Pool] <---> [Interest Rate Model] <---> [Borrow] |
|
||||
| | | |
|
||||
| v v |
|
||||
| [Collateral] [Debt Position]|
|
||||
| | | |
|
||||
| +-------------> [Liquidation Engine] <--------+ |
|
||||
| | |
|
||||
| v |
|
||||
| [Insurance Fund] |
|
||||
+----------------------------------------------------------+
|
||||
```
|
||||
|
||||
## Supply Assets
|
||||
|
||||
Deposit assets to earn yield:
|
||||
|
||||
```go
|
||||
// Supply USDT to earn interest
|
||||
result, err := lending.Supply(ctx, &SupplyParams{
|
||||
Asset: "USDT",
|
||||
Amount: "10000.00",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
fmt.Printf("Supplied: %s USDT\n", result.Amount)
|
||||
fmt.Printf("Shares received: %s\n", result.Shares)
|
||||
fmt.Printf("Current APY: %s%%\n", result.CurrentAPY)
|
||||
```
|
||||
|
||||
### Interest Accrual
|
||||
|
||||
Interest accrues continuously:
|
||||
|
||||
```go
|
||||
// Check accrued interest
|
||||
position, err := lending.GetSupplyPosition(ctx, "user123", "USDT")
|
||||
|
||||
fmt.Printf("Principal: %s\n", position.Principal)
|
||||
fmt.Printf("Accrued interest: %s\n", position.AccruedInterest)
|
||||
fmt.Printf("Total value: %s\n", position.TotalValue)
|
||||
```
|
||||
|
||||
## Borrow Assets
|
||||
|
||||
Borrow against collateral:
|
||||
|
||||
```go
|
||||
// Deposit collateral
|
||||
collateral, err := lending.DepositCollateral(ctx, &CollateralParams{
|
||||
Asset: "BTC",
|
||||
Amount: "1.0",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
// Borrow USDT
|
||||
borrow, err := lending.Borrow(ctx, &BorrowParams{
|
||||
Asset: "USDT",
|
||||
Amount: "30000.00",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
fmt.Printf("Borrowed: %s USDT\n", borrow.Amount)
|
||||
fmt.Printf("Interest rate: %s%%\n", borrow.InterestRate)
|
||||
fmt.Printf("Health factor: %s\n", borrow.HealthFactor)
|
||||
```
|
||||
|
||||
### Health Factor
|
||||
|
||||
Health factor determines liquidation risk:
|
||||
|
||||
```
|
||||
Health Factor = (Collateral Value * Collateral Factor) / Debt Value
|
||||
|
||||
> 1.0 = Safe
|
||||
< 1.0 = Liquidation eligible
|
||||
```
|
||||
|
||||
```go
|
||||
// Monitor health factor
|
||||
health, err := lending.GetHealthFactor(ctx, "user123")
|
||||
|
||||
if health.Factor < 1.2 {
|
||||
// Warning: close to liquidation
|
||||
fmt.Printf("Warning: Health factor is %s\n", health.Factor)
|
||||
}
|
||||
```
|
||||
|
||||
## Interest Rate Model
|
||||
|
||||
### Utilization-Based Rates
|
||||
|
||||
Interest rates adjust based on pool utilization:
|
||||
|
||||
```go
|
||||
// Rate model parameters
|
||||
type InterestRateModel struct {
|
||||
BaseRate string // Base borrow rate
|
||||
MultiplierRate string // Rate increase per utilization %
|
||||
JumpMultiplier string // Rate multiplier above kink
|
||||
Kink string // Utilization threshold for jump rate
|
||||
}
|
||||
|
||||
// Example: USDT pool
|
||||
usdtModel := &InterestRateModel{
|
||||
BaseRate: "0.02", // 2% base
|
||||
MultiplierRate: "0.10", // +10% at 100% utilization
|
||||
JumpMultiplier: "2.0", // 2x multiplier above kink
|
||||
Kink: "0.80", // Jump at 80% utilization
|
||||
}
|
||||
```
|
||||
|
||||
### Current Rates
|
||||
|
||||
```go
|
||||
rates, err := lending.GetMarketRates(ctx, "USDT")
|
||||
|
||||
fmt.Printf("Supply APY: %s%%\n", rates.SupplyAPY)
|
||||
fmt.Printf("Borrow APY: %s%%\n", rates.BorrowAPY)
|
||||
fmt.Printf("Utilization: %s%%\n", rates.Utilization)
|
||||
```
|
||||
|
||||
## Collateral Management
|
||||
|
||||
### Supported Collateral
|
||||
|
||||
| Asset | Collateral Factor | Liquidation Threshold |
|
||||
|-------|-------------------|----------------------|
|
||||
| BTC | 80% | 85% |
|
||||
| ETH | 75% | 80% |
|
||||
| LUX | 70% | 75% |
|
||||
| USDT | 85% | 90% |
|
||||
| USDC | 85% | 90% |
|
||||
|
||||
### Deposit Collateral
|
||||
|
||||
```go
|
||||
result, err := lending.DepositCollateral(ctx, &CollateralParams{
|
||||
Asset: "ETH",
|
||||
Amount: "10.0",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
fmt.Printf("Collateral value: $%s\n", result.ValueUSD)
|
||||
fmt.Printf("Borrowing power: $%s\n", result.BorrowingPower)
|
||||
```
|
||||
|
||||
### Withdraw Collateral
|
||||
|
||||
```go
|
||||
result, err := lending.WithdrawCollateral(ctx, &WithdrawParams{
|
||||
Asset: "ETH",
|
||||
Amount: "2.0",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
// Will fail if withdrawal would cause health factor < 1.0
|
||||
```
|
||||
|
||||
## Repay Debt
|
||||
|
||||
```go
|
||||
// Repay partial debt
|
||||
result, err := lending.Repay(ctx, &RepayParams{
|
||||
Asset: "USDT",
|
||||
Amount: "15000.00",
|
||||
UserID: "user123",
|
||||
})
|
||||
|
||||
fmt.Printf("Remaining debt: %s\n", result.RemainingDebt)
|
||||
fmt.Printf("New health factor: %s\n", result.HealthFactor)
|
||||
|
||||
// Repay all debt
|
||||
result, err = lending.RepayAll(ctx, "user123", "USDT")
|
||||
```
|
||||
|
||||
## Liquidation
|
||||
|
||||
### Liquidation Process
|
||||
|
||||
When health factor falls below 1.0:
|
||||
|
||||
```go
|
||||
// Check if position is liquidatable
|
||||
position, err := lending.GetPosition(ctx, "user123")
|
||||
|
||||
if position.HealthFactor < 1.0 {
|
||||
// Position can be liquidated
|
||||
result, err := lending.Liquidate(ctx, &LiquidateParams{
|
||||
Borrower: "user123",
|
||||
DebtAsset: "USDT",
|
||||
DebtAmount: "10000.00",
|
||||
CollatAsset: "BTC",
|
||||
})
|
||||
|
||||
fmt.Printf("Collateral received: %s BTC\n", result.CollateralReceived)
|
||||
fmt.Printf("Bonus: %s BTC\n", result.LiquidationBonus)
|
||||
}
|
||||
```
|
||||
|
||||
### Liquidation Bonus
|
||||
|
||||
Liquidators receive a bonus for clearing bad debt:
|
||||
|
||||
| Asset | Liquidation Bonus |
|
||||
|-------|------------------|
|
||||
| BTC | 5% |
|
||||
| ETH | 5% |
|
||||
| LUX | 7% |
|
||||
| Stablecoins | 3% |
|
||||
|
||||
## Flash Loans
|
||||
|
||||
Borrow without collateral for atomic operations:
|
||||
|
||||
```go
|
||||
// Flash loan for arbitrage
|
||||
err := lending.FlashLoan(ctx, &FlashLoanParams{
|
||||
Asset: "USDT",
|
||||
Amount: "1000000.00",
|
||||
Callback: func(amount string) error {
|
||||
// 1. Buy BTC on DEX A
|
||||
// 2. Sell BTC on DEX B
|
||||
// 3. Repay loan + fee
|
||||
return nil
|
||||
},
|
||||
})
|
||||
|
||||
// Fee: 0.09% of borrowed amount
|
||||
```
|
||||
|
||||
## Margin Trading Integration
|
||||
|
||||
Use borrowed funds for trading:
|
||||
|
||||
```go
|
||||
// Open margin position
|
||||
position, err := margin.OpenPosition(ctx, &MarginParams{
|
||||
Symbol: "BTC-USD",
|
||||
Side: types.Long,
|
||||
Collateral: "10000.00", // USDT collateral
|
||||
Leverage: 3, // 3x leverage
|
||||
})
|
||||
|
||||
// Position backed by lending protocol
|
||||
fmt.Printf("Position size: $%s\n", position.Size)
|
||||
fmt.Printf("Liquidation price: $%s\n", position.LiquidationPrice)
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Supply
|
||||
|
||||
```go
|
||||
func (l *Lending) Supply(ctx context.Context, params *SupplyParams) (*SupplyResult, error)
|
||||
```
|
||||
|
||||
### Withdraw
|
||||
|
||||
```go
|
||||
func (l *Lending) Withdraw(ctx context.Context, params *WithdrawParams) (*WithdrawResult, error)
|
||||
```
|
||||
|
||||
### Borrow
|
||||
|
||||
```go
|
||||
func (l *Lending) Borrow(ctx context.Context, params *BorrowParams) (*BorrowResult, error)
|
||||
```
|
||||
|
||||
### Repay
|
||||
|
||||
```go
|
||||
func (l *Lending) Repay(ctx context.Context, params *RepayParams) (*RepayResult, error)
|
||||
```
|
||||
|
||||
### GetPosition
|
||||
|
||||
```go
|
||||
func (l *Lending) GetPosition(ctx context.Context, userID string) (*Position, error)
|
||||
```
|
||||
|
||||
### GetMarketRates
|
||||
|
||||
```go
|
||||
func (l *Lending) GetMarketRates(ctx context.Context, asset string) (*MarketRates, error)
|
||||
```
|
||||
|
||||
## Risk Parameters
|
||||
|
||||
### Protocol Limits
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Max LTV | 80% |
|
||||
| Liquidation Threshold | 85% |
|
||||
| Liquidation Penalty | 5% |
|
||||
| Reserve Factor | 10% |
|
||||
| Flash Loan Fee | 0.09% |
|
||||
|
||||
### Oracle Integration
|
||||
|
||||
Prices from multiple oracles with TWAP protection:
|
||||
|
||||
```go
|
||||
oracle := lending.GetOracle()
|
||||
|
||||
price, err := oracle.GetPrice("BTC")
|
||||
fmt.Printf("BTC price: $%s\n", price.Value)
|
||||
fmt.Printf("Source: %s\n", price.Source) // Chainlink, Pyth, etc.
|
||||
fmt.Printf("Updated: %s\n", price.Timestamp)
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```go
|
||||
// Listen for lending events
|
||||
lending.OnSupply(func(event *SupplyEvent) {
|
||||
fmt.Printf("Supply: %s %s by %s\n",
|
||||
event.Amount, event.Asset, event.UserID)
|
||||
})
|
||||
|
||||
lending.OnBorrow(func(event *BorrowEvent) {
|
||||
fmt.Printf("Borrow: %s %s by %s\n",
|
||||
event.Amount, event.Asset, event.UserID)
|
||||
})
|
||||
|
||||
lending.OnLiquidation(func(event *LiquidationEvent) {
|
||||
fmt.Printf("Liquidation: %s -> %s\n",
|
||||
event.Borrower, event.Liquidator)
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"title": "LX DEX Documentation",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"index",
|
||||
"getting-started",
|
||||
"---",
|
||||
"architecture",
|
||||
"orderbook",
|
||||
"consensus",
|
||||
"---",
|
||||
"api",
|
||||
"sdk",
|
||||
"---",
|
||||
"lending",
|
||||
"bridge",
|
||||
"---",
|
||||
"development"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
---
|
||||
title: Orderbook Engine
|
||||
description: High-performance order matching engine - 434M+ orders/sec with sub-microsecond latency
|
||||
---
|
||||
|
||||
# Orderbook Engine
|
||||
|
||||
The LX DEX orderbook engine is designed for ultra-high performance trading with multiple backend options.
|
||||
|
||||
## Overview
|
||||
|
||||
The matching engine achieves:
|
||||
- **434M+ orders/sec** with GPU acceleration
|
||||
- **2ns latency** on Apple Silicon MLX
|
||||
- **487ns latency** on pure CPU
|
||||
- **Zero-copy** trade recording
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
+----------------------------------------------------------+
|
||||
| Order Flow |
|
||||
+----------------------------------------------------------+
|
||||
| Client Order |
|
||||
| | |
|
||||
| v |
|
||||
| [Validation] ---> [Risk Check] ---> [Matching Engine] |
|
||||
| | |
|
||||
| v |
|
||||
| [Order Book] |
|
||||
| / \ |
|
||||
| [Bids] [Asks] |
|
||||
| B-Tree B-Tree |
|
||||
| | |
|
||||
| v |
|
||||
| [Trade Buffer] |
|
||||
| (Circular, Lock-free)|
|
||||
+----------------------------------------------------------+
|
||||
```
|
||||
|
||||
## Order Book Structure
|
||||
|
||||
Each trading pair maintains a separate order book with optimized B-tree structures:
|
||||
|
||||
```go
|
||||
type OrderBook struct {
|
||||
Symbol string
|
||||
Bids *BTree[PriceLevel] // Sorted high to low
|
||||
Asks *BTree[PriceLevel] // Sorted low to high
|
||||
Orders map[string]*Order // O(1) order lookup
|
||||
TradeBuffer *CircularBuffer // Zero-copy trades
|
||||
}
|
||||
|
||||
type PriceLevel struct {
|
||||
Price int64 // Integer cents
|
||||
Orders []*Order // FIFO queue
|
||||
Volume int64 // Total volume at level
|
||||
}
|
||||
```
|
||||
|
||||
## Order Types
|
||||
|
||||
### Limit Order
|
||||
|
||||
Execute at specified price or better:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Limit,
|
||||
Side: types.Buy,
|
||||
Price: "50000.00",
|
||||
Size: "1.5",
|
||||
}
|
||||
book.PlaceOrder(order)
|
||||
```
|
||||
|
||||
### Market Order
|
||||
|
||||
Execute immediately at best available price:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Market,
|
||||
Side: types.Buy,
|
||||
Size: "1.0", // No price for market orders
|
||||
}
|
||||
book.PlaceOrder(order)
|
||||
```
|
||||
|
||||
### Stop Order
|
||||
|
||||
Trigger when price reaches threshold:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Stop,
|
||||
Side: types.Sell,
|
||||
StopPrice: "49000.00",
|
||||
Size: "1.0",
|
||||
}
|
||||
book.PlaceOrder(order)
|
||||
```
|
||||
|
||||
### Stop-Limit Order
|
||||
|
||||
Stop that becomes limit when triggered:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.StopLimit,
|
||||
Side: types.Sell,
|
||||
StopPrice: "49000.00",
|
||||
Price: "48500.00",
|
||||
Size: "1.0",
|
||||
}
|
||||
```
|
||||
|
||||
### Iceberg Order
|
||||
|
||||
Display only partial quantity:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Iceberg,
|
||||
Side: types.Buy,
|
||||
Price: "50000.00",
|
||||
Size: "100.0", // Total size
|
||||
DisplaySize: "10.0", // Visible size
|
||||
}
|
||||
```
|
||||
|
||||
### Pegged Order
|
||||
|
||||
Track reference price:
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Peg,
|
||||
Side: types.Buy,
|
||||
PegType: types.PegBestBid,
|
||||
Offset: "-0.01", // 1 cent below best bid
|
||||
Size: "1.0",
|
||||
}
|
||||
```
|
||||
|
||||
## Time in Force
|
||||
|
||||
| TIF | Description | Behavior |
|
||||
|-----|-------------|----------|
|
||||
| GTC | Good Till Cancelled | Remains until filled or cancelled |
|
||||
| IOC | Immediate or Cancel | Fill what's possible, cancel rest |
|
||||
| FOK | Fill or Kill | Fill entirely or cancel entirely |
|
||||
| DAY | Day Order | Expires at end of trading day |
|
||||
|
||||
```go
|
||||
order := &types.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: types.Limit,
|
||||
Side: types.Buy,
|
||||
Price: "50000.00",
|
||||
Size: "1.0",
|
||||
TimeInForce: types.IOC,
|
||||
}
|
||||
```
|
||||
|
||||
## Matching Algorithm
|
||||
|
||||
### Price-Time Priority
|
||||
|
||||
Orders are matched using price-time priority (FIFO at each price level):
|
||||
|
||||
```go
|
||||
func (book *OrderBook) Match(incomingOrder *Order) []*Trade {
|
||||
var trades []*Trade
|
||||
|
||||
// Get opposing side
|
||||
levels := book.GetOpposingSide(incomingOrder.Side)
|
||||
|
||||
for _, level := range levels {
|
||||
if !level.CanMatch(incomingOrder) {
|
||||
break
|
||||
}
|
||||
|
||||
for _, restingOrder := range level.Orders {
|
||||
trade := book.ExecuteTrade(incomingOrder, restingOrder)
|
||||
trades = append(trades, trade)
|
||||
|
||||
if incomingOrder.RemainingSize == 0 {
|
||||
return trades
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add unfilled portion to book
|
||||
if incomingOrder.RemainingSize > 0 {
|
||||
book.AddToBook(incomingOrder)
|
||||
}
|
||||
|
||||
return trades
|
||||
}
|
||||
```
|
||||
|
||||
### Execution Flow
|
||||
|
||||
1. **Validation**: Check order parameters
|
||||
2. **Risk Check**: Verify margin/balance
|
||||
3. **Price Match**: Find matching orders
|
||||
4. **Trade Execution**: Execute matched trades
|
||||
5. **Book Update**: Add remainder to book
|
||||
6. **Notification**: Publish trade events
|
||||
|
||||
## Performance Engines
|
||||
|
||||
### Pure Go Engine
|
||||
|
||||
Default engine with excellent portability:
|
||||
|
||||
```go
|
||||
book := lx.NewOrderBook("BTC-USD", lx.WithGoEngine())
|
||||
```
|
||||
|
||||
Performance:
|
||||
- Throughput: 1M+ orders/sec
|
||||
- Latency: ~500ns
|
||||
- Memory: ~100 bytes per order
|
||||
|
||||
### C++ Engine
|
||||
|
||||
High-performance engine with SIMD optimizations:
|
||||
|
||||
```go
|
||||
book := lx.NewOrderBook("BTC-USD", lx.WithCppEngine())
|
||||
```
|
||||
|
||||
Performance:
|
||||
- Throughput: 30M+ orders/sec
|
||||
- Latency: ~25ns
|
||||
- Requires: CGO enabled
|
||||
|
||||
### GPU/MLX Engine
|
||||
|
||||
Massive parallelization on Apple Silicon:
|
||||
|
||||
```go
|
||||
book := lx.NewOrderBook("BTC-USD", lx.WithMLXEngine())
|
||||
```
|
||||
|
||||
Performance:
|
||||
- Throughput: 434M+ orders/sec
|
||||
- Latency: ~2ns
|
||||
- Requires: Apple Silicon M-series
|
||||
|
||||
### Auto-Selection
|
||||
|
||||
Automatically choose best available engine:
|
||||
|
||||
```go
|
||||
book := lx.NewOrderBook("BTC-USD", lx.WithAutoEngine())
|
||||
```
|
||||
|
||||
Selection order:
|
||||
1. GPU/MLX (if Apple Silicon available)
|
||||
2. C++ (if CGO enabled)
|
||||
3. Pure Go (fallback)
|
||||
|
||||
## Memory Management
|
||||
|
||||
### Object Pooling
|
||||
|
||||
Reuse order objects to minimize allocations:
|
||||
|
||||
```go
|
||||
var orderPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &Order{}
|
||||
},
|
||||
}
|
||||
|
||||
func GetOrder() *Order {
|
||||
return orderPool.Get().(*Order)
|
||||
}
|
||||
|
||||
func PutOrder(order *Order) {
|
||||
order.Reset()
|
||||
orderPool.Put(order)
|
||||
}
|
||||
```
|
||||
|
||||
### Lock-Free Trade Buffer
|
||||
|
||||
Zero-copy circular buffer for trades:
|
||||
|
||||
```go
|
||||
type CircularTradeBuffer struct {
|
||||
buffer []Trade
|
||||
head atomic.Uint64
|
||||
tail atomic.Uint64
|
||||
mask uint64
|
||||
}
|
||||
|
||||
func (b *CircularTradeBuffer) Push(trade *Trade) {
|
||||
pos := b.head.Add(1) - 1
|
||||
b.buffer[pos & b.mask] = *trade
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### PlaceOrder
|
||||
|
||||
```go
|
||||
func (book *OrderBook) PlaceOrder(order *Order) (*OrderResult, error)
|
||||
```
|
||||
|
||||
Returns order placement result with:
|
||||
- OrderID
|
||||
- Status (Open, Filled, PartiallyFilled, Rejected)
|
||||
- FilledSize
|
||||
- Trades executed
|
||||
|
||||
### CancelOrder
|
||||
|
||||
```go
|
||||
func (book *OrderBook) CancelOrder(orderID string) (*CancelResult, error)
|
||||
```
|
||||
|
||||
### ModifyOrder
|
||||
|
||||
```go
|
||||
func (book *OrderBook) ModifyOrder(orderID string, newPrice, newSize string) (*ModifyResult, error)
|
||||
```
|
||||
|
||||
### GetOrderBook
|
||||
|
||||
```go
|
||||
func (book *OrderBook) GetOrderBook(depth int) *OrderBookSnapshot
|
||||
```
|
||||
|
||||
### GetOrder
|
||||
|
||||
```go
|
||||
func (book *OrderBook) GetOrder(orderID string) (*Order, error)
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
### Order Events
|
||||
|
||||
```go
|
||||
book.OnOrder(func(event *OrderEvent) {
|
||||
switch event.Type {
|
||||
case OrderCreated:
|
||||
// New order added to book
|
||||
case OrderFilled:
|
||||
// Order completely filled
|
||||
case OrderPartiallyFilled:
|
||||
// Order partially filled
|
||||
case OrderCancelled:
|
||||
// Order cancelled
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Trade Events
|
||||
|
||||
```go
|
||||
book.OnTrade(func(trade *Trade) {
|
||||
fmt.Printf("Trade: %s %s @ %s\n",
|
||||
trade.Symbol, trade.Size, trade.Price)
|
||||
})
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
Run benchmarks:
|
||||
|
||||
```bash
|
||||
go test -bench=BenchmarkOrderBook -benchmem ./pkg/lx/
|
||||
```
|
||||
|
||||
Results (Apple M2 Ultra):
|
||||
|
||||
```
|
||||
BenchmarkOrderBook/Place-24 2062933 487 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkOrderBook/Cancel-24 5234567 229 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkOrderBook/Match-24 1234567 851 ns/op 0 B/op 0 allocs/op
|
||||
BenchmarkOrderBook/MLX-24 434782609 2.3 ns/op 0 B/op 0 allocs/op
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Use object pooling** for high-frequency trading
|
||||
2. **Batch orders** when possible for better throughput
|
||||
3. **Choose appropriate engine** based on latency requirements
|
||||
4. **Monitor memory** to avoid GC pauses
|
||||
5. **Use atomic operations** for counters and flags
|
||||
@@ -0,0 +1,401 @@
|
||||
---
|
||||
title: SDK Guide
|
||||
description: Client libraries for integrating with LX DEX - TypeScript, Python, Go, and Rust SDKs
|
||||
---
|
||||
|
||||
# LX DEX SDK Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
LX DEX provides multiple SDKs and APIs for integration:
|
||||
- **TypeScript/JavaScript** - Web and Node.js applications
|
||||
- **Python** - Data analysis and algorithmic trading
|
||||
- **Go** - High-performance server applications
|
||||
- **Rust** - Systems programming (coming soon)
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Start the DEX Node
|
||||
|
||||
```bash
|
||||
# Build the node
|
||||
make build
|
||||
|
||||
# Run the node
|
||||
./bin/luxd
|
||||
```
|
||||
|
||||
This starts:
|
||||
- JSON-RPC API on port 8080
|
||||
- gRPC server on port 50051
|
||||
- WebSocket server on port 8081
|
||||
- P2P networking on port 5000
|
||||
|
||||
## TypeScript SDK
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
npm install @luxfi/dex-sdk
|
||||
# or
|
||||
pnpm add @luxfi/dex-sdk
|
||||
# or
|
||||
yarn add @luxfi/dex-sdk
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```typescript
|
||||
import { LXDexClient } from '@luxfi/dex-sdk';
|
||||
|
||||
const client = new LXDexClient({
|
||||
jsonRpcUrl: 'http://localhost:8080/rpc',
|
||||
wsUrl: 'ws://localhost:8081'
|
||||
});
|
||||
|
||||
// Place an order
|
||||
const order = await client.placeOrder({
|
||||
symbol: 'BTC-USD',
|
||||
type: 'limit',
|
||||
side: 'buy',
|
||||
price: 50000,
|
||||
size: 1.0
|
||||
});
|
||||
|
||||
console.log('Order placed:', order.orderId);
|
||||
```
|
||||
|
||||
### WebSocket Subscriptions
|
||||
|
||||
```typescript
|
||||
// Subscribe to order book
|
||||
client.subscribeOrderBook('BTC-USD', (book) => {
|
||||
console.log('Best bid:', book.bids[0]);
|
||||
console.log('Best ask:', book.asks[0]);
|
||||
});
|
||||
|
||||
// Subscribe to trades
|
||||
client.subscribeTrades('BTC-USD', (trade) => {
|
||||
console.log('New trade:', trade);
|
||||
});
|
||||
|
||||
// Subscribe to your orders
|
||||
client.subscribeUserOrders((order) => {
|
||||
console.log('Order update:', order);
|
||||
});
|
||||
```
|
||||
|
||||
### Advanced Configuration
|
||||
|
||||
```typescript
|
||||
const client = new LXDexClient({
|
||||
jsonRpcUrl: 'https://api.lux.network/rpc',
|
||||
wsUrl: 'wss://api.lux.network/ws',
|
||||
apiKey: 'your-api-key',
|
||||
apiSecret: 'your-api-secret',
|
||||
timeout: 30000,
|
||||
retry: {
|
||||
maxRetries: 3,
|
||||
backoffMs: 1000
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Python SDK
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
pip install luxfi-dex
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```python
|
||||
from luxfi_dex import LXDexClient
|
||||
|
||||
client = LXDexClient(
|
||||
json_rpc_url='http://localhost:8080/rpc',
|
||||
ws_url='ws://localhost:8081'
|
||||
)
|
||||
|
||||
# Place an order
|
||||
order = client.place_order(
|
||||
symbol='BTC-USD',
|
||||
order_type='limit',
|
||||
side='buy',
|
||||
price=50000,
|
||||
size=1.0
|
||||
)
|
||||
|
||||
print(f'Order placed: {order.order_id}')
|
||||
```
|
||||
|
||||
### Get Market Data
|
||||
|
||||
```python
|
||||
# Get order book
|
||||
book = client.get_order_book('BTC-USD', depth=10)
|
||||
print(f"Best bid: {book['bids'][0]}")
|
||||
print(f"Best ask: {book['asks'][0]}")
|
||||
|
||||
# Get recent trades
|
||||
trades = client.get_trades('BTC-USD', limit=100)
|
||||
for trade in trades:
|
||||
print(f"{trade['side']} {trade['size']} @ {trade['price']}")
|
||||
```
|
||||
|
||||
### Async Support
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from luxfi_dex import AsyncLXDexClient
|
||||
|
||||
async def main():
|
||||
client = AsyncLXDexClient(
|
||||
json_rpc_url='http://localhost:8080/rpc',
|
||||
ws_url='ws://localhost:8081'
|
||||
)
|
||||
|
||||
# Place order asynchronously
|
||||
order = await client.place_order(
|
||||
symbol='BTC-USD',
|
||||
order_type='limit',
|
||||
side='buy',
|
||||
price=50000,
|
||||
size=1.0
|
||||
)
|
||||
|
||||
# Stream market data
|
||||
async for book in client.stream_order_book('BTC-USD'):
|
||||
print(f"Bid: {book.best_bid}, Ask: {book.best_ask}")
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Go SDK
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/dex/sdk/go
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/luxfi/dex/sdk/go/lxdex"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := lxdex.NewClient(
|
||||
lxdex.WithJSONRPC("http://localhost:8080/rpc"),
|
||||
lxdex.WithGRPC("localhost:50051"),
|
||||
)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Place an order
|
||||
order, err := client.PlaceOrder(ctx, &lxdex.Order{
|
||||
Symbol: "BTC-USD",
|
||||
Type: lxdex.OrderTypeLimit,
|
||||
Side: lxdex.Buy,
|
||||
Price: 50000,
|
||||
Size: 1.0,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Printf("Order placed: %s\n", order.OrderID)
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming Data
|
||||
|
||||
```go
|
||||
// Stream order book
|
||||
stream, err := client.StreamOrderBook(ctx, "BTC-USD")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for {
|
||||
update, err := stream.Recv()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
fmt.Printf("Order book update: %+v\n", update)
|
||||
}
|
||||
```
|
||||
|
||||
### gRPC Integration
|
||||
|
||||
```go
|
||||
import (
|
||||
"context"
|
||||
"google.golang.org/grpc"
|
||||
pb "github.com/luxfi/dex/pkg/grpc/pb"
|
||||
)
|
||||
|
||||
// Connect to gRPC server
|
||||
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
|
||||
defer conn.Close()
|
||||
|
||||
client := pb.NewLXDEXServiceClient(conn)
|
||||
|
||||
// Place an order via gRPC
|
||||
resp, err := client.PlaceOrder(context.Background(), &pb.PlaceOrderRequest{
|
||||
Symbol: "BTC-USD",
|
||||
Type: pb.OrderType_LIMIT,
|
||||
Side: pb.OrderSide_BUY,
|
||||
Price: 50000,
|
||||
Size: 1.0,
|
||||
UserId: "trader1",
|
||||
})
|
||||
```
|
||||
|
||||
## Order Types
|
||||
|
||||
| Type | Value | Description |
|
||||
|------|-------|-------------|
|
||||
| LIMIT | 0 | Order at specific price |
|
||||
| MARKET | 1 | Execute at best price |
|
||||
| STOP | 2 | Trigger at stop price |
|
||||
| STOP_LIMIT | 3 | Stop becomes limit |
|
||||
| ICEBERG | 4 | Hidden quantity order |
|
||||
| PEG | 5 | Pegged to best bid/ask |
|
||||
|
||||
## Order Sides
|
||||
|
||||
| Side | Value | Description |
|
||||
|------|-------|-------------|
|
||||
| BUY | 0 | Buy order |
|
||||
| SELL | 1 | Sell order |
|
||||
|
||||
## Time in Force
|
||||
|
||||
| TIF | Description |
|
||||
|-----|-------------|
|
||||
| GTC | Good Till Cancelled |
|
||||
| IOC | Immediate Or Cancel |
|
||||
| FOK | Fill Or Kill |
|
||||
| DAY | Day Order |
|
||||
|
||||
## Error Handling
|
||||
|
||||
### TypeScript
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const order = await client.placeOrder({...});
|
||||
} catch (error) {
|
||||
if (error.code === 'INSUFFICIENT_BALANCE') {
|
||||
console.error('Not enough funds');
|
||||
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
|
||||
console.error('Too many requests');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
from luxfi_dex.exceptions import InsufficientBalanceError, RateLimitError
|
||||
|
||||
try:
|
||||
order = client.place_order(...)
|
||||
except InsufficientBalanceError:
|
||||
print('Not enough funds')
|
||||
except RateLimitError:
|
||||
print('Too many requests')
|
||||
except Exception as e:
|
||||
print(f'Error: {e}')
|
||||
```
|
||||
|
||||
### Go
|
||||
|
||||
```go
|
||||
order, err := client.PlaceOrder(ctx, &lxdex.Order{...})
|
||||
if err != nil {
|
||||
switch e := err.(type) {
|
||||
case *lxdex.InsufficientBalanceError:
|
||||
log.Printf("Not enough funds: need %f, have %f", e.Required, e.Available)
|
||||
case *lxdex.RateLimitError:
|
||||
log.Printf("Rate limited, retry after %v", e.RetryAfter)
|
||||
default:
|
||||
log.Printf("Error: %v", err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limits
|
||||
|
||||
| Endpoint | Limit |
|
||||
|----------|-------|
|
||||
| Orders | 100/sec per user |
|
||||
| Cancellations | 100/sec per user |
|
||||
| Market Data | 1000 req/min |
|
||||
| WebSocket | 10 connections/IP |
|
||||
|
||||
## Authentication
|
||||
|
||||
### API Key Setup
|
||||
|
||||
```typescript
|
||||
const client = new LXDexClient({
|
||||
apiKey: 'your-api-key',
|
||||
apiSecret: 'your-api-secret'
|
||||
});
|
||||
```
|
||||
|
||||
### JWT Authentication
|
||||
|
||||
```python
|
||||
client = LXDexClient(
|
||||
jwt_token='eyJhbGciOiJIUzI1NiIs...'
|
||||
)
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Network
|
||||
|
||||
```bash
|
||||
# Start test node
|
||||
./bin/luxd --testnet
|
||||
|
||||
# Use test endpoints
|
||||
JSON-RPC: http://localhost:18080/rpc
|
||||
gRPC: localhost:15051
|
||||
WebSocket: ws://localhost:18081
|
||||
```
|
||||
|
||||
### Example Test Script
|
||||
|
||||
```bash
|
||||
# Run SDK tests
|
||||
npm test # TypeScript
|
||||
python -m pytest # Python
|
||||
go test ./... # Go
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
- **Order Matching**: 597ns latency (C++ engine)
|
||||
- **Throughput**: 100M+ orders/second (with MLX GPU)
|
||||
- **Block Time**: 1ms finality
|
||||
- **Network**: Quantum-secure with BLS signatures
|
||||
|
||||
## Support
|
||||
|
||||
- GitHub: https://github.com/luxfi/dex
|
||||
- Documentation: https://dex.lux.network
|
||||
- Discord: https://discord.gg/luxfi
|
||||
@@ -13,6 +13,10 @@ const config = {
|
||||
images: {
|
||||
unoptimized: true,
|
||||
},
|
||||
// For GitHub Pages deployment at dex.lux.network
|
||||
// No basePath needed since using custom domain
|
||||
basePath: '',
|
||||
trailingSlash: true,
|
||||
}
|
||||
|
||||
const withMDX = createMDX()
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --port 3001",
|
||||
"build": "fumadocs-mdx && TURBOPACK=0 next build",
|
||||
"build": "fumadocs-mdx && next build",
|
||||
"export": "TURBOPACK=0 next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
@@ -15,7 +15,7 @@
|
||||
"fumadocs-mdx": "^12.0.3",
|
||||
"fumadocs-ui": "^15.8.5",
|
||||
"lucide-react": "^0.468.0",
|
||||
"next": "16.0.1",
|
||||
"next": "15.3.3",
|
||||
"react": "19.2.0",
|
||||
"react-dom": "19.2.0",
|
||||
"tailwindcss": "^4.1.16",
|
||||
|
||||
Generated
+4157
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
dex.lux.network
|
||||
+20
-5
@@ -1,6 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
@@ -18,9 +22,20 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./*"]
|
||||
}
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
},
|
||||
"target": "ES2017"
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user