Skip to content

Commit 8410a04

Browse files
authored
Merge pull request #1 from chainbound/nico/fixes
feat: vibe coded fixes
2 parents 3b510d8 + 461952a commit 8410a04

13 files changed

Lines changed: 4328 additions & 4398 deletions

File tree

INTEGRATION.md

Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
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

crates/backend/src/api/handlers.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ pub async fn create_encumbered_wallet(
6969
state.wallet_owners.insert(owner, address);
7070

7171
// Initialize empty balance for the wallet
72-
state.internal_balances.insert(address, dashmap::DashMap::new());
72+
// Note: InternalBalances doesn't need explicit initialization
7373

7474
Ok(Json(address))
7575
}
@@ -101,6 +101,9 @@ pub async fn create_order(
101101
status: OrderStatus::Open,
102102
};
103103

104+
// TODO: Get encumbered wallet from user's existing wallets or create new one
105+
// For now, use a placeholder - this needs to be implemented properly
106+
let encumbered_wallet = Address::from([0u8; 20]); // Placeholder
104107
state.add_order(order.clone(), encumbered_wallet, address)?;
105108

106109
// Trigger matching engine
@@ -156,14 +159,14 @@ pub async fn withdraw(
156159
return Err(AppError::BadRequest("No orders have reached expiry yet".to_string()));
157160
}
158161

159-
todo!("Verify, execute transaction, update state");
162+
// TODO: Implement withdrawal logic
160163
// In production, this would:
161164
// 1. Verify the signature
162165
// 2. Check balances in the encumbered wallet
163166
// 3. Execute the withdrawal transaction on-chain
164167
// 4. Update internal state
165168

166-
// Mock transaction hash
169+
// Mock transaction hash for now
167170
let tx_hash = TxHash::ZERO;
168171

169172
Ok(Json(TransactionResponse { tx_hash }))

crates/backend/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ use axum::{
44
routing::{delete, get, post},
55
Router,
66
};
7-
use backend::{api, AppState};
7+
use backend::{api, rpc::RpcClient, AppState};
88
use std::net::SocketAddr;
99
use tower_http::{
1010
cors::{Any, CorsLayer},
1111
trace::TraceLayer,
1212
};
1313
use tracing::info;
14-
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
14+
use tracing_subscriber::fmt;
1515

1616
#[tokio::main]
1717
async fn main() {

0 commit comments

Comments
 (0)