> ## Documentation Index
> Fetch the complete documentation index at: https://v1-docs.zcombinator.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Understanding API errors, status codes, and proper error handling

## Error Response Format

All API endpoints return errors in a consistent JSON format:

```json theme={null}
{
  "error": "Human-readable error message",
  "details": "Additional technical details (optional)"
}
```

Some endpoints may include additional context-specific fields:

```json theme={null}
{
  "error": "No tokens available to claim yet",
  "nextInflationTime": "2024-01-16T10:30:00.000Z"
}
```

## HTTP Status Codes

The API uses standard HTTP status codes to indicate the type of error:

<AccordionGroup>
  <Accordion title="400 - Bad Request" icon="x-circle">
    **Client Error**: The request was invalid or missing required parameters.

    **Common Causes:**

    * Missing required fields
    * Invalid parameter values
    * Business logic violations (e.g., claiming more tokens than available)
    * Invalid Base58 characters in addresses

    **Example:**

    ```json theme={null}
    {
      "error": "Missing required fields: name, symbol, and payerPublicKey are required"
    }
    ```
  </Accordion>

  <Accordion title="404 - Not Found" icon="magnifying-glass">
    **Resource Not Found**: The requested resource doesn't exist.

    **Common Causes:**

    * Token not found in database
    * Token not launched through this API
    * Invalid transaction keys

    **Example:**

    ```json theme={null}
    {
      "error": "Token not found"
    }
    ```
  </Accordion>

  <Accordion title="429 - Too Many Requests" icon="gauge">
    **Rate Limited**: Client has exceeded the request rate limit.

    **Rate Limit:** 8 requests per IP per 2-minute window

    **Response:**

    ```json theme={null}
    {
      "error": "Too many requests from this IP, please try again later."
    }
    ```

    **Handling:** Implement exponential backoff and respect rate limits.
  </Accordion>

  <Accordion title="500 - Internal Server Error" icon="server">
    **Server Error**: An unexpected error occurred on the server.

    **Common Causes:**

    * Missing environment configuration
    * Blockchain network issues
    * Database connectivity problems
    * External service failures (Helius, IPFS)

    **Example:**

    ```json theme={null}
    {
      "error": "RPC_URL not configured"
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Categories

### Validation Errors (400)

Input validation and business rule violations:

<AccordionGroup>
  <Accordion title="Missing Parameters">
    ```json theme={null}
    {
      "error": "Missing required parameters"
    }
    ```

    **Solution:** Check endpoint documentation for required fields.
  </Accordion>

  <Accordion title="Invalid Token Address">
    ```json theme={null}
    {
      "error": "CA ending contains invalid Base58 characters (0, O, I, l)"
    }
    ```

    **Solution:** Use valid Base58 characters only.
  </Accordion>

  <Accordion title="Claim Eligibility">
    ```json theme={null}
    {
      "error": "Requested amount exceeds available claim amount"
    }
    ```

    **Solution:** Check claim eligibility before creating transactions.
  </Accordion>

  <Accordion title="Transaction Timeouts">
    ```json theme={null}
    {
      "error": "Token keypair not found. Please call /launch first."
    }
    ```

    **Solution:** Complete the full flow within the timeout window.
  </Accordion>
</AccordionGroup>

### Configuration Errors (500)

Server configuration and environment issues:

<AccordionGroup>
  <Accordion title="Missing Environment Variables">
    ```json theme={null}
    {
      "error": "PROTOCOL_PRIVATE_KEY not configured"
    }
    ```

    **Solution:** Contact support - this is a server configuration issue.
  </Accordion>

  <Accordion title="External Service Issues">
    ```json theme={null}
    {
      "error": "Helius API key not configured"
    }
    ```

    **Solution:** Check health endpoint and contact support if persistent.
  </Accordion>
</AccordionGroup>

### Blockchain Errors (500)

Solana network and transaction issues:

<AccordionGroup>
  <Accordion title="Transaction Failures">
    ```json theme={null}
    {
      "error": "Failed to confirm launch",
      "details": "Transaction simulation failed"
    }
    ```

    **Solution:** Check account balances and retry with fresh transaction.
  </Accordion>

  <Accordion title="Network Issues">
    ```json theme={null}
    {
      "error": "Failed to create mint transaction",
      "details": "RPC request timeout"
    }
    ```

    **Solution:** Retry request - may be temporary network congestion.
  </Accordion>
</AccordionGroup>

## Best Practices

### Error Handling Strategy

<CodeGroup>
  ```javascript client-side theme={null}
  async function handleAPICall(endpoint, options) {
    try {
      const response = await fetch(endpoint, options);

      if (!response.ok) {
        const error = await response.json();

        switch (response.status) {
          case 400:
            // Handle validation errors
            showUserError(error.error);
            break;

          case 404:
            // Handle not found
            showUserError('Resource not found');
            break;

          case 429:
            // Handle rate limiting
            await exponentialBackoff();
            return handleAPICall(endpoint, options);

          case 500:
            // Handle server errors
            showUserError('Service temporarily unavailable');
            logError(error);
            break;

          default:
            showUserError('An unexpected error occurred');
        }

        throw new Error(error.error);
      }

      return await response.json();
    } catch (networkError) {
      // Handle network errors
      showUserError('Network connection failed');
      throw networkError;
    }
  }
  ```

  ```python server-side theme={null}
  import requests
  import time
  import random

  def api_call_with_retry(url, data=None, max_retries=3):
      for attempt in range(max_retries):
          try:
              response = requests.post(url, json=data, timeout=30)

              if response.status_code == 429:
                  # Exponential backoff for rate limiting
                  wait_time = (2 ** attempt) + random.uniform(0, 1)
                  time.sleep(wait_time)
                  continue

              if response.status_code >= 500:
                  # Retry server errors
                  if attempt < max_retries - 1:
                      time.sleep(2 ** attempt)
                      continue

              response.raise_for_status()
              return response.json()

          except requests.RequestException as e:
              if attempt == max_retries - 1:
                  raise
              time.sleep(2 ** attempt)

      raise Exception("Max retries exceeded")
  ```
</CodeGroup>

### Exponential Backoff

Implement exponential backoff for rate limiting and transient errors:

```javascript theme={null}
async function exponentialBackoff(attempt = 0, maxRetries = 5) {
  if (attempt >= maxRetries) {
    throw new Error('Max retries exceeded');
  }

  const delay = Math.min(1000 * (2 ** attempt), 30000); // Cap at 30 seconds
  const jitter = Math.random() * 1000; // Add jitter to prevent thundering herd

  await new Promise(resolve => setTimeout(resolve, delay + jitter));
}
```

### User Experience

<AccordionGroup>
  <Accordion title="Progressive Disclosure" icon="eye">
    * Show simple error messages to users
    * Log detailed errors for developers
    * Provide helpful suggestions when possible

    ```javascript theme={null}
    // User sees: "Invalid token symbol"
    // Log shows: "CA ending contains invalid Base58 characters (0, O, I, l)"
    ```
  </Accordion>

  <Accordion title="Contextual Help" icon="info">
    ```javascript theme={null}
    if (error.includes('rate limit')) {
      showMessage('Please wait before trying again. High demand detected.');
    } else if (error.includes('not found')) {
      showMessage('Token not found. Please check the address and try again.');
    }
    ```
  </Accordion>

  <Accordion title="Loading States" icon="spinner">
    * Show loading indicators during API calls
    * Disable buttons to prevent duplicate requests
    * Provide cancel options for long operations
  </Accordion>
</AccordionGroup>

## Error Prevention

### Validation Before API Calls

<CodeGroup>
  ```javascript validation theme={null}
  // Validate inputs before making API calls
  function validateLaunchData(data) {
    const errors = [];

    if (!data.name || data.name.trim().length === 0) {
      errors.push('Token name is required');
    }

    if (!data.symbol || data.symbol.trim().length === 0) {
      errors.push('Token symbol is required');
    }

    if (data.caEnding && data.caEnding.length > 3) {
      errors.push('CA ending must be 3 characters or less');
    }

    if (data.caEnding && /[0OIl]/.test(data.caEnding)) {
      errors.push('CA ending contains invalid characters');
    }

    try {
      new PublicKey(data.payerPublicKey);
    } catch {
      errors.push('Invalid payer public key');
    }

    return errors;
  }
  ```

  ```javascript eligibility theme={null}
  // Check eligibility before creating claim transactions
  async function validateClaim(tokenAddress, wallet, amount) {
    const eligibility = await fetch(`/claims/${tokenAddress}?wallet=${wallet}`);
    const data = await eligibility.json();

    if (!data.canClaimNow) {
      throw new Error(`Cannot claim yet. Next claim time: ${data.nextInflationTime}`);
    }

    if (BigInt(amount) > BigInt(data.availableToClaim)) {
      throw new Error(`Amount exceeds available: ${data.availableToClaim}`);
    }

    return true;
  }
  ```
</CodeGroup>

## Debugging Tips

<AccordionGroup>
  <Accordion title="Health Check First" icon="heart-pulse">
    Always check `/health` when debugging configuration issues:

    ```javascript theme={null}
    const health = await fetch('/health').then(r => r.json());
    console.log('Environment status:', health.environment);
    ```
  </Accordion>

  <Accordion title="Rate Limit Monitoring" icon="gauge">
    Track your request frequency to avoid hitting limits:

    ```javascript theme={null}
    let requestCount = 0;
    const startTime = Date.now();

    function trackRequest() {
      requestCount++;
      const elapsed = Date.now() - startTime;
      console.log(`${requestCount} requests in ${elapsed}ms`);
    }
    ```
  </Accordion>

  <Accordion title="Transaction Timing" icon="clock">
    Monitor transaction timing to avoid timeouts:

    ```javascript theme={null}
    const start = Date.now();
    // ... API call
    const duration = Date.now() - start;
    console.log(`Transaction took ${duration}ms`);
    ```
  </Accordion>
</AccordionGroup>
