|
| 1 | +# Frontend-Backend Integration Guide |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +This document outlines the integration between the Next.js frontend and Rust/Axum backend for the Trustee DEX application. |
| 6 | + |
| 7 | +## Architecture |
| 8 | + |
| 9 | +``` |
| 10 | +┌─────────────────┐ HTTP/SSE ┌─────────────────┐ |
| 11 | +│ Next.js │ ◄────────────► │ Rust/Axum │ |
| 12 | +│ Frontend │ │ Backend │ |
| 13 | +│ │ │ │ |
| 14 | +│ • Porto Wallet │ │ • Orderbook │ |
| 15 | +│ • UI Components │ │ • Matching │ |
| 16 | +│ • API Client │ │ • SSE Events │ |
| 17 | +└─────────────────┘ └─────────────────┘ |
| 18 | +``` |
| 19 | + |
| 20 | +## API Endpoints |
| 21 | + |
| 22 | +### Backend Endpoints (Port 3000) |
| 23 | + |
| 24 | +| Method | Endpoint | Description | |
| 25 | +| ------ | ----------------------------- | ---------------------------- | |
| 26 | +| GET | `/orderbook?pair=ETH/USDC` | Get public orderbook | |
| 27 | +| GET | `/orders/:address` | Get user's private orders | |
| 28 | +| POST | `/encumbered_wallet/:address` | Create encumbered wallet | |
| 29 | +| POST | `/order/:address` | Create new order | |
| 30 | +| GET | `/order/:id` | Get specific order | |
| 31 | +| DELETE | `/order/:id` | Cancel order | |
| 32 | +| POST | `/withdraw` | Withdraw funds | |
| 33 | +| GET | `/order_filled` | SSE stream for filled orders | |
| 34 | + |
| 35 | +### Frontend API Client |
| 36 | + |
| 37 | +Located in `frontend/lib/api.ts`, provides TypeScript wrappers for all backend endpoints. |
| 38 | + |
| 39 | +## Data Flow |
| 40 | + |
| 41 | +### 1. Order Creation Flow |
| 42 | + |
| 43 | +```typescript |
| 44 | +// 1. User connects wallet (Porto) |
| 45 | +const { address } = useAccount(); |
| 46 | + |
| 47 | +// 2. Create encumbered wallet |
| 48 | +const encumberedWallet = await postEncumberedWallet(address); |
| 49 | + |
| 50 | +// 3. Transfer assets to encumbered wallet |
| 51 | +await walletClient.sendTransaction({ |
| 52 | + to: encumberedWallet, |
| 53 | + value: parseEther(amount), |
| 54 | +}); |
| 55 | + |
| 56 | +// 4. Create order on backend |
| 57 | +await postOrder(address, { |
| 58 | + asset_sold: tokenAddress, |
| 59 | + amount_sold: amount, |
| 60 | + asset_bought: otherTokenAddress, |
| 61 | + amount_bought: otherAmount, |
| 62 | + pair: "ETH/USDC", |
| 63 | + expiry: timestamp, |
| 64 | +}); |
| 65 | +``` |
| 66 | + |
| 67 | +### 2. Order Matching Flow |
| 68 | + |
| 69 | +```rust |
| 70 | +// Backend matching engine runs continuously |
| 71 | +pub async fn match_orders(&mut self) { |
| 72 | + // Find matching orders |
| 73 | + // Execute trades |
| 74 | + // Update balances |
| 75 | + // Send SSE events |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +### 3. Real-time Updates |
| 80 | + |
| 81 | +```typescript |
| 82 | +// Frontend subscribes to SSE events |
| 83 | +const es = openOrderFilledStream(); |
| 84 | +es.onmessage = (evt) => { |
| 85 | + const data: OrderFilled = JSON.parse(evt.data); |
| 86 | + // Update UI with filled order |
| 87 | +}; |
| 88 | +``` |
| 89 | + |
| 90 | +## Type Definitions |
| 91 | + |
| 92 | +### Shared Types (Rust → TypeScript) |
| 93 | + |
| 94 | +```rust |
| 95 | +// crates/primitives/src/lib.rs |
| 96 | +pub struct PublicOrder { |
| 97 | + pub id: Uuid, |
| 98 | + pub asset_sold: Address, |
| 99 | + pub amount_sold: U256, |
| 100 | + pub asset_bought: Address, |
| 101 | + pub amount_bought: U256, |
| 102 | + pub pair: String, |
| 103 | + pub expiry: u64, |
| 104 | + pub status: OrderStatus, |
| 105 | +} |
| 106 | +``` |
| 107 | + |
| 108 | +```typescript |
| 109 | +// frontend/lib/types.ts |
| 110 | +export type PublicOrder = { |
| 111 | + id: UUID; |
| 112 | + asset_sold: Address; |
| 113 | + amount_sold: BigNumberString; |
| 114 | + asset_bought: Address; |
| 115 | + amount_bought: BigNumberString; |
| 116 | + pair: string; |
| 117 | + expiry: number; |
| 118 | + status: "FILLED" | "OPEN" | "WITHDRAWN" | "CANCELLED"; |
| 119 | +}; |
| 120 | +``` |
| 121 | + |
| 122 | +## Development Setup |
| 123 | + |
| 124 | +### Prerequisites |
| 125 | + |
| 126 | +- Node.js 18+ |
| 127 | +- Rust 1.70+ |
| 128 | +- pnpm |
| 129 | + |
| 130 | +### Quick Start |
| 131 | + |
| 132 | +1. **Install dependencies:** |
| 133 | + |
| 134 | + ```bash |
| 135 | + npm run install:all |
| 136 | + ``` |
| 137 | + |
| 138 | +2. **Set environment variables:** |
| 139 | + |
| 140 | + ```bash |
| 141 | + # Backend |
| 142 | + export PRIVATE_KEY="your_private_key_here" |
| 143 | + |
| 144 | + # Frontend (optional) |
| 145 | + export NEXT_PUBLIC_API_URL="http://localhost:3000" |
| 146 | + ``` |
| 147 | + |
| 148 | +3. **Start development servers:** |
| 149 | + |
| 150 | + ```bash |
| 151 | + npm run dev |
| 152 | + ``` |
| 153 | + |
| 154 | +4. **Access the application:** |
| 155 | + - Frontend: http://localhost:3001 |
| 156 | + - Backend: http://localhost:3000 |
| 157 | + |
| 158 | +### Individual Commands |
| 159 | + |
| 160 | +```bash |
| 161 | +# Backend only |
| 162 | +npm run dev:backend |
| 163 | + |
| 164 | +# Frontend only |
| 165 | +npm run dev:frontend |
| 166 | + |
| 167 | +# Build both |
| 168 | +npm run build |
| 169 | +``` |
| 170 | + |
| 171 | +## Key Integration Points |
| 172 | + |
| 173 | +### 1. CORS Configuration |
| 174 | + |
| 175 | +Backend allows all origins for development: |
| 176 | + |
| 177 | +```rust |
| 178 | +let cors = CorsLayer::new() |
| 179 | + .allow_origin(Any) |
| 180 | + .allow_methods(Any) |
| 181 | + .allow_headers(Any); |
| 182 | +``` |
| 183 | + |
| 184 | +### 2. Error Handling |
| 185 | + |
| 186 | +Both frontend and backend use consistent error responses: |
| 187 | + |
| 188 | +```typescript |
| 189 | +// Frontend |
| 190 | +if (!res.ok) throw new Error(`API failed: ${res.statusText}`); |
| 191 | +``` |
| 192 | + |
| 193 | +```rust |
| 194 | +// Backend |
| 195 | +#[derive(Debug, Serialize)] |
| 196 | +pub enum AppError { |
| 197 | + OrderNotFound, |
| 198 | + InvalidOrder(String), |
| 199 | + Unauthorized, |
| 200 | + // ... |
| 201 | +} |
| 202 | +``` |
| 203 | + |
| 204 | +### 3. Real-time Updates |
| 205 | + |
| 206 | +SSE (Server-Sent Events) for order status updates: |
| 207 | + |
| 208 | +- Backend broadcasts order filled events |
| 209 | +- Frontend subscribes and updates UI in real-time |
| 210 | + |
| 211 | +### 4. Wallet Integration |
| 212 | + |
| 213 | +Porto wallet integration for: |
| 214 | + |
| 215 | +- User authentication |
| 216 | +- Transaction signing |
| 217 | +- Asset transfers |
| 218 | + |
| 219 | +## Testing Integration |
| 220 | + |
| 221 | +### Manual Testing |
| 222 | + |
| 223 | +1. **Order Creation:** |
| 224 | + |
| 225 | + - Connect wallet |
| 226 | + - Create order |
| 227 | + - Verify order appears in orderbook |
| 228 | + |
| 229 | +2. **Order Matching:** |
| 230 | + |
| 231 | + - Create opposite orders |
| 232 | + - Verify automatic matching |
| 233 | + - Check SSE notifications |
| 234 | + |
| 235 | +3. **Withdrawal:** |
| 236 | + - Wait for order expiry |
| 237 | + - Attempt withdrawal |
| 238 | + - Verify transaction |
| 239 | + |
| 240 | +### Automated Testing |
| 241 | + |
| 242 | +```bash |
| 243 | +# Backend tests |
| 244 | +cd crates/backend && cargo test |
| 245 | + |
| 246 | +# Frontend tests |
| 247 | +cd frontend && pnpm test |
| 248 | +``` |
| 249 | + |
| 250 | +## Troubleshooting |
| 251 | + |
| 252 | +### Common Issues |
| 253 | + |
| 254 | +1. **CORS Errors:** |
| 255 | + |
| 256 | + - Ensure backend CORS is configured |
| 257 | + - Check frontend API base URL |
| 258 | + |
| 259 | +2. **Type Mismatches:** |
| 260 | + |
| 261 | + - Verify Rust and TypeScript types match |
| 262 | + - Check field names (e.g., `asset_bought` vs `assert_bought`) |
| 263 | + |
| 264 | +3. **SSE Connection Issues:** |
| 265 | + |
| 266 | + - Verify backend SSE endpoint is running |
| 267 | + - Check browser console for connection errors |
| 268 | + |
| 269 | +4. **Wallet Connection:** |
| 270 | + - Ensure Porto wallet is properly configured |
| 271 | + - Check network configuration |
| 272 | + |
| 273 | +### Debug Mode |
| 274 | + |
| 275 | +Enable debug logging: |
| 276 | + |
| 277 | +```bash |
| 278 | +# Backend |
| 279 | +RUST_LOG=debug cargo run |
| 280 | + |
| 281 | +# Frontend |
| 282 | +NEXT_PUBLIC_DEBUG=true pnpm dev |
| 283 | +``` |
| 284 | + |
| 285 | +## Production Deployment |
| 286 | + |
| 287 | +### Environment Variables |
| 288 | + |
| 289 | +```bash |
| 290 | +# Backend |
| 291 | +PRIVATE_KEY=production_private_key |
| 292 | +RPC_URL=production_rpc_url |
| 293 | +PORT=3000 |
| 294 | + |
| 295 | +# Frontend |
| 296 | +NEXT_PUBLIC_API_URL=https://api.yourdomain.com |
| 297 | +NEXT_PUBLIC_CHAIN_ID=1 |
| 298 | +``` |
| 299 | + |
| 300 | +### Build Commands |
| 301 | + |
| 302 | +```bash |
| 303 | +# Production build |
| 304 | +npm run build |
| 305 | + |
| 306 | +# Docker deployment |
| 307 | +docker build -t trustee-dex . |
| 308 | +docker run -p 3000:3000 trustee-dex |
| 309 | +``` |
| 310 | + |
| 311 | +## Future Enhancements |
| 312 | + |
| 313 | +1. **Authentication:** |
| 314 | + |
| 315 | + - JWT tokens for API authentication |
| 316 | + - Session management |
| 317 | + |
| 318 | +2. **Rate Limiting:** |
| 319 | + |
| 320 | + - API rate limiting |
| 321 | + - Order submission throttling |
| 322 | + |
| 323 | +3. **Monitoring:** |
| 324 | + |
| 325 | + - Metrics collection |
| 326 | + - Error tracking |
| 327 | + - Performance monitoring |
| 328 | + |
| 329 | +4. **Security:** |
| 330 | + - Input validation |
| 331 | + - SQL injection prevention |
| 332 | + - XSS protection |
0 commit comments