This guide provides comprehensive configuration instructions for all API endpoints in the GXQ Studio platform.
api/
├── middleware/
│ ├── validation.ts # Input validation
│ ├── errorHandler.ts # Error handling
│ ├── cors.ts # CORS configuration
│ └── index.ts # Middleware exports
├── admin/
│ ├── auth.ts # Authentication
│ ├── metrics.ts # Performance metrics
│ ├── control.ts # Bot control
│ └── logs.ts # Log access
├── health.ts # Health checks
├── monitor.ts # Opportunity monitoring
├── execute.ts # Trade execution
└── walletAnalysisEndpoints.ts # Wallet analysis
Purpose: Monitor system health and status
Method: GET
Authentication: None
Configuration:
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
WALLET_PRIVATE_KEY=your_base58_private_keyResponse:
{
"status": "healthy",
"rpcLatency": 150,
"walletBalance": 1.5,
"walletAddress": "...",
"jupiterApiStatus": "online",
"uptime": 3600,
"errorRate": 0.5,
"timestamp": 1703001234567
}Status Codes:
200- Healthy503- Degraded/Unhealthy
Rate Limit: 60 requests/minute
Purpose: Scan for arbitrage opportunities
Method: GET
Authentication: Cron secret (optional)
Configuration:
SOLANA_RPC_URL=required
MINIMUM_PROFIT_SOL=0.01
CRON_SECRET=optional_secretHeaders:
Authorization: Bearer ${CRON_SECRET} # Optional
Response:
{
"success": true,
"opportunitiesFound": 5,
"topOpportunity": {
"id": "opp_123",
"type": "arbitrage",
"estimatedProfit": 0.025,
"confidence": 85
},
"scanDuration": 1234,
"timestamp": 1703001234567
}Rate Limit: 10 requests/minute
Cron Schedule: Every 1 minute
Purpose: Execute pending arbitrage trades
Method: POST
Authentication: Cron secret (optional)
Configuration:
SOLANA_RPC_URL=required
WALLET_PRIVATE_KEY=required
MINIMUM_PROFIT_SOL=0.01
MAX_SLIPPAGE=0.01
CRON_SECRET=optional_secretResponse:
{
"success": true,
"tradesExecuted": 3,
"successCount": 2,
"failCount": 1,
"totalProfit": 0.045,
"transactions": [...],
"timestamp": 1703001234567
}Rate Limit: 5 requests/minute
Cron Schedule: Every 5 minutes
Purpose: Admin panel login
Method: POST
Authentication: None (creates JWT)
Configuration:
ADMIN_USERNAME=required
ADMIN_PASSWORD=required (plain or bcrypt hash)
JWT_SECRET=required (32+ characters)Request Body:
{
"username": "admin",
"password": "your_password"
}Response:
{
"success": true,
"token": "eyJhbGc...",
"expiresIn": 86400
}Rate Limit: 5 requests/15 minutes
Security:
- Use bcrypt hashed passwords in production
- Rotate JWT_SECRET regularly
- Monitor failed login attempts
Purpose: View trading metrics and statistics
Method: GET
Authentication: JWT Bearer token
Headers:
Authorization: Bearer ${JWT_TOKEN}
Response:
{
"success": true,
"metrics": {
"profitToday": 0.5,
"profitWeek": 2.5,
"profitMonth": 10.0,
"tradesCount": 150,
"successRate": 85.5,
"avgProfit": 0.035,
"opportunities24h": 45,
"rpcHealth": {...},
"activeStrategies": ["arbitrage"],
"liveOpportunities": [...]
},
"timestamp": 1703001234567
}Rate Limit: 30 requests/minute
Purpose: Control bot operations
Method: POST
Authentication: JWT Bearer token
Configuration:
MINIMUM_PROFIT_SOL=configurable
MAX_SLIPPAGE=configurableRequest Body:
{
"command": "start|stop|pause|resume|emergency-stop|get-status|update-config",
"config": {
"minProfit": 0.01,
"slippage": 0.01,
"enabledStrategies": ["arbitrage"],
"maxGasPrice": 10000
}
}Commands:
start- Start the botstop- Stop the botpause- Pause executionresume- Resume from pauseemergency-stop- Immediate stopget-status- Get current statusupdate-config- Update configuration
Response:
{
"success": true,
"message": "Bot started successfully",
"currentStatus": {
"running": true,
"paused": false,
"uptime": 3600,
"currentStrategy": "arbitrage"
}
}Rate Limit: 30 requests/minute
Purpose: Analyze Solana wallets
Method: POST
Authentication: Optional
Configuration:
SOLANA_RPC_URL=required
NEYNAR_API_KEY=optional (for Farcaster integration)Request Body:
{
"walletAddress": "...",
"includeSocial": true,
"saveToDatabase": false
}Rate Limit: 20 requests/minute
# Solana (Required for all endpoints)
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
WALLET_PRIVATE_KEY=your_base58_private_key
# Admin Panel (Required for admin endpoints)
ADMIN_USERNAME=admin
ADMIN_PASSWORD=strong_password
JWT_SECRET=your_32_character_secret
# Trading Configuration (Required for execute/monitor)
MINIMUM_PROFIT_SOL=0.01
MAX_SLIPPAGE=0.01
GAS_BUFFER=1.5
# Security (Optional but recommended)
CRON_SECRET=your_cron_secret
# Features (Optional)
NEYNAR_API_KEY=your_neynar_keyDevelopment:
- Allows all origins
- All methods enabled
- No credentials required
Production:
- Whitelist specific domains
- Limited methods (GET, POST, OPTIONS)
- Credentials enabled
Configure in: api/middleware/cors.ts
export const productionCorsOptions: CorsOptions = {
origin: (origin: string) => {
const allowedDomains = [
'https://TradeOS.vercel.app',
'https://gxq-studio.vercel.app',
];
return allowedDomains.some(domain => origin.startsWith(domain));
},
};Configure per endpoint or globally:
import { checkRateLimit } from './middleware/validation';
const rateLimit = checkRateLimit(
getClientIp(req),
60, // max requests
60000 // window in ms (1 minute)
);
if (!rateLimit.allowed) {
return res.status(429).json({
error: 'Rate limit exceeded',
resetIn: rateLimit.resetIn,
});
}✅ Never commit .env files
✅ Use different secrets per environment
✅ Rotate secrets regularly
✅ Use strong, random values
✅ Minimum 32 characters for JWT_SECRET
✅ Use bcrypt for password hashing ✅ Implement rate limiting on auth endpoints ✅ Use JWT with expiration ✅ Validate tokens on every request ✅ Never log passwords or tokens
✅ Validate all user input ✅ Use type-safe validation ✅ Sanitize HTML and scripts ✅ Validate Solana addresses ✅ Check array/object sizes
✅ Never expose stack traces ✅ Use consistent error format ✅ Log errors with context ✅ Return generic messages to users ✅ Monitor error rates
✅ Enable CORS with whitelist ✅ Implement rate limiting ✅ Use HTTPS in production ✅ Add request logging ✅ Monitor for abuse
# Start local server
npm run dev
# Test health endpoint
curl http://localhost:3000/api/health
# Test auth endpoint
curl -X POST http://localhost:3000/api/admin/auth \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}'
# Test protected endpoint
curl http://localhost:3000/api/admin/metrics \
-H "Authorization: Bearer YOUR_JWT_TOKEN"# Run endpoint validation
npm run validate-endpoints http://localhost:3000
# Run with custom base URL
npm run validate-endpoints https://your-domain.vercel.app# Test production health
curl https://your-domain.vercel.app/api/health
# Monitor continuously
watch -n 5 'curl -s https://your-domain.vercel.app/api/health | jq'Add to each endpoint:
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
console.log('IP:', getClientIp(req));
console.log('Body:', req.body);Track these metrics:
- Request rate per endpoint
- Response times
- Error rates
- Rate limit hits
- Authentication failures
- RPC latency
Set up alerts for:
- Error rate > 5%
- Response time > 2 seconds
- Rate limit hits > 100/hour
- Failed auth attempts > 10/hour
- Low wallet balance < 0.01 SOL
Issue: 401 Unauthorized Solution: Check JWT token validity and ADMIN_USERNAME/PASSWORD
Issue: 429 Rate Limit Exceeded Solution: Wait for reset time or adjust rate limits
Issue: 503 Service Unavailable Solution: Check RPC connection and wallet balance
Issue: CORS Errors Solution: Add your domain to allowed origins in cors.ts
Issue: Slow Responses Solution: Check RPC latency and consider using premium RPC
Enable verbose logging:
LOG_LEVEL=debug
NODE_ENV=developmentCheck these in order:
- RPC URL accessible
- Wallet private key valid
- Environment variables set
- Jupiter API accessible
- Sufficient wallet balance
File: vercel.json
{
"functions": {
"api/**/*.ts": {
"runtime": "nodejs18.x",
"maxDuration": 60,
"memory": 1024
}
},
"crons": [
{
"path": "/api/monitor",
"schedule": "*/1 * * * *"
},
{
"path": "/api/execute",
"schedule": "*/5 * * * *"
}
]
}File: railway.json
{
"deploy": {
"healthcheckPath": "/api/health",
"healthcheckTimeout": 30
}
}- ✅ Configure environment variables
- ✅ Test all endpoints locally
- ✅ Deploy to staging
- ✅ Run automated validation
- ✅ Monitor for errors
- ✅ Deploy to production
- ✅ Set up monitoring alerts