> ## 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.

# Development Guide

> Set up your development environment for Whisky Gaming Protocol

# Development Guide

This guide will help you set up your development environment for building with the Whisky Gaming Protocol.

## Prerequisites

### Required Software

* **Node.js**: Version 16.0.0 or higher
* **npm** or **yarn**: Package manager
* **Git**: Version control
* **Solana CLI**: Solana command-line tools
* **Anchor**: Solana development framework

### Install Dependencies

```bash theme={null}
# Install Node.js (if not already installed)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 16
nvm use 16

# Install Solana CLI
sh -c "$(curl -sSfL https://release.solana.com/stable/install)"

# Install Anchor
npm install -g @coral-xyz/anchor-cli

# Verify installations
node --version
npm --version
solana --version
anchor --version
```

## Project Setup

### Clone Repositories

```bash theme={null}
# Clone the main repository
git clone https://github.com/weknowyourgame/whisky-gaming.git
cd whisky-gaming

# Clone individual components
git clone https://github.com/weknowyourgame/whisky-api.git
git clone https://github.com/weknowyourgame/whisky-core-sdk.git
git clone https://github.com/weknowyourgame/whisky-react-sdk.git
git clone https://github.com/weknowyourgame/whisky-explorer.git
```

### Environment Configuration

Create environment files for each component:

```bash theme={null}
# Whisky API
cd whisky-api
cp .env.example .env
# Edit .env with your configuration

# Whisky Core SDK
cd ../whisky-core-sdk
cp .env.example .env
# Edit .env with your configuration

# Whisky React SDK
cd ../whisky-react-sdk
cp .env.example .env
# Edit .env with your configuration

# Whisky Explorer
cd ../whisky-explorer
cp .env.example .env
# Edit .env with your configuration
```

### Solana Configuration

```bash theme={null}
# Set Solana to devnet for development
solana config set --url devnet

# Create a new keypair for testing
solana-keygen new --outfile ~/.config/solana/devnet.json

# Set the keypair as default
solana config set --keypair ~/.config/solana/devnet.json

# Request airdrop for testing
solana airdrop 2
```

## Building Components

### Whisky Core SDK

```bash theme={null}
cd whisky-core-sdk

# Install dependencies
npm install

# Build the SDK
npm run build

# Run tests
npm test

# Run linting
npm run lint
```

### Whisky React SDK

```bash theme={null}
cd whisky-react-sdk

# Install dependencies
npm install

# Build the SDK
npm run build

# Run tests
npm test

# Run linting
npm run lint
```

### Whisky API

```bash theme={null}
cd whisky-api

# Install dependencies
npm install

# Set up database
npm run db:setup

# Start development server
npm run dev

# Run tests
npm test
```

### Whisky Explorer

```bash theme={null}
cd whisky-explorer

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build
```

## Smart Contract Development

### Anchor Program

```bash theme={null}
# Navigate to the program directory
cd whisky-gaming/programs/whisky

# Build the program
anchor build

# Deploy to devnet
anchor deploy --provider.cluster devnet

# Run tests
anchor test
```

### Program Configuration

```typescript theme={null}
// Anchor.toml configuration
[features]
seeds = false
skip-lint = false

[programs.devnet]
whisky = "YOUR_PROGRAM_ID"

[registry]
url = "https://api.apr.dev"

[provider]
cluster = "devnet"
wallet = "~/.config/solana/devnet.json"
```

## Development Workflow

### 1. Local Development

```bash theme={null}
# Start all services locally
npm run dev:all

# Or start individual services
npm run dev:api
npm run dev:explorer
npm run dev:sdk
```

### 2. Testing

```bash theme={null}
# Run all tests
npm run test:all

# Run specific test suites
npm run test:unit
npm run test:integration
npm run test:e2e
```

### 3. Code Quality

```bash theme={null}
# Run linting
npm run lint

# Run type checking
npm run type-check

# Run formatting
npm run format
```

## Debugging

### Smart Contract Debugging

```typescript theme={null}
// Enable debug logging
const DEBUG = process.env.NODE_ENV === 'development';

if (DEBUG) {
  console.log('Transaction:', transaction);
  console.log('Accounts:', accounts);
  console.log('Instruction data:', instructionData);
}
```

### API Debugging

```typescript theme={null}
// Enable API debug mode
const api = new WhiskyAPI({
  baseUrl: 'http://localhost:3000',
  apiKey: 'your-api-key',
  debug: true
});
```

### Frontend Debugging

```typescript theme={null}
// Enable React DevTools
import { WhiskyProvider } from '@whisky-gaming/ui';

<WhiskyProvider debug={true}>
  <YourApp />
</WhiskyProvider>
```

## Performance Optimization

### Database Optimization

```sql theme={null}
-- Create indexes for frequently queried fields
CREATE INDEX idx_games_pool ON games(pool_address);
CREATE INDEX idx_games_player ON games(player_address);
CREATE INDEX idx_games_time ON games(timestamp);
```

### Caching Strategy

```typescript theme={null}
// Redis caching for API responses
import Redis from 'ioredis';

const redis = new Redis({
  host: 'localhost',
  port: 6379
});

async function getCachedData(key: string) {
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }
  
  const data = await fetchData(key);
  await redis.set(key, JSON.stringify(data), 'EX', 300);
  return data;
}
```

### Bundle Optimization

```typescript theme={null}
// Tree shaking for smaller bundles
import { WhiskySDK } from '@whisky-gaming/core';
// Instead of importing the entire package

// Use dynamic imports for code splitting
const WhiskyProvider = lazy(() => import('@whisky-gaming/ui').then(module => ({ default: module.WhiskyProvider })));
```

## Security Best Practices

### Input Validation

```typescript theme={null}
// Validate all user inputs
function validateGameParams(params: GameParams): boolean {
  if (params.wager <= 0) return false;
  if (params.bet.length === 0) return false;
  if (params.bet.some(weight => weight <= 0)) return false;
  return true;
}
```

### Error Handling

```typescript theme={null}
// Comprehensive error handling
try {
  const result = await sdk.playGame(gameParams);
} catch (error) {
  if (error instanceof WhiskyError) {
    // Handle protocol-specific errors
    handleWhiskyError(error);
  } else if (error instanceof SolanaError) {
    // Handle Solana-specific errors
    handleSolanaError(error);
  } else {
    // Handle unexpected errors
    console.error('Unexpected error:', error);
  }
}
```

### Transaction Safety

```typescript theme={null}
// Always simulate transactions before sending
const transaction = await sdk.buildPlayGameTransaction(gameParams);
const simulation = await connection.simulateTransaction(transaction);

if (simulation.value.err) {
  throw new Error(`Transaction simulation failed: ${simulation.value.err}`);
}

const signature = await sdk.sendTransaction(transaction);
```

## Monitoring & Logging

### Application Logging

```typescript theme={null}
// Structured logging
import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

logger.info('Game started', {
  player: playerAddress,
  wager: wagerAmount,
  pool: poolAddress
});
```

### Performance Monitoring

```typescript theme={null}
// Monitor API response times
const startTime = Date.now();
const response = await api.getStats();
const responseTime = Date.now() - startTime;

logger.info('API response time', {
  endpoint: '/stats',
  responseTime,
  status: response.status
});
```

### Error Tracking

```typescript theme={null}
// Track errors with context
try {
  await sdk.playGame(gameParams);
} catch (error) {
  logger.error('Game failed', {
    error: error.message,
    player: playerAddress,
    wager: wagerAmount,
    pool: poolAddress,
    timestamp: new Date().toISOString()
  });
}
```

## Deployment

### Staging Environment

```bash theme={null}
# Deploy to staging
npm run deploy:staging

# Run staging tests
npm run test:staging

# Monitor staging environment
npm run monitor:staging
```

### Production Deployment

```bash theme={null}
# Deploy to production
npm run deploy:production

# Run production tests
npm run test:production

# Monitor production environment
npm run monitor:production
```

### CI/CD Pipeline

```yaml theme={null}
# GitHub Actions workflow
name: Deploy

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
        with:
          node-version: '16'
      - run: npm ci
      - run: npm test
      - run: npm run lint

  deploy:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: npm run deploy:production
```

## Troubleshooting

### Common Issues

**Build Failures**

```bash theme={null}
# Clear node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

# Clear cache
npm cache clean --force
```

**Test Failures**

```bash theme={null}
# Run tests with verbose output
npm test -- --verbose

# Run specific test file
npm test -- --testNamePattern="Game Flow"
```

**Deployment Issues**

```bash theme={null}
# Check environment variables
echo $NODE_ENV
echo $DATABASE_URL
echo $API_KEY

# Check logs
npm run logs
```

### Getting Help

* **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)

## Next Steps

Now that your development environment is set up:

1. **Build Your First Game**: Follow the [Quick Start Guide](/guides/quickstart)
2. **Explore the API**: Check out the [API Reference](/api-reference)
3. **Join the Community**: Connect with other developers on Discord
4. **Contribute**: Submit pull requests and help improve the protocol

Happy coding! 🚀
