โก DEX Platform
Bitcoin-Native Decentralized Exchange for Professional Trading
๐ฏ Overviewโ
The BLGV DEX Platform is a professional-grade decentralized exchange designed specifically for Bitcoin-native assets, Taproot Assets, and cross-platform trading within the BLGV ecosystem.
Key Featuresโ
- Bitcoin-Native Trading: Direct BTC and Lightning Network integration
- Taproot Assets: First-class support for Bitcoin-native tokens
- Professional Interface: Advanced trading tools and analytics
- Cross-Platform Integration: Seamless mobile and treasury platform sync
- Lightning Fast: Instant settlement via Lightning Network
Production URLโ
Live Platform: https://dex.blgvbtc.com
๐๏ธ Architectureโ
Technology Stackโ
- Frontend: React 18 + TypeScript + Vite
- Backend: Node.js + Express
- Database: PostgreSQL (dex schema)
- Trading Engine: Custom orderbook and matching engine
- Payments: BTCPay Server + Lightning Network
- WebSockets: Real-time price feeds and order updates
Directory Structureโ
platforms/dex/
โโโ client/ # React frontend
โ โโโ src/
โ โ โโโ components/ # UI components
โ โ โโโ pages/ # Trading interface pages
โ โ โโโ lib/ # Trading utilities
โ โ โโโ index.css # Styles
โ โโโ package.json
โโโ server/ # Trading engine backend
โ โโโ routes/ # API routes
โ โโโ amm-engine.ts # AMM trading engine
โ โโโ btcpay-plugin.ts # Payment integration
โ โโโ index.ts # Server entry
โโโ shared/ # Shared trading logic
โโโ mobile/ # Mobile SDK integration
โโโ README.md
Database Schemaโ
- Schema:
dex - Main Tables:
users,trading_pairs,orders,trades - Real-Time: Order book and trade history
๐ Getting Startedโ
Development Setupโ
cd platforms/dex
# Install dependencies
npm install
# Setup environment
cp .env.example .env.development
# Start development servers
npm run dev
# Frontend: http://localhost:3002
# Backend API: http://localhost:3002/api
Environment Variablesโ
# Development
NODE_ENV=development
DATABASE_URL=postgresql://localhost:5432/blgv_development
BTCPAY_API_KEY=your_btcpay_key
TREASURY_WEBHOOK_URL=http://localhost:3001/v1/events
# Production (see docs/ENVIRONMENT_SECRETS.md)
NODE_ENV=production
DATABASE_URL=postgresql://doadmin:...
BTCPAY_LIVE_API_KEY=production_key
TREASURY_WEBHOOK_URL=https://blgvbtc.com/v1/events
๐ฑ Trading Featuresโ
1. Order Managementโ
Component: TradingInterface.tsx
Professional trading interface:
- Market and limit orders
- Stop-loss and take-profit orders
- Order book visualization
- Trade history and portfolio tracking
2. Automated Market Making (AMM)โ
Engine: amm-engine.ts
Advanced AMM functionality:
- Liquidity pools for trading pairs
- Dynamic fee adjustments
- Slippage protection
- Yield farming opportunities
3. Lightning Integrationโ
Component: LightningPayments.tsx
Instant settlement capabilities:
- Lightning Network deposits/withdrawals
- Submarine swaps (on-chain โ Lightning)
- Channel management
- Real-time settlement
4. Taproot Assetsโ
Component: TaprootAssets.tsx
Bitcoin-native token support:
- Asset issuance and management
- Cross-asset trading pairs
- Asset metadata and verification
- Multi-asset portfolios
๐ API Endpointsโ
Tradingโ
GET /api/markets # Available trading pairs
GET /api/orderbook/:pair # Order book for trading pair
POST /api/orders # Create new order
GET /api/orders # User's orders
DELETE /api/orders/:id # Cancel order
Portfolioโ
GET /api/portfolio # User portfolio
GET /api/trades # Trade history
GET /api/balances # Account balances
POST /api/deposits # Initiate deposit
POST /api/withdrawals # Request withdrawal
Market Dataโ
GET /api/tickers # 24h ticker data
GET /api/candles/:pair # OHLCV candlestick data
GET /api/trades/:pair # Recent trades
GET /api/stats # Platform statistics
Lightningโ
POST /api/lightning/invoice # Create Lightning invoice
GET /api/lightning/channels # Channel information
POST /api/lightning/swap # Submarine swap
GET /api/lightning/balance # Lightning balance
๐ Authentication & Securityโ
Wallet-Based Authenticationโ
// Connect Bitcoin wallet
const walletAddress = await connectWallet();
// Sign authentication message
const signature = await signMessage(authMessage);
// Authenticate with DEX
const session = await dexSDK.auth.authenticateWithWallet(
walletAddress,
signature
);
Trading Securityโ
- Non-Custodial: Users control their private keys
- Multi-Signature: Optional multi-sig wallet support
- Time-Locked Orders: Automated order expiration
- Rate Limiting: Protection against API abuse
Fund Securityโ
- Lightning Channels: Secure channel state management
- On-Chain Escrow: Multi-signature escrow for large trades
- Hot/Cold Storage: Segregated fund management
- Regular Audits: Proof-of-reserves verification
๐ฑ Mobile Integrationโ
SDK Integrationโ
import { blgvSDK } from '../../sdk/typescript';
// Get market data for mobile
const markets = await blgvSDK.dex.getMarkets();
// Place mobile order
const order = await blgvSDK.dex.createOrder({
pair: 'BTC/USDT',
side: 'buy',
amount: 0.001,
type: 'market'
});
// Real-time price updates
blgvSDK.dex.subscribeToPriceUpdates((update) => {
updateMobilePrices(update);
});
Mobile Featuresโ
- Touch-Optimized Interface: Mobile-first trading UI
- Biometric Orders: Biometric confirmation for trades
- Push Notifications: Price alerts and order fills
- Offline Portfolio: Cached portfolio data
๐ Real-Time Tradingโ
WebSocket Feedsโ
// Real-time order book updates
const ws = new WebSocket('/ws/orderbook/BTC-USDT');
ws.on('orderbook_update', (data) => {
updateOrderBook(data);
});
// Real-time trade stream
ws.on('trade', (trade) => {
updateTradeHistory(trade);
});
// Price ticker updates
ws.on('ticker', (ticker) => {
updatePriceTicker(ticker);
});
Market Data Feedsโ
- Order Book: Real-time bid/ask updates
- Trade Stream: Live trade execution data
- Price Tickers: 24h price and volume data
- Depth Charts: Market depth visualization
๐ฐ Payment Integrationโ
BTCPay Server Integrationโ
// Create payment invoice
const invoice = await btcpay.createInvoice({
amount: 0.001,
currency: 'BTC',
description: 'DEX deposit'
});
// Monitor payment status
btcpay.on('payment_received', (payment) => {
creditUserAccount(payment);
});
Lightning Networkโ
// Lightning deposit
const lightningInvoice = await lnd.createInvoice({
amount: 10000, // sats
memo: 'DEX Lightning deposit'
});
// Lightning withdrawal
const withdrawal = await lnd.payInvoice({
invoice: userInvoice,
amount: 5000
});
๐งช Testingโ
Trading Engine Testsโ
# Order matching tests
npm run test:orderbook
# AMM engine tests
npm run test:amm
# Lightning integration tests
npm run test:lightning
# End-to-end trading tests
npm run test:e2e:trading
Test Coverageโ
- Order Matching: Comprehensive order book testing
- Payment Integration: BTCPay and Lightning testing
- API Endpoints: Full REST API testing
- WebSocket: Real-time data stream testing
๐ Deploymentโ
Production Deploymentโ
# Sync to production repo
./ops/deploy/sync-to-production.sh dex
# Monitor deployment
./ops/deploy/sync-to-production.sh --status
# Verify trading functionality
curl -s https://dex.blgvbtc.com/api/health
curl -s https://dex.blgvbtc.com/api/markets
Health Checksโ
- Endpoint:
/api/health - Trading Engine: Order matching functionality
- Database: Connection and query performance
- BTCPay: Payment processor connectivity
- Lightning: Node connectivity and channel status
๐ Trading Analyticsโ
Platform Metricsโ
- Trading Volume: 24h and historical volume
- Liquidity Depth: Order book depth analysis
- User Activity: Active traders and new signups
- Fee Revenue: Platform fee generation
Performance Monitoringโ
- Order Latency: Time from order to execution
- WebSocket Performance: Real-time data delivery
- Payment Processing: Deposit/withdrawal times
- Database Queries: Trading query optimization
๐ ๏ธ Development Guidelinesโ
Trading Engine Developmentโ
// Order processing template
interface Order {
id: string;
userId: string;
pair: string;
side: 'buy' | 'sell';
type: 'market' | 'limit';
amount: number;
price?: number;
status: 'pending' | 'filled' | 'cancelled';
}
const processOrder = async (order: Order) => {
// Validation
// Risk checks
// Order matching
// Settlement
};
Component Developmentโ
// Trading component template
interface TradingComponentProps {
pair: TradingPair;
orderBook: OrderBook;
onOrderCreate: (order: Order) => void;
}
const TradingComponent: React.FC<TradingComponentProps> = ({
pair,
orderBook,
onOrderCreate
}) => {
// Trading logic
return (
<div className="trading-interface">
{/* Trading UI */}
</div>
);
};
๐ Troubleshootingโ
Common Issuesโ
Order Not Executingโ
# Check order book liquidity
curl https://dex.blgvbtc.com/api/orderbook/BTC-USDT
# Verify order parameters
curl https://dex.blgvbtc.com/api/orders/USER_ORDER_ID
# Check trading engine logs
tail -f logs/trading-engine.log
Payment Issuesโ
# Test BTCPay connection
curl -H "Authorization: Bearer $BTCPAY_API_KEY" \
https://btc.gdyup.xyz/api/v1/stores
# Check Lightning node status
lightning-cli getinfo
# Verify invoice status
curl https://dex.blgvbtc.com/api/invoices/INVOICE_ID
WebSocket Connection Failedโ
# Test WebSocket endpoint
wscat -c wss://dex.blgvbtc.com/ws/orderbook/BTC-USDT
# Check connection limits
netstat -an | grep 3002 | wc -l
# Verify authentication
# Check WebSocket authentication headers
๐ง Configurationโ
Trading Parametersโ
# Order matching
MIN_ORDER_SIZE=0.00001
MAX_ORDER_SIZE=10.0
TICK_SIZE=0.01
MAKER_FEE=0.001
TAKER_FEE=0.002
# Risk management
MAX_OPEN_ORDERS=100
DAILY_TRADING_LIMIT=1.0
WITHDRAWAL_LIMIT=0.1
Performance Settingsโ
# WebSocket
WS_MAX_CONNECTIONS=10000
WS_HEARTBEAT_INTERVAL=30000
# Database
ORDER_BOOK_CACHE_TTL=5000
TRADE_HISTORY_LIMIT=1000
# Lightning
CHANNEL_RESERVE=100000
PAYMENT_TIMEOUT=30000
๐ Resourcesโ
Documentationโ
External Resourcesโ
๐ฏ Roadmapโ
Current Features โ โ
- Spot trading (BTC/USDT, BTC/USD)
- Lightning deposits/withdrawals
- Real-time order book
- Mobile trading interface
- Cross-platform portfolio sync
Planned Features ๐โ
-
Q1 2025
- Taproot Assets trading
- Advanced order types
- Margin trading
- DCA (Dollar Cost Averaging)
-
Q2 2025
- Derivatives trading
- Options contracts
- Liquidity mining
- Governance tokens
-
Q3 2025
- Cross-chain bridges
- Automated trading bots
- Institutional API
- Advanced charting
Maintainer: DEX Team
Last Updated: January 2025
Version: 2.1.0