# Error Handling Source: https://api-docs.metadao.fi/advanced/error-handling Understanding and handling API errors ## Error Response Format All API errors follow a consistent JSON format: ```json theme={null} { "error": "Error message describing what went wrong" } ``` The HTTP status code indicates the error category, and the error message provides specific details. ## HTTP Status Codes ### Success Codes Request successful, data returned ### Client Error Codes The request was malformed or contains invalid parameters **Common causes:** * Missing required query parameters * Invalid ticker\_id format * Malformed request body The requested resource does not exist **Common causes:** * Invalid endpoint path * Ticker not found * DAO does not exist Rate limit exceeded **Details:** * Limit: 60 requests per minute per IP * Reset: Wait until the next minute window ### Server Error Codes An unexpected error occurred on the server **Common causes:** * RPC connection issues * Blockchain data unavailable * Service temporarily down Upstream service (RPC) is unavailable API is temporarily unavailable (maintenance or overload) ## Common Error Scenarios ### Rate Limit Exceeded When you exceed 60 requests per minute: ```json theme={null} { "error": "Rate limit exceeded. Please try again later." } ``` **Solution:** Wait 60 seconds before retrying Gradually increase wait time between retries Store frequently accessed data locally **Example Implementation:** ```javascript JavaScript theme={null} async function fetchWithRetry(url, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(url); if (response.status === 429) { const waitTime = Math.pow(2, i) * 1000; // Exponential backoff console.log(`Rate limited. Waiting ${waitTime}ms...`); await new Promise(resolve => setTimeout(resolve, waitTime)); continue; } if (!response.ok) { throw new Error(`HTTP ${response.status}: ${await response.text()}`); } return await response.json(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } } } // Usage const tickers = await fetchWithRetry('https://your-api-domain.com/api/tickers'); ``` ```python Python theme={null} import time import requests from typing import Optional, Dict def fetch_with_retry(url: str, max_retries: int = 3) -> Optional[Dict]: for i in range(max_retries): try: response = requests.get(url) if response.status_code == 429: wait_time = (2 ** i) * 1 # Exponential backoff print(f"Rate limited. Waiting {wait_time}s...") time.sleep(wait_time) continue response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: if i == max_retries - 1: raise e time.sleep(i + 1) return None # Usage tickers = fetch_with_retry('https://your-api-domain.com/api/tickers') ``` ### Ticker Not Found When requesting a specific ticker that doesn't exist: ```json theme={null} { "error": "Ticker not found: INVALID_MINT_ADDRESS" } ``` **Solutions:** * Verify the ticker\_id format: `{BASE_MINT}_{QUOTE_MINT}` * Ensure both mint addresses are valid Solana PublicKeys * Check if the DAO is excluded via `EXCLUDED_DAOS` * Verify the DAO has active pools with reserves ### RPC Connection Issues When the Solana RPC is unavailable: ```json theme={null} { "error": "Failed to fetch DAO data from blockchain" } ``` **Solutions:** Verify your RPC provider is operational Configure multiple RPC endpoints Use a premium RPC provider Implement automatic retry logic ### Invalid Configuration When required environment variables are missing: ```json theme={null} { "error": "FACTORY_ADDRESS not configured" } ``` **Solution:** Ensure all required environment variables are set in your `.env` file: ```env theme={null} FACTORY_ADDRESS=YOUR_FACTORY_PROGRAM_ID ROUTER_ADDRESS=YOUR_ROUTER_PROGRAM_ID ``` ## Error Handling Best Practices Never assume requests will succeed. Wrap all API calls in try-catch blocks. ```javascript theme={null} try { const data = await fetch('/api/tickers').then(r => r.json()); } catch (error) { console.error('API request failed:', error); // Handle error appropriately } ``` Set reasonable timeouts to prevent hanging requests. ```javascript theme={null} const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 10000); // 10s timeout try { const response = await fetch('/api/tickers', { signal: controller.signal }); clearTimeout(timeout); } catch (error) { if (error.name === 'AbortError') { console.error('Request timed out'); } } ``` Implement exponential backoff for transient errors. See code examples above for implementation details. Cache successful responses to reduce API load and improve resilience. ```javascript theme={null} const cache = new Map(); const CACHE_TTL = 10000; // 10 seconds async function getCached(url) { const cached = cache.get(url); if (cached && Date.now() - cached.timestamp < CACHE_TTL) { return cached.data; } const data = await fetch(url).then(r => r.json()); cache.set(url, { data, timestamp: Date.now() }); return data; } ``` Log all errors for debugging and monitoring. ```javascript theme={null} async function fetchAPI(url) { try { return await fetch(url).then(r => r.json()); } catch (error) { console.error({ timestamp: new Date().toISOString(), url, error: error.message, stack: error.stack }); throw error; } } ``` ## Monitoring API Health Use the health check endpoint to monitor API status: ```bash theme={null} curl https://your-api-domain.com/health ``` **Healthy Response:** ```json theme={null} { "status": "healthy", "timestamp": "2024-01-01T00:00:00.000Z", "uptime": 3600.5 } ``` Set up automated health checks every 1-5 minutes to detect issues early. ## Getting Support If you encounter persistent errors: Review API documentation for proper usage Report bugs or request features Get help from the community Check configuration settings ## Error Response Examples ```json 400 Bad Request theme={null} { "error": "Invalid ticker_id format. Expected: BASE_MINT_QUOTE_MINT" } ``` ```json 404 Not Found theme={null} { "error": "Endpoint not found: /api/invalid" } ``` ```json 429 Rate Limited theme={null} { "error": "Rate limit exceeded. Please try again later." } ``` ```json 500 Server Error theme={null} { "error": "Failed to fetch DAO data from blockchain" } ``` ```json 503 Service Unavailable theme={null} { "error": "Service temporarily unavailable. Please try again in a few moments." } ``` # API Overview Source: https://api-docs.metadao.fi/api-reference/overview Overview of the Futarchy CoinGecko-compatible DEX API ## What is This API? The Futarchy CoinGecko DEX API is a CoinGecko-compatible API that automatically discovers and aggregates all DAOs from the Futarchy protocol, providing real-time pricing and trading information. This API is fully compatible with CoinGecko's DEX API specification, making it easy to integrate with price aggregators and trading platforms. ## Base URL ``` https://market-api.metadao.fi ``` All API requests should be made to this base URL. ## Available Endpoints API information and available endpoints All DAO tickers with pricing and volume Token supply breakdown with allocation details Aggregate volume with daily breakdown Health check endpoint ### Supply Endpoints | Endpoint | Description | | ------------------------------------------ | -------------------------------------------------------------- | | `GET /api/supply/:mintAddress` | Returns complete supply breakdown with allocation details | | `GET /api/supply/:mintAddress/total` | Returns total supply only | | `GET /api/supply/:mintAddress/circulating` | Returns circulating supply (excludes team performance package) | ### Volume Endpoints | Endpoint | Description | | --------------------------- | ----------------------------------------------------------------------------- | | `GET /api/volume/aggregate` | Returns aggregate volume with daily breakdown for all DAO tokens since launch | ## Root Endpoint **Endpoint:** `GET /` Returns API information and available endpoints. **Response:** ```json theme={null} { "name": "Futarchy AMM - CoinGecko API", "version": "1.0.0", "documentation": "https://docs.coingecko.com/reference/exchanges-list", "endpoints": { "tickers": "/api/tickers - Returns all DAO tickers with pricing and volume", "supply": "/api/supply/:mintAddress - Returns complete supply breakdown with allocation details", "supply_total": "/api/supply/:mintAddress/total - Returns total supply only", "supply_circulating": "/api/supply/:mintAddress/circulating - Returns circulating supply (excludes team performance package)", "volume_aggregate": "/api/volume/aggregate - Returns aggregate volume with daily breakdown for all DAO tokens since launch", "health": "/health" }, "dex": { "fork_type": "Uniswap V1", "factory_address": "FUTARELBfJfQ8RDGhg1wdhddq1odMAJUePHFuBYfUxKq", "router_address": "FUTARELBfJfQ8RDGhg1wdhddq1odMAJUePHFuBYfUxKq" }, "supplyBreakdown": { "description": "For launchpad tokens, supply is broken down into:", "circulatingSupply": "Total supply minus team performance package (liquidity IS circulating)", "teamPerformancePackage": "Locked tokens allocated to the team (price-based unlock) - NOT circulating", "futarchyAmmLiquidity": "Tokens in the internal FutarchyAMM for spot trading - IS circulating", "meteoraLpLiquidity": "Tokens in the external Meteora DAMM pool (POL) - IS circulating" }, "note": "This API automatically discovers and aggregates all DAOs from the Futarchy protocol." } ``` **Example Request:** ```bash theme={null} curl https://market-api.metadao.fi/ ``` ## Health Endpoint **Endpoint:** `GET /health` Health check endpoint for monitoring API status. **Response:** ```json theme={null} { "status": "healthy", "timestamp": "2024-01-01T00:00:00.000Z", "uptime": 3600.5 } ``` **Response Fields:** Health status of the API. Always `"healthy"` when the endpoint responds successfully. Current server timestamp in ISO 8601 format. Server uptime in seconds. **Example Request:** ```bash theme={null} curl https://market-api.metadao.fi/health ``` Use this endpoint for automated health monitoring. Set up checks every 1-5 minutes to detect issues early. ## Key Features The API automatically discovers all DAOs from the Futarchy protocol without manual configuration. No need to maintain a list of DAOs - they're discovered dynamically from the blockchain. Prices are calculated from spot pool reserves in real-time, accounting for token decimal differences to ensure accuracy. Trading volumes are calculated from accumulated protocol fees, providing accurate volume metrics that reflect actual trading activity. Comprehensive liquidity information for all pools, calculated in USD for easy comparison. Built with Bun for exceptional performance, featuring intelligent caching (10s for tickers, 100s for metadata) and rate limiting. Fully compatible with CoinGecko's DEX API specification, making integration seamless with existing tools and platforms. ## Rate Limiting The API implements rate limiting to ensure fair usage: * **60 requests per minute** per IP address * Returns `429 Too Many Requests` when limit is exceeded * Rate limits reset at the start of each minute window ## Caching The API uses intelligent caching to balance freshness with performance: * **Tickers**: 10 seconds TTL * **Token Metadata**: 100 seconds TTL (longer cache for static data) ## Data Sources All data comes from on-chain sources: 1. **Solana Blockchain** - Pool reserves, DAO accounts, protocol fees 2. **Metaplex Token Metadata** - Token symbols, names, and metadata 3. **Spot Pools Only** - Prices calculated from spot pools, not conditional markets Prices are only calculated from spot pools, not conditional/futarchy pools, to ensure spot market accuracy. ## Response Format All endpoints return JSON responses. Error responses follow a consistent format: ```json theme={null} { "error": "Error message describing what went wrong" } ``` ## Next Steps Learn about the tickers API endpoint Get token supply information Understand how prices are calculated Get started with the API Configure your API instance Learn how to handle API errors # GET /api/supply Source: https://api-docs.metadao.fi/api-reference/supply GET /api/supply/:mintAddress Retrieve complete token supply breakdown with allocation details ## Overview The supply endpoints provide complete supply breakdown for launchpad tokens, including detailed allocation information for circulating supply, team performance packages, and liquidity positions. For launchpad tokens, circulating supply **excludes** the team performance package but **includes** all liquidity (both FutarchyAMM and Meteora DAMM). ## Supply Breakdown For launchpad tokens, supply is broken down into the following categories: | Category | Description | Circulating? | | ---------------------------- | -------------------------------------------------------- | ------------ | | **Circulating Supply** | Total supply minus team performance package | ✅ Yes | | **Team Performance Package** | Locked tokens allocated to the team (price-based unlock) | ❌ No | | **FutarchyAMM Liquidity** | Tokens in the internal FutarchyAMM for spot trading | ✅ Yes | | **Meteora LP Liquidity** | Tokens in the external Meteora DAMM pool (POL) | ✅ Yes | Liquidity tokens (both FutarchyAMM and Meteora) **are** counted as circulating supply since they can be traded. ## Endpoints | Endpoint | Description | | ------------------------------------------ | -------------------------------------------------------------- | | `GET /api/supply/:mintAddress` | Returns complete supply breakdown with allocation details | | `GET /api/supply/:mintAddress/total` | Returns total supply only | | `GET /api/supply/:mintAddress/circulating` | Returns circulating supply (excludes team performance package) | ## Full Supply Information **Endpoint:** `GET /api/supply/:mintAddress` Returns complete supply information for a token. ### Path Parameters The SPL token mint address (Solana PublicKey) Example: `METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta` ### Response The formatted total supply as a string Complete supply data object with allocation breakdown The token mint address Total token supply (formatted with decimals) Circulating token supply - excludes team performance package (formatted with decimals) Locked tokens allocated to the team with price-based unlock - NOT circulating Tokens in the internal FutarchyAMM for spot trading - IS circulating Tokens in the external Meteora DAMM pool (POL) - IS circulating Token decimal places Raw total supply without decimal formatting ### Example Request ```bash cURL theme={null} curl https://market-api.metadao.fi/api/supply/METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta ``` ```javascript JavaScript theme={null} const mintAddress = 'METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta'; const response = await fetch(`https://market-api.metadao.fi/api/supply/${mintAddress}`); const data = await response.json(); console.log(data); ``` ```python Python theme={null} import requests mint_address = 'METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta' response = requests.get(f'https://market-api.metadao.fi/api/supply/{mint_address}') data = response.json() print(data) ``` ### Example Response ```json theme={null} { "result": "1000000.0", "data": { "mint": "METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta", "totalSupply": "1000000.0", "circulatingSupply": "850000.0", "teamPerformancePackage": "150000.0", "futarchyAmmLiquidity": "200000.0", "meteoraLpLiquidity": "100000.0", "decimals": 9, "rawTotalSupply": "1000000000000000" } } ``` *** ## Total Supply Only **Endpoint:** `GET /api/supply/:mintAddress/total` Returns just the total supply value as a plain string. Useful for integrations that only need the total supply number. ### Example Request ```bash theme={null} curl https://market-api.metadao.fi/api/supply/METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta/total ``` ### Example Response ``` 1000000.0 ``` This endpoint returns a plain text response, not JSON, for easy integration with tools expecting a simple number. *** ## Circulating Supply Only **Endpoint:** `GET /api/supply/:mintAddress/circulating` Returns just the circulating supply value as a plain string. This value **excludes** the team performance package but **includes** all liquidity positions. **Circulating = Total Supply - Team Performance Package** Both FutarchyAMM liquidity and Meteora LP liquidity are included in circulating supply since these tokens are actively tradeable. ### Example Request ```bash theme={null} curl https://market-api.metadao.fi/api/supply/METAwkXcqyXKy1AtsSgJ8JiUHwGCafnZL38n3vYmeta/circulating ``` ### Example Response ``` 850000.0 ``` This endpoint returns a plain text response, not JSON, for easy integration with price aggregators like CoinGecko and CoinMarketCap. *** ## Use Cases CoinGecko and CoinMarketCap require supply endpoints for market cap calculations Display real-time supply metrics on token information pages Track supply changes over time for tokenomics analysis Calculate fully diluted valuations and token metrics ## Error Handling ### Invalid Mint Address ```json theme={null} { "error": "Invalid mint address" } ``` ### Mint Not Found ```json theme={null} { "error": "Token mint not found" } ``` ## Related Documentation Get pricing and volume data for all DAOs Get aggregate volume with daily breakdown Learn about the API architecture Handle API errors properly # GET /api/tickers Source: https://api-docs.metadao.fi/api-reference/tickers GET /api/tickers Retrieve all DAO tickers with pricing and volume information ## Overview The tickers endpoint returns comprehensive trading information for all DAOs discovered in the Futarchy protocol. This endpoint automatically discovers and aggregates data without requiring manual configuration. This endpoint is fully compatible with CoinGecko's DEX API specification. ## Request ```bash theme={null} GET /api/tickers ``` ### No Parameters Required This endpoint requires no query parameters. It automatically returns all active DAOs with valid pools. ## Response Unique identifier for the trading pair in format `{BASE_MINT}_{QUOTE_MINT}` Example: `"ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta_EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"` The base token mint address (Solana PublicKey) The quote token mint address, typically USDC The symbol of the base token (e.g., "ZKFG"). May be empty if metadata unavailable. The name of the base token. May be empty if metadata unavailable. The symbol of the quote token (e.g., "USDC") The name of the quote token (e.g., "USD Coin") The DAO address (Solana PublicKey) Current price of base token in terms of quote token (quote/base ratio) 24-hour trading volume in base token, calculated from protocol fees 24-hour trading volume in quote token, calculated from protocol fees Total pool liquidity in USD Best bid price (accounting for price impact) Best ask price (accounting for price impact) ## Example Request ```bash cURL theme={null} curl https://market-api.metadao.fi/api/tickers ``` ```javascript JavaScript theme={null} const response = await fetch('https://market-api.metadao.fi/api/tickers'); const tickers = await response.json(); console.log(tickers); ``` ```python Python theme={null} import requests response = requests.get('https://market-api.metadao.fi/api/tickers') tickers = response.json() print(tickers) ``` ```go Go theme={null} package main import ( "encoding/json" "fmt" "net/http" ) func main() { resp, err := http.Get("https://market-api.metadao.fi/api/tickers") if err != nil { panic(err) } defer resp.Body.Close() var tickers []map[string]interface{} json.NewDecoder(resp.Body).Decode(&tickers) fmt.Println(tickers) } ``` ## Example Response ```json theme={null} [ { "ticker_id": "ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta_EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_currency": "ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta", "target_currency": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_symbol": "ZKFG", "base_name": "ZKFG Token", "target_symbol": "USDC", "target_name": "USD Coin", "pool_id": "5FPGRzY9ArJFwY2Hp2y2eqMzVewyWCBox7esmpuZfCvE", "last_price": "0.081340728222", "base_volume": "30024.81040000", "target_volume": "2441.23456789", "liquidity_in_usd": "180138.45", "bid": "0.080934024581", "ask": "0.081747431863" }, { "ticker_id": "ANOTHER_TOKEN_MINT_ADDRESS_EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_currency": "ANOTHER_TOKEN_MINT_ADDRESS", "target_currency": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_symbol": "ABC", "base_name": "ABC Token", "target_symbol": "USDC", "target_name": "USD Coin", "pool_id": "ANOTHER_DAO_ADDRESS", "last_price": "1.234567", "base_volume": "15000.00", "target_volume": "18520.35", "liquidity_in_usd": "95000.00", "bid": "1.220000", "ask": "1.250000" } ] ``` ## Data Characteristics Prices are calculated from spot pool reserves only (not conditional/futarchy pools). **Formula:** `price = (quoteReserves / baseReserves) * 10^(baseDecimals - quoteDecimals)` This ensures accurate pricing regardless of token decimal differences. Volume is derived from accumulated protocol fees, providing accurate trading activity. **Formula:** `volume = protocolFees / feeRate` Uses the `PROTOCOL_FEE_RATE` configured in your environment (default: 0.25%). Liquidity is calculated as double the quote reserves (for stablecoin pairs). **Formula:** `liquidity = 2 * quoteReserves` Assumes symmetric liquidity for stablecoin-denominated pools. Bid and ask prices account for price impact from trading. These values represent realistic execution prices for small trades. ## Caching The API implements intelligent caching to optimize performance: * **Ticker data**: Cached for **10 seconds** to balance freshness with performance * **Token metadata**: Cached for **100 seconds** (longer cache for static data like symbols and names) Subsequent requests within the cache window return cached data instantly, reducing load on the Solana RPC and improving response times. ## Filtering DAOs can be excluded from results by adding their addresses to the `EXCLUDED_DAOS` environment variable. Only DAOs with: * Valid pool reserves (non-zero) * Accessible on-chain data * Not in the exclusion list will appear in the response. ## Rate Limiting This endpoint is subject to the global rate limit of **60 requests per minute** per IP address. ## Use Cases Integrate with price tracking platforms like CoinGecko Display real-time market data for all DAOs Analyze trading volumes and liquidity across DAOs Monitor prices for arbitrage opportunities ## Related Documentation Learn about the API architecture Understand how prices are calculated Configure your API instance Handle API errors properly # GET /api/volume/aggregate Source: https://api-docs.metadao.fi/api-reference/volume-aggregate GET /api/volume/aggregate Retrieve aggregate trading volume with daily breakdown for all DAO tokens ## Overview The volume aggregate endpoint returns comprehensive trading volume data for all DAO tokens since launch, including daily breakdowns for detailed analysis. This endpoint aggregates volume data across all DAOs, providing a complete picture of trading activity on the Futarchy protocol. ## Request ```bash theme={null} GET /api/volume/aggregate ``` ### No Parameters Required This endpoint requires no query parameters. It automatically returns aggregate volume data for all active DAOs. ## Response Total aggregate trading volume across all DAOs since launch (in USD) Array of daily volume records Date in ISO 8601 format (YYYY-MM-DD) Trading volume for that day (in USD) Number of trades executed that day Per-token volume breakdown Token mint address Token symbol Total volume for this token since launch ## Example Request ```bash cURL theme={null} curl https://market-api.metadao.fi/api/volume/aggregate ``` ```javascript JavaScript theme={null} const response = await fetch('https://market-api.metadao.fi/api/volume/aggregate'); const volumeData = await response.json(); console.log(volumeData); ``` ```python Python theme={null} import requests response = requests.get('https://market-api.metadao.fi/api/volume/aggregate') volume_data = response.json() print(volume_data) ``` ## Example Response ```json theme={null} { "totalVolume": "5234567.89", "dailyBreakdown": [ { "date": "2024-01-15", "volume": "125000.00", "trades": 342 }, { "date": "2024-01-14", "volume": "98500.50", "trades": 287 } ], "tokens": [ { "mint": "ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta", "symbol": "ZKFG", "totalVolume": "1250000.00" }, { "mint": "ANOTHER_TOKEN_MINT", "symbol": "ABC", "totalVolume": "875000.00" } ] } ``` ## Data Characteristics Volume is derived from accumulated protocol fees, providing accurate trading activity metrics. **Formula:** `volume = protocolFees / feeRate` Uses the protocol fee rate of 0.25% for calculations. Daily volume data is tracked since each DAO's launch date, providing historical trading patterns and trends. Volume is aggregated per token, making it easy to compare trading activity across different DAOs. ## Use Cases Display historical volume trends and trading patterns Analyze trading activity across the Futarchy ecosystem Track overall protocol health and growth Generate volume reports for stakeholders ## Rate Limiting This endpoint is subject to the global rate limit of **60 requests per minute** per IP address. ## Related Documentation Get real-time pricing and volume for all DAOs Get token supply breakdown information Learn about the API architecture # Price Calculation Source: https://api-docs.metadao.fi/concepts/pricing-methodology Understanding how prices are calculated in the Futarchy DEX API ## Overview The Futarchy DEX API calculates prices from on-chain spot pool reserves, ensuring accurate and real-time pricing data for all trading pairs. All prices are calculated from **spot pools only**, not conditional or futarchy markets. ## Price Formula The price calculation accounts for token decimal differences to provide accurate exchange rates: ``` price = (quoteReserves / baseReserves) × 10^(baseDecimals - quoteDecimals) ``` ### Components The amount of quote token (typically USDC) in the pool The amount of base token in the pool Number of decimal places for the base token (often 9 for Solana tokens) Number of decimal places for the quote token (6 for USDC) ## Example Calculation Let's calculate the price for a ZKFG/USDC pool: * Base reserves (ZKFG): 1,000,000 tokens * Quote reserves (USDC): 81,340 tokens * Base decimals (ZKFG): 9 * Quote decimals (USDC): 6 ``` price = (81,340 / 1,000,000) × 10^(9 - 6) price = 0.08134 × 10^3 price = 0.08134 × 1000 price = 81.34 ``` Wait, that's not right! Let's recalculate: ``` price = (81,340 / 1,000,000) × 10^(9 - 6) price = 0.08134 × 1000 price = 81.34 USDC per 1000 ZKFG ``` Actually, the correct interpretation: ``` price = 81,340 / (1,000,000 × 10^(9-6)) price = 81,340 / (1,000,000 × 1000) price ≈ 0.08134 USDC per ZKFG ``` The price of 1 ZKFG = 0.08134 USDC ## Why Decimal Adjustment Matters Without accounting for decimals, prices would be incorrect: ``` Simple ratio: 81,340 / 1,000,000 Result: 0.08134 Problem: Ignores decimal places ``` ``` Adjusted: 0.08134 × 10^3 Result: 0.08134 (correct) Accounts for decimal differences ``` ## Real-World Token Decimals Common token decimal configurations on Solana: | Token | Decimals | Example | | --------------- | -------- | ----------------------- | | USDC | 6 | 1,000,000 = 1 USDC | | USDT | 6 | 1,000,000 = 1 USDT | | SOL | 9 | 1,000,000,000 = 1 SOL | | Most SPL Tokens | 9 | 1,000,000,000 = 1 token | ## Bid and Ask Prices In addition to the last price, the API provides bid and ask prices: The **bid price** is the highest price a buyer is willing to pay. In the API, this accounts for: * Current pool reserves * Expected price impact from a small sell order * Slippage considerations ``` bid = last_price × (1 - small_price_impact) ``` The **ask price** is the lowest price a seller is willing to accept. This accounts for: * Current pool reserves * Expected price impact from a small buy order * Slippage considerations ``` ask = last_price × (1 + small_price_impact) ``` ## Price Updates Prices are updated in real-time as trades occur and pool reserves change. The API caches price data for **10 seconds** to balance freshness with performance: * **Cache Hit**: Returns cached price instantly * **Cache Miss**: Fetches fresh data from blockchain * **Pool Changes**: Triggers cache invalidation ## Data Sources All price data comes from: 1. **On-chain pool accounts** - Reserve balances 2. **Token metadata programs** - Decimal information 3. **Spot pools only** - Excludes conditional markets Prices from conditional markets or futarchy pools are **not included** in the price calculation to ensure spot market accuracy. ## Best Practices For current market price, use `last_price` field For execution estimates, use bid/ask spread Check liquidity\_in\_usd for price stability Always respect token decimal places in calculations ## Related Topics Access price data via API Configure your API instance Handle API errors properly Learn about the API architecture # Configuration Source: https://api-docs.metadao.fi/configuration Configure your Futarchy DEX API instance ## Environment Variables All configuration is managed through environment variables in your `.env` file. ### Quick Reference | Variable | Description | Default | Required | | ------------------- | ------------------------------------------------ | ------------------------------------- | -------- | | `SOLANA_RPC_URL` | Solana RPC endpoint URL | `https://api.mainnet-beta.solana.com` | Yes | | `SOLANA_WS_URL` | Solana WebSocket endpoint URL | `wss://api.mainnet-beta.solana.com` | No | | `PORT` | Server port | `3000` | No | | `NODE_ENV` | Node.js environment | `production` | No | | `DEX_FORK_TYPE` | DEX fork type identifier | `Custom` | Yes | | `FACTORY_ADDRESS` | Factory program address | (empty) | Yes | | `ROUTER_ADDRESS` | Router program address | (empty) | Yes | | `PROTOCOL_FEE_RATE` | Protocol fee rate for volume calculation | `0.0025` (0.25%) | No | | `EXCLUDED_DAOS` | Comma-separated list of DAO addresses to exclude | (empty) | No | ### Solana Configuration The Solana RPC endpoint URL for fetching blockchain data. **Recommendations:** * Use a dedicated RPC provider (e.g., Helius, QuickNode) for production * Public endpoints may be rate-limited ```env theme={null} SOLANA_RPC_URL=https://api.mainnet-beta.solana.com ``` The Solana WebSocket endpoint URL for real-time updates. ```env theme={null} SOLANA_WS_URL=wss://api.mainnet-beta.solana.com ``` ### Server Configuration The port on which the API server will listen. ```env theme={null} PORT=3000 ``` The Node.js environment. Options: `development`, `production`, `test` ```env theme={null} NODE_ENV=production ``` ### DEX Configuration The DEX fork type identifier for CoinGecko compatibility. **Supported Types:** * `Custom` (recommended for Futarchy) * `Uniswap V2`, `Uniswap V3`, `Uniswap V4` * `Raydium`, `Raydium CLMM` * `Orca` * See [full list](/configuration#supported-dex-forks) ```env theme={null} DEX_FORK_TYPE=Custom ``` The factory program address that creates and manages DAO instances. This must be a valid Solana program ID (PublicKey) ```env theme={null} FACTORY_ADDRESS=YOUR_FACTORY_PROGRAM_ID ``` The router program address for executing swaps. ```env theme={null} ROUTER_ADDRESS=YOUR_ROUTER_PROGRAM_ID ``` ### Protocol Configuration The protocol fee rate used for volume calculation. Default is 0.0025 (0.25%). **Formula:** `volume = protocolFees / feeRate` ```env theme={null} PROTOCOL_FEE_RATE=0.0025 ``` Comma-separated list of DAO addresses to exclude from the API responses. ```env theme={null} EXCLUDED_DAOS=DAO1_PUBLIC_KEY,DAO2_PUBLIC_KEY,DAO3_PUBLIC_KEY ``` ## Supported DEX Forks The following DEX fork types are supported for CoinGecko compatibility: * Uniswap V2, V3, V4 * Raydium * Raydium CLMM * Orca * Balancer V2, V3 * Curve * Algebra * Algebra Integral * Camelot V3 * Cetus * Iziswap * Kyberswap * Kyberswap Elastic * Quickswap V3 * Maverick V2 * Solidly V2, V3 * Traderjoe V2 * Velocore V2 * Ston.fi, Ston.fi V2 * Surge Protocol * Dedust * Ekubo * Jediswap * And more... ## Example Configuration Here's a complete example `.env` file: ```env theme={null} # Solana Configuration SOLANA_RPC_URL=https://rpc.helius.xyz/?api-key=YOUR_API_KEY SOLANA_WS_URL=wss://rpc.helius.xyz/?api-key=YOUR_API_KEY # Server Configuration PORT=3000 NODE_ENV=production # DEX Configuration DEX_FORK_TYPE=Custom FACTORY_ADDRESS=FACTgvmECoA8e8Y4h3cKfQcr45Rthxsix92YUJz1DiBk ROUTER_ADDRESS=RouTSKvxjyPNWvDCQkBq3cDPZcqEW3ZQRzDCJvxTBhQ # Protocol Configuration PROTOCOL_FEE_RATE=0.0025 # Optional: Exclude specific DAOs EXCLUDED_DAOS=11111111111111111111111111111111 ``` ## Validation The API validates all configuration on startup and will log warnings or errors for invalid settings. On startup, check the logs for: * ✅ RPC connection successful * ✅ Factory address valid * ✅ Router address valid * ⚠️ Any configuration warnings ## Production Recommendations Premium RPC providers offer higher rate limits and better reliability Ensure PROTOCOL\_FEE\_RATE matches your actual protocol fees Use health check endpoint to monitor API status Consider adding authentication for production deployments # Introduction Source: https://api-docs.metadao.fi/introduction Welcome to the Futarchy DEX API - A CoinGecko-compatible API for the Futarchy protocol ## What is Futarchy DEX API? The Futarchy DEX API is a CoinGecko-compatible DEX API that automatically discovers and aggregates all DAOs from the Futarchy protocol, providing real-time pricing and trading information. Get started with the API in minutes Explore all available endpoints Learn how to configure your API instance Understand how prices are calculated ## Key Features The API automatically discovers all DAOs from the Futarchy protocol without manual configuration. Get accurate real-time prices calculated from spot pool reserves with support for various token decimals. Trading volumes are calculated from protocol fees, providing accurate volume metrics. Access comprehensive liquidity information for all pools in USD. Built with Bun for exceptional performance with intelligent caching and rate limiting. ## Base URL ``` https://market-api.metadao.fi ``` All API requests should be made to this base URL. ## Available Endpoints | Endpoint | Description | | ------------------------------------------ | -------------------------------------------------------- | | `GET /` | API information and available endpoints | | `GET /api/tickers` | All DAO tickers with pricing and volume information | | `GET /api/supply/:mintAddress` | Complete supply breakdown with allocation details | | `GET /api/supply/:mintAddress/total` | Total supply only | | `GET /api/supply/:mintAddress/circulating` | Circulating supply (excludes team performance package) | | `GET /api/volume/aggregate` | Aggregate volume with daily breakdown for all DAO tokens | | `GET /health` | Health check endpoint for monitoring | See the [API Reference](/api-reference/overview) for detailed documentation on each endpoint. ## Response Format All endpoints return JSON responses. See the [API Reference](/api-reference/overview) for detailed response schemas. ## Rate Limits The API implements rate limiting of **60 requests per minute** per IP address to ensure fair usage and system stability. ## Getting Help Report bugs or request features Join our community for support # Quickstart Source: https://api-docs.metadao.fi/quickstart Get started with the Futarchy DEX API in under 5 minutes ## Installation ```bash theme={null} git clone https://github.com/metaDAOproject/futarchy-coingecko-api.git cd futarchy-coingecko-api ``` This project uses Bun for superior performance: ```bash theme={null} bun install ``` Create a `.env` file based on the example: ```bash theme={null} cp example.env .env ``` Edit `.env` with your configuration: ```env theme={null} SOLANA_RPC_URL=https://api.mainnet-beta.solana.com SOLANA_WS_URL=wss://api.mainnet-beta.solana.com PORT=3000 DEX_FORK_TYPE=Custom FACTORY_ADDRESS=YOUR_FACTORY_PROGRAM_ID ROUTER_ADDRESS=YOUR_ROUTER_PROGRAM_ID PROTOCOL_FEE_RATE=0.0025 ``` ```bash theme={null} bun run build bun start ``` For development with hot reload: ```bash theme={null} bun run dev ``` ## Make Your First Request You can use the live API directly or run your own instance locally. ### Using the Live API The public API is available at `https://market-api.metadao.fi`: ```bash theme={null} curl https://market-api.metadao.fi/ ``` This returns API information including version, available endpoints, and DEX configuration. ### Get Ticker Data Retrieve all DAO tickers with pricing and volume information: ```bash cURL theme={null} curl https://market-api.metadao.fi/api/tickers ``` ```javascript JavaScript theme={null} const response = await fetch('https://market-api.metadao.fi/api/tickers'); const data = await response.json(); console.log(data); ``` ```python Python theme={null} import requests response = requests.get('https://market-api.metadao.fi/api/tickers') data = response.json() print(data) ``` ### Local Development If running locally, replace `https://market-api.metadao.fi` with `http://localhost:3000` in the examples above. ## Example Response ```json theme={null} [ { "ticker_id": "ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta_EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_currency": "ZKFHiLAfAFMTcDAuCtjNW54VzpERvoe7PBF9mYgmeta", "target_currency": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "base_symbol": "ZKFG", "base_name": "ZKFG", "target_symbol": "USDC", "target_name": "USD Coin", "pool_id": "5FPGRzY9ArJFwY2Hp2y2eqMzVewyWCBox7esmpuZfCvE", "last_price": "0.081340728222", "base_volume": "30024.81040000", "target_volume": "2441.23456789", "liquidity_in_usd": "180138.45", "bid": "0.080934024581", "ask": "0.081747431863" } ] ``` ## Health Check Verify the API is running properly: ```bash theme={null} curl https://market-api.metadao.fi/health ``` Response: ```json theme={null} { "status": "healthy", "timestamp": "2024-01-01T00:00:00.000Z", "uptime": 3600.5 } ``` **Success!** Your API is now running and ready to serve data. ## Next Steps Learn about all configuration options Explore the tickers endpoint Learn how prices are calculated Learn how to handle errors