DOCUMENTATION.md
1 # f(x) Protocol REST API - Complete Documentation 2 3 **Version:** 1.0.0 4 **Last Updated:** December 29, 2025 5 **Framework:** FastAPI (Python) 6 **Production API:** https://fx-api-production.up.railway.app 7 8 --- 9 10 ## Table of Contents 11 12 1. [Overview](#overview) 13 2. [Quick Start](#quick-start) 14 3. [API Endpoints](#api-endpoints) 15 4. [Authentication & Security](#authentication--security) 16 5. [Rate Limiting](#rate-limiting) 17 6. [Error Handling](#error-handling) 18 7. [Performance Features](#performance-features) 19 8. [Transaction Flow](#transaction-flow) 20 9. [Examples](#examples) 21 10. [Deployment](#deployment) 22 23 --- 24 25 ## Overview 26 27 The f(x) Protocol REST API provides a comprehensive HTTP interface for interacting with the f(x) Protocol ecosystem. Built on FastAPI, it offers: 28 29 - **RESTful Design**: Clean, intuitive endpoint structure 30 - **Type Safety**: Pydantic models for request/response validation 31 - **Security First**: No private key handling - client-side signing required 32 - **High Performance**: Response caching and batch operations 33 - **Developer Friendly**: Auto-generated OpenAPI docs, helpful error messages 34 35 ### Key Features 36 37 - ✅ Complete read operations (balances, protocol info, Convex, Curve) 38 - ✅ Transaction preparation endpoints (unsigned transactions) 39 - ✅ Transaction broadcasting and tracking 40 - ✅ Response caching (30s for balances, 5min for protocol info) 41 - ✅ Batch operations for multiple addresses 42 - ✅ RPC fallback for reliability 43 - ✅ Enhanced error messages with context 44 - ✅ Gas estimation support 45 - ✅ Comprehensive health checks and metrics 46 47 --- 48 49 ## Quick Start 50 51 ### Production API 52 53 **Live API:** https://fx-api-production.up.railway.app 54 55 - **API Documentation:** https://fx-api-production.up.railway.app/docs 56 - **Health Check:** https://fx-api-production.up.railway.app/v1/health 57 58 ### Local Development 59 60 1. **Install dependencies:** 61 ```bash 62 pip install -r requirements.txt 63 ``` 64 65 2. **Set up environment variables:** 66 ```bash 67 cp .env.example .env 68 # Edit .env with your settings 69 ``` 70 71 3. **Run the API:** 72 ```bash 73 uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 74 ``` 75 76 4. **Access the API:** 77 - API: http://localhost:8000 78 - Docs: http://localhost:8000/docs 79 - Health: http://localhost:8000/v1/health 80 81 --- 82 83 ## API Endpoints 84 85 ### Health & Status 86 87 | Endpoint | Method | Description | 88 |----------|--------|-------------| 89 | `/v1/health` | GET | Basic health check | 90 | `/v1/status` | GET | Detailed API status with RPC connectivity | 91 | `/v1/health/detailed` | GET | Comprehensive health check with component status | 92 | `/v1/metrics` | GET | API metrics and statistics | 93 94 ### Balances 95 96 | Endpoint | Method | Description | 97 |----------|--------|-------------| 98 | `/v1/balances/{address}` | GET | Get all token balances for an address | 99 | `/v1/balances/batch` | POST | Get balances for multiple addresses | 100 | `/v1/balances/{address}/fxusd` | GET | Get fxUSD balance | 101 | `/v1/balances/{address}/fxn` | GET | Get FXN balance | 102 | `/v1/balances/{address}/feth` | GET | Get fETH balance | 103 | `/v1/balances/{address}/xeth` | GET | Get xETH balance | 104 | `/v1/balances/{address}/xcvx` | GET | Get xCVX balance | 105 | `/v1/balances/{address}/xwbtc` | GET | Get xWBTC balance | 106 | `/v1/balances/{address}/xeeth` | GET | Get xeETH balance | 107 | `/v1/balances/{address}/xezeth` | GET | Get xezETH balance | 108 | `/v1/balances/{address}/xsteth` | GET | Get xstETH balance | 109 | `/v1/balances/{address}/xfrxeth` | GET | Get xfrxETH balance | 110 | `/v1/balances/{address}/vefxn` | GET | Get veFXN balance | 111 | `/v1/balances/{address}/fxsave` | GET | Get fxSAVE balance | 112 | `/v1/balances/{address}/fxsp` | GET | Get fxSP balance | 113 | `/v1/balances/{address}/rusd` | GET | Get rUSD balance | 114 | `/v1/balances/{address}/arusd` | GET | Get arUSD balance | 115 | `/v1/balances/{address}/btcusd` | GET | Get btcUSD balance | 116 | `/v1/balances/{address}/cvxusd` | GET | Get cvxUSD balance | 117 | `/v1/balances/{address}/token/{token_address}` | GET | Get balance for any ERC-20 token | 118 119 ### Protocol Information 120 121 | Endpoint | Method | Description | 122 |----------|--------|-------------| 123 | `/v1/protocol/nav` | GET | Get protocol NAV (fETH/xETH) | 124 | `/v1/protocol/nav/batch` | POST | Get NAV for multiple tokens | 125 | `/v1/protocol/nav/{token}` | GET | Get NAV for specific token | 126 | `/v1/protocol/pool-info/{pool_address}` | GET | Get V2 pool manager info | 127 | `/v1/protocol/market-info/{market_address}` | GET | Get V1 market info | 128 | `/v1/protocol/treasury-info` | GET | Get stETH treasury info | 129 | `/v1/protocol/steth-price` | GET | Get stETH price | 130 | `/v1/protocol/fxusd/supply` | GET | Get fxUSD total supply | 131 | `/v1/protocol/v1/nav` | GET | Get V1 NAV | 132 | `/v1/protocol/v1/collateral-ratio` | GET | Get V1 collateral ratio | 133 | `/v1/protocol/v1/rebalance-pools` | GET | Get all V1 rebalance pools | 134 | `/v1/protocol/v1/rebalance-pool/{pool_address}/balances/{address}` | GET | Get rebalance pool balances | 135 | `/v1/protocol/peg-keeper` | GET | Get peg keeper info | 136 137 ### V2 Protocol 138 139 | Endpoint | Method | Description | 140 |----------|--------|-------------| 141 | `/v1/v2/pool/{pool_address}/info` | GET | Get V2 pool info | 142 | `/v1/v2/position/{position_id}/info` | GET | Get V2 position info | 143 | `/v1/v2/pool-manager/{pool_address}/info` | GET | Get pool manager info | 144 | `/v1/v2/reserve-pool/{token_address}/bonus-ratio` | GET | Get reserve pool bonus ratio | 145 146 ### Convex Finance 147 148 | Endpoint | Method | Description | 149 |----------|--------|-------------| 150 | `/v1/convex/pools` | GET | List all Convex pools (paginated) | 151 | `/v1/convex/pool/{pool_id}/info` | GET | Get Convex pool info | 152 | `/v1/convex/vault/{vault_address}/info` | GET | Get Convex vault info | 153 | `/v1/convex/vault/{vault_address}/balance` | GET | Get vault staked balance | 154 | `/v1/convex/vault/{vault_address}/rewards` | GET | Get claimable rewards | 155 | `/v1/convex/user/{address}/vaults` | GET | Get user's Convex vaults | 156 157 ### Curve Finance 158 159 | Endpoint | Method | Description | 160 |----------|--------|-------------| 161 | `/v1/curve/pools` | GET | List all Curve pools (paginated) | 162 | `/v1/curve/pool/{pool_address}/info` | GET | Get Curve pool info | 163 | `/v1/curve/gauge/{gauge_address}/balance` | GET | Get gauge staked balance | 164 | `/v1/curve/gauge/{gauge_address}/rewards` | GET | Get claimable rewards | 165 166 ### Gauges & Governance 167 168 | Endpoint | Method | Description | 169 |----------|--------|-------------| 170 | `/v1/gauges/{address}/all` | GET | Get all gauge balances for address | 171 | `/v1/gauges/{gauge_address}/weight` | GET | Get gauge weight | 172 | `/v1/gauges/{gauge_address}/relative-weight` | GET | Get gauge relative weight | 173 | `/v1/gauges/{gauge_address}/rewards/{address}` | GET | Get claimable rewards | 174 175 ### veFXN 176 177 | Endpoint | Method | Description | 178 |----------|--------|-------------| 179 | `/v1/vefxn/{address}/info` | GET | Get veFXN locked info | 180 181 ### Transactions 182 183 #### Broadcast 184 185 | Endpoint | Method | Description | 186 |----------|--------|-------------| 187 | `/v1/transactions/broadcast` | POST | Broadcast a signed transaction | 188 | `/v1/transactions/{tx_hash}/status` | GET | Get transaction status | 189 190 #### Prepare (Unsigned Transactions) 191 192 All prepare endpoints return unsigned transaction data that must be signed client-side. 193 194 **Minting:** 195 - `/v1/transactions/mint/f-token/prepare` - Mint f-token 196 - `/v1/transactions/mint/x-token/prepare` - Mint x-token 197 - `/v1/transactions/mint/both/prepare` - Mint both tokens 198 - `/v1/transactions/mint/treasury/prepare` - Mint via treasury 199 - `/v1/transactions/mint/f-token/gateway/prepare` - Mint f-token via gateway 200 - `/v1/transactions/mint/x-token/gateway/prepare` - Mint x-token via gateway 201 202 **Redemption:** 203 - `/v1/transactions/redeem/prepare` - Redeem tokens 204 - `/v1/transactions/redeem/treasury/prepare` - Redeem via treasury 205 206 **V1 Operations:** 207 - `/v1/transactions/v1/rebalance-pool/{pool_address}/deposit/prepare` - Deposit to rebalance pool 208 - `/v1/transactions/v1/rebalance-pool/{pool_address}/unlock/prepare` - Unlock from rebalance pool 209 - `/v1/transactions/v1/rebalance-pool/{pool_address}/withdraw/prepare` - Withdraw from rebalance pool 210 - `/v1/transactions/v1/rebalance-pool/{pool_address}/claim/prepare` - Claim from rebalance pool 211 212 **Savings & Stability Pool:** 213 - `/v1/transactions/savings/deposit/prepare` - Deposit to savings 214 - `/v1/transactions/savings/redeem/prepare` - Redeem from savings 215 - `/v1/transactions/stability-pool/deposit/prepare` - Deposit to stability pool 216 - `/v1/transactions/stability-pool/withdraw/prepare` - Withdraw from stability pool 217 218 **Vesting:** 219 - `/v1/transactions/vesting/{token_type}/claim/prepare` - Claim vesting (fxn, feth, fxusd) 220 221 **Advanced Operations:** 222 - `/v1/transactions/pool-manager/{pool_address}/harvest/prepare` - Harvest pool manager 223 - `/v1/transactions/reserve-pool/request-bonus/prepare` - Request bonus from reserve pool 224 - `/v1/transactions/swap/prepare` - Execute swap 225 - `/v1/transactions/flash-loan/prepare` - Execute flash loan 226 - `/v1/transactions/treasury/harvest/prepare` - Harvest treasury 227 228 **V2 Position Operations:** 229 - `/v1/transactions/positions/{position_id}/operate/prepare` - Operate position 230 - `/v1/transactions/positions/{position_id}/rebalance/prepare` - Rebalance position 231 - `/v1/transactions/positions/{position_id}/liquidate/prepare` - Liquidate position 232 233 **Gauge Operations:** 234 - `/v1/transactions/gauges/{gauge_address}/vote/prepare` - Vote on gauge 235 - `/v1/transactions/gauges/{gauge_address}/claim/prepare` - Claim gauge rewards 236 - `/v1/transactions/gauges/claim-all/prepare` - Claim all gauge rewards 237 238 **veFXN:** 239 - `/v1/transactions/vefxn/deposit/prepare` - Deposit FXN to veFXN 240 241 **Token Operations:** 242 - `/v1/transactions/approve/prepare` - Approve token spending 243 - `/v1/transactions/transfer/prepare` - Transfer tokens 244 245 --- 246 247 ## Authentication & Security 248 249 ### Client-Side Signing 250 251 The API **never handles private keys**. All transactions follow this secure flow: 252 253 1. **Client Builds Transaction**: Using SDK or web3 library 254 2. **Client Signs Offline**: Private key never leaves client device 255 3. **API Broadcasts**: API only receives and broadcasts signed transaction 256 4. **Transaction Tracking**: Status can be queried after broadcast 257 258 ### Input Validation 259 260 - **Pydantic Models**: Type-safe request/response validation 261 - **Address Validation**: Ethereum address format checking (EIP-55 checksum) 262 - **Amount Validation**: Non-negative, properly formatted amounts 263 - **Clear Error Messages**: Helpful validation error responses 264 265 --- 266 267 ## Rate Limiting 268 269 ### Free Tier (All Users) 270 271 - **Per Minute**: 100 requests 272 - **Per Hour**: 5,000 requests 273 - **Per Day**: 50,000 requests 274 275 ### Rate Limit Headers 276 277 All responses include rate limit information: 278 - `X-RateLimit-Limit-Minute` 279 - `X-RateLimit-Limit-Hour` 280 - `X-RateLimit-Limit-Day` 281 - `X-RateLimit-Remaining-*` 282 - `Retry-After` (when limit exceeded) 283 284 ### Rate Limit Exceeded 285 286 When rate limit is exceeded, you'll receive: 287 - HTTP 429 status code 288 - Error message with retry time 289 - `Retry-After` header with seconds to wait 290 291 --- 292 293 ## Error Handling 294 295 ### Error Response Format 296 297 ```json 298 { 299 "error": true, 300 "code": "ERROR_CODE", 301 "message": "Human-readable error message" 302 } 303 ``` 304 305 ### Common Error Codes 306 307 - `INVALID_ADDRESS` - Invalid Ethereum address format 308 - `INVALID_AMOUNT` - Invalid amount format or value 309 - `CONTRACT_CALL_ERROR` - Error calling smart contract 310 - `TRANSACTION_FAILED` - Transaction failed on blockchain 311 - `RATE_LIMIT_EXCEEDED` - Rate limit exceeded 312 - `INTERNAL_ERROR` - Server-side error 313 314 ### Enhanced Error Messages 315 316 Error messages include: 317 - **Helpful Context**: Suggestions and context 318 - **Documentation Links**: Direct links to relevant docs 319 - **Validation Details**: Detailed validation error messages 320 - **Error Codes**: Consistent error codes for programmatic handling 321 322 --- 323 324 ## Performance Features 325 326 ### Response Caching 327 328 - **In-Memory Caching**: Fast, efficient caching for read operations 329 - **TTL-Based Expiration**: 330 - Balances: 30 seconds 331 - Protocol info: 5 minutes 332 - **Automatic Cache Management**: Expired entries are automatically cleaned up 333 - **Cache Statistics**: Track cache hits/misses via metrics endpoint 334 335 ### Batch Operations 336 337 - **Batch Balances**: Query multiple addresses in one request (`POST /v1/balances/batch`) 338 - **Batch NAV**: Query multiple token NAVs in one request (`POST /v1/protocol/nav/batch`) 339 - **Parallel Processing**: Batch requests are processed concurrently 340 - **Reduced HTTP Overhead**: Fewer round trips for multiple queries 341 342 ### RPC Fallback 343 344 - **Multiple RPC Endpoints**: Automatic fallback to backup RPCs 345 - **Health Monitoring**: RPC connectivity is continuously monitored 346 - **Graceful Degradation**: API continues operating even if some RPCs fail 347 348 ### Gas Estimation 349 350 - **Optional Gas Estimation**: Request gas estimates for prepare endpoints 351 - **Cost Calculation**: Estimated total gas cost in Wei 352 - **Query Parameter**: Add `?estimate_gas=true&from_address=...` to any prepare endpoint 353 354 --- 355 356 ## Transaction Flow 357 358 ### Complete Transaction Flow 359 360 1. **Prepare Transaction**: Call prepare endpoint to get unsigned transaction data 361 2. **Sign Locally**: Sign transaction using your private key (never send to API) 362 3. **Broadcast**: Send signed transaction to `/v1/transactions/broadcast` 363 4. **Track Status**: Query `/v1/transactions/{tx_hash}/status` for confirmation 364 365 ### Example Flow 366 367 ```python 368 # 1. Prepare transaction 369 response = requests.post( 370 "https://fx-api-production.up.railway.app/v1/transactions/mint/f-token/prepare", 371 json={ 372 "market_address": "0x...", 373 "base_in": "1000000000000000000", 374 "wallet_address": "0x..." 375 } 376 ) 377 unsigned_tx = response.json()["transaction"] 378 379 # 2. Sign locally (using web3.py, ethers.js, etc.) 380 signed_tx = sign_transaction(unsigned_tx, private_key) 381 382 # 3. Broadcast 383 broadcast_response = requests.post( 384 "https://fx-api-production.up.railway.app/v1/transactions/broadcast", 385 json={"signed_transaction": signed_tx} 386 ) 387 tx_hash = broadcast_response.json()["transaction_hash"] 388 389 # 4. Track status 390 status_response = requests.get( 391 f"https://fx-api-production.up.railway.app/v1/transactions/{tx_hash}/status" 392 ) 393 status = status_response.json()["status"] 394 ``` 395 396 --- 397 398 ## Examples 399 400 ### Get All Balances 401 402 ```bash 403 curl https://fx-api-production.up.railway.app/v1/balances/0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb 404 ``` 405 406 ### Get Protocol NAV 407 408 ```bash 409 curl https://fx-api-production.up.railway.app/v1/protocol/nav 410 ``` 411 412 ### Batch Query Balances 413 414 ```bash 415 curl -X POST https://fx-api-production.up.railway.app/v1/balances/batch \ 416 -H "Content-Type: application/json" \ 417 -d '{ 418 "addresses": [ 419 "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", 420 "0x1234567890123456789012345678901234567890" 421 ] 422 }' 423 ``` 424 425 ### Prepare Mint Transaction 426 427 ```bash 428 curl -X POST https://fx-api-production.up.railway.app/v1/transactions/mint/f-token/prepare \ 429 -H "Content-Type: application/json" \ 430 -d '{ 431 "market_address": "0x...", 432 "base_in": "1000000000000000000", 433 "wallet_address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" 434 }' 435 ``` 436 437 ### Broadcast Signed Transaction 438 439 ```bash 440 curl -X POST https://fx-api-production.up.railway.app/v1/transactions/broadcast \ 441 -H "Content-Type: application/json" \ 442 -d '{ 443 "signed_transaction": "0x..." 444 }' 445 ``` 446 447 ### Get Transaction Status 448 449 ```bash 450 curl https://fx-api-production.up.railway.app/v1/transactions/0x.../status 451 ``` 452 453 --- 454 455 ## Deployment 456 457 ### Railway Deployment 458 459 The production API is deployed on Railway. See `RAILWAY_DEPLOYMENT.md` for details. 460 461 ### Environment Variables 462 463 Key environment variables: 464 - `RPC_URLS` - Comma-separated list of RPC endpoints 465 - `RATE_LIMIT_PER_MINUTE` - Rate limit per minute (default: 100) 466 - `RATE_LIMIT_PER_HOUR` - Rate limit per hour (default: 5000) 467 - `RATE_LIMIT_PER_DAY` - Rate limit per day (default: 50000) 468 - `ALLOWED_ORIGINS` - CORS allowed origins (default: "*") 469 470 See `.env.example` for all available configuration options. 471 472 --- 473 474 ## Documentation 475 476 ### Interactive Documentation 477 478 - **Swagger UI**: `/docs` - Full interactive API explorer 479 - **ReDoc**: `/redoc` - Alternative documentation format 480 - **OpenAPI JSON**: `/openapi.json` - Machine-readable schema 481 482 ### Response Headers 483 484 All responses include: 485 - `X-Request-ID` - Unique identifier for each request 486 - `X-Process-Time` - Request processing time in seconds 487 - `X-RateLimit-*` - Rate limit information 488 489 --- 490 491 ## Support 492 493 For issues, questions, or contributions: 494 - **GitHub**: https://github.com/chrisstampar/fx-api 495 - **API Health**: https://fx-api-production.up.railway.app/v1/health 496 - **Interactive Docs**: https://fx-api-production.up.railway.app/docs 497 498 **Note**: This API is designed to be free for all users with no paid tiers. Rate limits are generous and should accommodate most use cases. 499