API Authentication

The APY Calculator API currently operates as an open API without authentication requirements. This design choice prioritizes accessibility and ease of integration for developers while maintaining service reliability through other protective mechanisms

CORS Policy

The API implements comprehensive Cross-Origin Resource Sharing (CORS) settings to maximize compatibility across different client environments:
allow_origins=["*"]           # Accepts requests from any domain
allow_credentials=True        # Supports cookies and authentication headers
allow_methods=["GET", "POST"] # Supports primary HTTP methods
allow_headers=["*"]           # Accepts any request headers
This configuration allows requests from any origin, making it suitable for frontend integrations and testing Security Considerations:
  • While permissive, the API relies on input validation and rate limiting for protection
  • No sensitive authentication data is exposed due to the open access model
  • All requests are logged with unique identifiers for monitoring

Request Identification

While authentication is not required, each request receives a unique identifier for tracking and debugging purposes:
X-Request-ID: uuid4-generated-string
This header is automatically added to all responses and can be used for support inquiries

Rate Limits and Usage Constraints

The API implements intelligent constraints designed to balance performance, reliability, and fair resource allocation across all users

Input Amount Validation

Diluted APY Calculations:
  • Constraint: Input amounts must be non-negative integers (≥ 0)
  • Rationale: Negative amounts would produce meaningless yield calculations
  • Validation: Performed at the endpoint level before processing
  • Error Response: Returns 422 status with validation_error type
Example Valid Inputs:
{
  "input_amount": 1000, // ✅ Valid
  "input_amount": 0, // ✅ Valid (edge case)
  "input_amount": 1000000000 // ✅ Valid (large amounts supported)
}
Invalid Examples:
{
  "input_amount": -100, // ❌ Negative value
  "input_amount": 1000.5, // ❌ Decimal value
  "input_amount": "1000" // ❌ String format
}

Batch Processing Limits

Maximum Multicall Size: 30 calls per batch request Technical Reasoning:
  • Timeout Prevention: Larger batches risk exceeding response time limits
  • Memory Management: Prevents excessive memory allocation per request
  • Fair Resource Distribution: Ensures no single request monopolizes system resources
Optimal Batch Strategies:
  • Group related calculations (same protocol/chain) for better caching efficiency
  • Split large datasets into multiple sequential batch requests
  • Implement client side batching logic for datasets exceeding 30 items

Blockchain Support

The API provides comprehensive coverage across major EVM-compatible networks, with standardized naming conventions and aliases for developer convenience
  • Ethereum (ethereum)
  • Base (base)
  • Arbitrum (arbitrum)
  • BNB Chain (bnb, binance smart chain, bsc)
  • Avalanche (avalanche)
  • Gnosis (gnosis)
  • Polygon (polygon)
  • Optimism (optimism)
  • Mantle (mantle)
  • Linea (linea)
  • Scroll (scroll)
  • Taiko (taiko)
  • Blast (blast)
  • Sonic (sonic)
  • Berachain (berachain)
  • Unichain (unichain)
  • HyperEVM (hyperevm)

Timeout Configurations

The API implements environment-aware timeout settings optimized for different deployment contexts
Operation TypeProduction TimeoutLocal Timeout
Liquidity States1s20s
Dependent States1s20s
Timeout Strategy:
  • Production: Aggressive timeouts ensure responsive user experience
  • Development: Extended timeouts accommodate debugging and testing
  • Automatic Failover: Requests failing due to timeouts trigger retry mechanisms where applicable

Cache Configuration

The API employs multi-tiered caching for optimal performance and resource utilization
  • Cache Size: 10,000 entries maximum
  • Cache TTL: 300 seconds (5 minutes)
  • APY Cache: 3,600 seconds (1 hour)

System Resource Limits

The API implements dynamic resource monitoring with automatic request rejection when system constraints are exceeded
  • CPU Usage: Above 95%
  • Memory Usage: Above 95%
  • Error Rate: Above 75% (when total requests > 10)

Error Handling

The API provides comprehensive error handling with structured responses designed for both human debugging and programmatic error recovery

Error Format

All API errors follow a consistent, machine-readable JSON structure that provides multiple levels of diagnostic information:
{
  "success": false,
  "error": "Error message description",
  "error_type": "error_category",
  "step": "operation_step",
  "request_id": "uuid4-request-identifier"
}
Field Descriptions:
  • success: Always false for error responses (enables quick programmatic checks)
  • error: Human readable message suitable for logging and debugging
  • error_type: Standardized category for programmatic error handling
  • step: Specific operation stage where failure occurred
  • request_id: Unique identifier for support and debugging correlation

Error Types

Validation Errors

HTTP Status Code: 422 Unprocessable Entity Error Type: validation_error These errors occur during input parameter validation before any processing begins. They indicate client-side issues that require request modification
{
  "success": false,
  "error": "pool_address must be a valid Ethereum address (0x...)",
  "error_type": "validation_error",
  "step": "input_validation"
}
Common validation errors
  • Invalid Ethereum addresses (must be 42 characters with 0x prefix)
  • Unsupported blockchain networks
  • Missing required parameters (pool_address or lp_token_address)
  • Invalid input amounts (negative values)
  • Input token same as LP token

Calculation Errors

HTTP Status Code: 404 Not Found Error Type: calculation_failed These errors occur when the API successfully validates inputs but cannot complete the requested calculation due to missing data or computational issues
{
  "success": false,
  "error": "Pool data not found for pool_address=0x... in chain ethereum",
  "error_type": "calculation_failed",
  "step": "pool_data_retrieval"
}
Common calculation errors:
  • Pool not found in database
  • Incomplete pool states
  • Missing protocol modules
  • Network timeout during state calls

Internal Server Errors

HTTP Status Code: 500 Internal Server Error Error Type: internal_error System level errors:
{
  "success": false,
  "error": "Database connectivity failed",
  "error_type": "internal_error",
  "request_id": "abc123-def456-ghi789"
}

Service Unavailable

HTTP Status Code: 503 Service Unavailable Error Type: startup_error or resource_exhaustion Service initialization failures:
{
  "success": false,
  "error": "Service initialization failed",
  "error_type": "startup_error"
}

Database Errors

Database connectivity issues are handled gracefully:
{
  "success": false,
  "error": "Database error during pool_address lookup: Connection timeout",
  "error_type": "calculation_failed",
  "step": "pool_data_retrieval"
}

Network and Timeout Errors

Blockchain network calls may timeout:
{
  "success": false,
  "error": "Timeout during state calls",
  "error_type": "calculation_failed",
  "step": "state_calls_timeout"
}

Error Step Mapping

Common Steps

  • input_validation: Parameter validation failed
  • pool_data_retrieval: Cannot fetch pool data from database
  • protocol_id_validation: Missing or invalid protocol identifier
  • module_import_failed: Cannot load required blockchain modules
  • initialization_failed: Pool initialization error

APY Calculation Steps

  • input_token_validation: Invalid input token address
  • lp_token_validation: Input token conflicts with LP token
  • apy_calculation_error: Mathematical calculation failed
  • states_incomplete: Required blockchain states not available

TVL Calculation Steps

  • tvl_calculation_error: TVL computation failed
  • pool_creation_failed: Cannot instantiate pool object

Health Monitoring

The API provides comprehensive health monitoring capabilities designed for both operational oversight and integration into larger monitoring ecosystems

Health Check Endpoint

Endpoint: GET /health-check Purpose: Comprehensive system validation suitable for load balancer health checks and monitoring systems
  • Router initialization status
  • Database connectivity
  • Error rate analysis (must be < 75%)
  • System resource usage (CPU and memory < 95%)

Metrics Monitoring

Endpoint: GET /metrics Purpose: Detailed performance and operational metrics for observability and optimization Response Format:
{
  "success": true,
  "request_metrics": {
    "total_requests": 1000,
    "cache_hit_rate_percent": 85.5,
    "error_rate_percent": 2.1,
    "avg_response_time_seconds": 0.245
  },
  "system_metrics": {
    "cpu_usage_percent": 45.2,
    "memory_usage_percent": 68.1,
    "pending_tasks": 3,
    "cache_size": 150,
    "uptime_seconds": 86400
  }
}

Best Practices

Error Handling in Client Applications

  1. Always check the success field before processing response data
  2. Use error_type for programmatic error handling rather than parsing error messages
  3. Include request_id in support requests for faster debugging
  4. Implement retry logic for timeout and network errors
  5. Cache successful responses to reduce API load

Request Optimization

  1. Use caching: Identical requests within 5 minutes return cached results
  2. Validate addresses client-side: Ensure Ethereum addresses are properly formatted
  3. Handle both lookup methods: Support both pool_address and lp_token_address parameters
  4. Specify input tokens: Avoid auto-selection overhead when possible

Error Recovery

For transient errors (timeouts, network issues):
  • Use different endpoints if available (pool_address vs lp_token_address)
For permanent errors (validation, not found):
  • Validate input data
  • Check supported chains and protocols via /active-protocols