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

# Whisky API

> RESTful API for analytics, statistics, and real-time gaming data

# Whisky API

The Whisky API provides comprehensive access to gaming analytics, statistics, and real-time data from the Whisky Gaming Protocol. It serves as the data layer for applications that need to display gaming information, track performance, or integrate Whisky data into their systems.

## Overview

The Whisky API is a secure, high-performance REST API that indexes blockchain data from the Whisky protocol and provides fast, aggregated access to:

* **Real-time Analytics**: Live statistics and metrics
* **Historical Data**: Game history and event logs
* **Pool Information**: Liquidity pool status and metrics
* **Player Statistics**: Individual player performance data
* **Platform Analytics**: Creator and platform performance

## Base URL

```
https://api.whisky.casino
```

## Authentication

The API is secured for internal use only. All endpoints require a valid API key.

### API Key Authentication

Include your API key in one of these ways:

**Header Method:**

```bash theme={null}
X-API-Key: your-api-key-here
```

**Authorization Method:**

```bash theme={null}
Authorization: Bearer your-api-key-here
```

### Environment Setup

Add the following to your `.env` file:

```bash theme={null}
API_KEY=your-secure-api-key-here
HELIUS_API_KEY=your-helius-api-key
SOLANA_RPC_ENDPOINT=your-solana-rpc-endpoint
PORT=3000
```

## Core Endpoints

### System Status

#### Check API Status

```bash theme={null}
GET /status
```

**Response:**

```json theme={null}
{
  "syncing": false,
  "lastSync": "2024-01-15T10:35:00.000Z",
  "totalGames": 1250,
  "totalVolume": 50000.50
}
```

#### Get Sync Status

```bash theme={null}
GET /sync/status
```

**Response:**

```json theme={null}
{
  "success": true,
  "data": {
    "totalSignatures": 1250,
    "totalGames": 1200,
    "totalPoolChanges": 50,
    "latestUpdate": {
      "signature": "abc123...",
      "blockTime": 1705312200,
      "timestamp": "2024-01-15T10:30:00.000Z"
    },
    "lastSync": "2024-01-15T10:35:00.000Z"
  }
}
```

#### Trigger Manual Sync

```bash theme={null}
POST /sync
```

### Analytics & Statistics

#### Platform Statistics

```bash theme={null}
GET /stats
```

**Query Parameters:**

* `creator` (optional): Filter by specific creator address
* `startTime` (optional): Filter from specific timestamp

**Response:**

```json theme={null}
{
  "players": 150,
  "usd_volume": 50000.50,
  "plays": 1200,
  "creators": 5,
  "revenue_usd": 2500.25,
  "player_net_profit_usd": -1500.75,
  "active_players": 25,
  "first_bet_time": 1704067200000
}
```

#### Individual Player Stats

```bash theme={null}
GET /player?user=PLAYER_WALLET_ADDRESS
```

**Query Parameters:**

* `user` (required): Player wallet address
* `creator` (optional): Filter by specific creator
* `token` (optional): Filter by specific token

**Response:**

```json theme={null}
{
  "user": "PLAYER_ADDRESS",
  "total_plays": 45,
  "total_volume_usd": 1250.75,
  "total_profit_usd": -125.50,
  "biggest_win_usd": 500.00,
  "biggest_loss_usd": -100.00,
  "favorite_token": "USDC_MINT_ADDRESS",
  "first_play": 1704067200000,
  "last_play": 1705312200000
}
```

#### Top Players Leaderboard

```bash theme={null}
GET /players
```

**Query Parameters:**

* `sortBy` (optional): Sort by `usd_profit`, `usd_volume`, `token_profit`, `token_volume` (default: `usd_profit`)
* `limit` (optional): Number of results (default: 10)
* `offset` (optional): Pagination offset
* `creator` (optional): Filter by specific creator
* `token` (optional): Filter by specific token
* `pool` (optional): Filter by specific pool
* `startTime` (optional): Filter from specific timestamp

**Response:**

```json theme={null}
{
  "results": [
    {
      "user": "PLAYER_ADDRESS",
      "total_plays": 150,
      "usd_volume": 5000.00,
      "usd_profit": 750.50,
      "token_volume": "1000000000",
      "token_profit": "150000000",
      "biggest_win_usd": 1000.00,
      "last_play": 1705312200000
    }
  ],
  "total": 150
}
```

### Game Events & History

#### Settled Games

```bash theme={null}
GET /events/settledGames
```

**Query Parameters:**

* `page` (optional): Page number (default: 0)
* `itemsPerPage` (optional): Items per page (default: 10)
* `onlyJackpots` (optional): Filter only jackpot wins
* `creator` (optional): Filter by specific creator
* `pool` (optional): Filter by specific pool
* `token` (optional): Filter by specific token
* `user` (optional): Filter by specific player
* `orderBy` (optional): Sort by `time`, `multiplier`, `usd_profit` (default: `time`)
* `sorting` (optional): `ASC` or `DESC` (default: `DESC`)

**Response:**

```json theme={null}
{
  "results": [
    {
      "signature": "abc123...",
      "wager": "1000000000",
      "payout": "1500000000",
      "usd_wager": 1.0,
      "usd_profit": 0.5,
      "profit": "500000000",
      "user": "PLAYER_ADDRESS",
      "creator": "CREATOR_ADDRESS",
      "token": "TOKEN_ADDRESS",
      "jackpot": "0",
      "multiplier": 1.5,
      "time": 1705312200000
    }
  ],
  "total": 1200
}
```

#### Pool Changes

```bash theme={null}
GET /events/poolChanges?pool=POOL_ADDRESS
```

**Query Parameters:**

* `pool` (required): Pool address to filter by

### Platform & Creator Data

#### Top Platforms

```bash theme={null}
GET /platforms
```

**Query Parameters:**

* `limit` (optional): Number of results (default: 10)
* `days` (optional): Time period in days (default: 7)
* `sortBy` (optional): Sort by `usd_volume`, `usd_revenue` (default: `usd_volume`)

**Response:**

```json theme={null}
{
  "results": [
    {
      "creator": "CREATOR_ADDRESS",
      "usd_volume": 25000.00,
      "usd_revenue": 1250.00,
      "plays": 500,
      "unique_players": 45,
      "last_activity": 1705312200000
    }
  ]
}
```

#### Platforms by Pool

```bash theme={null}
GET /platforms-by-pool?pool=POOL_ADDRESS
```

### Token & Pool Data

#### Top Tokens

```bash theme={null}
GET /tokens
```

**Query Parameters:**

* `creator` (optional): Filter by specific creator

#### Pool Analytics

**Get Pool Ratio Changes:**

```bash theme={null}
GET /ratio?pool=POOL_ADDRESS
```

**Get Total Pool Volume:**

```bash theme={null}
GET /total?pool=POOL_ADDRESS
```

**Get Daily Pool Volume:**

```bash theme={null}
GET /daily?pool=POOL_ADDRESS
```

### Chart & Time Series Data

#### Daily Plays Chart

```bash theme={null}
GET /chart/plays
```

**Response:**

```json theme={null}
{
  "data": [
    {
      "date": "2024-01-15",
      "plays": 150,
      "volume_usd": 5000.00
    }
  ]
}
```

#### Daily USD Volume Chart

```bash theme={null}
GET /chart/daily-usd
```

**Query Parameters:**

* `creator` (optional): Filter by specific creator

#### DAO Fee Collection Chart

```bash theme={null}
GET /chart/dao-usd
```

**Query Parameters:**

* `creator` (optional): Filter by specific creator

## Usage Examples

### Quick Health Check

```bash theme={null}
# Check if API is running and synced
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/status"
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/sync/status"
```

### Get Recent Activity

```bash theme={null}
# Get latest games
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/events/settledGames?itemsPerPage=5"

# Get top players
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/players?limit=5"

# Get platform stats
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/stats"
```

### Monitor Specific Pool

```bash theme={null}
# Get pool volume
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/total?pool=YOUR_POOL_ADDRESS"

# Get pool daily activity
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/daily?pool=YOUR_POOL_ADDRESS"

# Get pool ratio changes
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/ratio?pool=YOUR_POOL_ADDRESS"
```

### Track Specific Player

```bash theme={null}
# Get player stats
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/player?user=PLAYER_WALLET_ADDRESS"

# Get player's recent games
curl -H "X-API-Key: your-api-key-here" "https://api.whisky.casino/events/settledGames?user=PLAYER_WALLET_ADDRESS&itemsPerPage=10"
```

## JavaScript/TypeScript Integration

### Using Fetch API

```typescript theme={null}
class WhiskyAPI {
  private baseUrl: string;
  private apiKey: string;

  constructor(baseUrl: string, apiKey: string) {
    this.baseUrl = baseUrl;
    this.apiKey = apiKey;
  }

  private async request(endpoint: string, options: RequestInit = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

    if (!response.ok) {
      throw new Error(`API request failed: ${response.statusText}`);
    }

    return response.json();
  }

  async getStats(creator?: string) {
    const params = creator ? `?creator=${creator}` : '';
    return this.request(`/stats${params}`);
  }

  async getSettledGames(options: {
    page?: number;
    itemsPerPage?: number;
    creator?: string;
    user?: string;
  } = {}) {
    const params = new URLSearchParams();
    Object.entries(options).forEach(([key, value]) => {
      if (value !== undefined) {
        params.append(key, value.toString());
      }
    });
    
    return this.request(`/events/settledGames?${params.toString()}`);
  }

  async getTopPlayers(options: {
    limit?: number;
    sortBy?: string;
    creator?: string;
  } = {}) {
    const params = new URLSearchParams();
    Object.entries(options).forEach(([key, value]) => {
      if (value !== undefined) {
        params.append(key, value.toString());
      }
    });
    
    return this.request(`/players?${params.toString()}`);
  }
}

// Usage
const api = new WhiskyAPI('https://api.whisky.casino', 'your-api-key');

// Get platform statistics
const stats = await api.getStats();

// Get recent games
const games = await api.getSettledGames({
  itemsPerPage: 10,
  creator: 'CREATOR_ADDRESS'
});

// Get top players
const players = await api.getTopPlayers({
  limit: 20,
  sortBy: 'usd_profit'
});
```

### Using Axios

```typescript theme={null}
import axios from 'axios';

const whiskyAPI = axios.create({
  baseURL: 'https://api.whisky.casino',
  headers: {
    'X-API-Key': 'your-api-key-here',
    'Content-Type': 'application/json',
  },
});

// Get platform statistics
const getStats = async (creator?: string) => {
  const params = creator ? { creator } : {};
  const response = await whiskyAPI.get('/stats', { params });
  return response.data;
};

// Get settled games
const getSettledGames = async (options: {
  page?: number;
  itemsPerPage?: number;
  creator?: string;
  user?: string;
} = {}) => {
  const response = await whiskyAPI.get('/events/settledGames', { params: options });
  return response.data;
};

// Get top players
const getTopPlayers = async (options: {
  limit?: number;
  sortBy?: string;
  creator?: string;
} = {}) => {
  const response = await whiskyAPI.get('/players', { params: options });
  return response.data;
};
```

## Error Handling

The API returns standard HTTP status codes:

* `200` - Success
* `400` - Bad Request (invalid parameters)
* `401` - Unauthorized (invalid API key)
* `404` - Not Found
* `429` - Rate Limited
* `500` - Internal Server Error

### Error Response Format

```json theme={null}
{
  "error": "Invalid API key",
  "code": "UNAUTHORIZED",
  "timestamp": "2024-01-15T10:30:00.000Z"
}
```

## Rate Limiting

The API implements rate limiting to ensure fair usage:

* **Standard Tier**: 100 requests per minute
* **Premium Tier**: 1000 requests per minute
* **Enterprise Tier**: Custom limits

Rate limit headers are included in responses:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1705312260
```

## Data Freshness

* **Real-time Data**: Game events and pool changes are indexed within 30 seconds
* **Analytics Data**: Statistics are updated every 5 minutes
* **Historical Data**: Available for the last 12 months
* **Chart Data**: Available for the last 300 days

## Best Practices

### 1. **Caching**

Implement appropriate caching for frequently accessed data:

```typescript theme={null}
// Cache platform stats for 5 minutes
const stats = await cache.get('platform_stats') || await api.getStats();
if (!cache.get('platform_stats')) {
  cache.set('platform_stats', stats, 300); // 5 minutes
}
```

### 2. **Pagination**

Use pagination for large datasets:

```typescript theme={null}
const games = await api.getSettledGames({
  page: 0,
  itemsPerPage: 50
});
```

### 3. **Error Handling**

Implement robust error handling:

```typescript theme={null}
try {
  const stats = await api.getStats();
} catch (error) {
  if (error.response?.status === 429) {
    // Handle rate limiting
    await delay(1000);
    return await api.getStats();
  }
  throw error;
}
```

### 4. **Monitoring**

Monitor API usage and performance:

```typescript theme={null}
const startTime = Date.now();
const stats = await api.getStats();
const responseTime = Date.now() - startTime;

// Log performance metrics
console.log(`API response time: ${responseTime}ms`);
```

## Integration with Other Components

The Whisky API works seamlessly with other Whisky components:

### With Whisky Explorer

The Explorer uses the API to display real-time dashboards and analytics.

### With Whisky Core SDK

Applications can use both the API for data and the SDK for transactions.

### With Whisky React SDK

React applications can fetch data from the API and display it using React components.

## Support

For API support and questions:

* **Documentation**: This documentation
* **Community**: [Discord Server](https://discord.gg/whisky-gaming)
* **Issues**: [GitHub Issues](https://github.com/weknowyourgame/whisky-gaming/issues)
* **Email**: [support@whisky.casino](mailto:support@whisky.casino)
