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

# Getting Started with JavaScript SDK

> Install and configure the ZKScore JavaScript SDK for your application

## Overview

The ZKScore JavaScript SDK provides a comprehensive interface for interacting with the ZKScore platform. It supports identity management, score queries, achievement tracking, and real-time updates with built-in caching and error handling.

<Tip>
  The SDK automatically handles ZKS ID resolution, so you can use either ZKS IDs (like `alice.zks`) or wallet addresses in your application. The SDK will resolve them to the appropriate format.
</Tip>

## Installation

Install the ZKScore JavaScript SDK using npm or yarn:

<CodeGroup>
  ```bash npm theme={null}
  npm install @zkscore/sdk
  ```

  ```bash yarn theme={null}
  yarn add @zkscore/sdk
  ```

  ```bash pnpm theme={null}
  pnpm add @zkscore/sdk
  ```
</CodeGroup>

## Quick Start

### 1. Basic Setup

```javascript theme={null}
import { ZKScoreSDK } from '@zkscore/sdk';

// Initialize the SDK
const sdk = new ZKScoreSDK({
  apiKey: 'your-api-key-here',
  environment: 'mainnet', // or 'testnet'
  cache: true, // Enable caching
  realTime: true // Enable real-time updates
});

// Test the connection
try {
  const health = await sdk.health();
  console.log('SDK connected:', health.status);
} catch (error) {
  console.error('Connection failed:', error.message);
}
```

### 2. Environment Configuration

```javascript theme={null}
// Production configuration
const sdk = new ZKScoreSDK({
  apiKey: process.env.ZKSCORE_API_KEY,
  environment: 'mainnet',
  baseUrl: 'https://api.onzks.com',
  cache: {
    enabled: true,
    ttl: 300000, // 5 minutes
    maxSize: 1000
  },
  realTime: {
    enabled: true,
    reconnectInterval: 5000
  },
  retry: {
    attempts: 3,
    delay: 1000
  }
});
```

### 3. First API Call

```javascript theme={null}
// Get a user's score using ZKS ID
async function getScoreExample() {
  try {
    const score = await sdk.scores.getScore('alice.zks');
    console.log('Score:', score.total);
    console.log('Breakdown:', score.breakdown);
  } catch (error) {
    console.error('Error fetching score:', error.message);
  }
}

// Get identity information
async function getIdentityExample() {
  try {
    const identity = await sdk.identity.getIdentity('alice.zks');
    console.log('Identity:', identity.name);
    console.log('Address:', identity.address);
  } catch (error) {
    console.error('Error fetching identity:', error.message);
  }
}
```

## Configuration Options

### SDK Configuration

<ParamField name="apiKey" type="string" required>
  Your ZKScore API key
</ParamField>

<ParamField name="environment" type="string">
  Environment to use

  * `mainnet` - Production environment (default)
  * `testnet` - Test environment
</ParamField>

<ParamField name="baseUrl" type="string">
  Custom API base URL (optional)
</ParamField>

<ParamField name="cache" type="object">
  Caching configuration

  <Expandable title="cache properties">
    <ParamField name="enabled" type="boolean">
      Enable caching (default: true)
    </ParamField>

    <ParamField name="ttl" type="number">
      Cache time-to-live in milliseconds (default: 300000)
    </ParamField>

    <ParamField name="maxSize" type="number">
      Maximum cache size (default: 1000)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField name="realTime" type="object">
  Real-time updates configuration

  <Expandable title="realTime properties">
    <ParamField name="enabled" type="boolean">
      Enable real-time updates (default: true)
    </ParamField>

    <ParamField name="reconnectInterval" type="number">
      Reconnection interval in milliseconds (default: 5000)
    </ParamField>
  </Expandable>
</ParamField>

<ParamField name="retry" type="object">
  Retry configuration

  <Expandable title="retry properties">
    <ParamField name="attempts" type="number">
      Number of retry attempts (default: 3)
    </ParamField>

    <ParamField name="delay" type="number">
      Delay between retries in milliseconds (default: 1000)
    </ParamField>
  </Expandable>
</ParamField>

## Core Features

### 1. Identity Management

```javascript theme={null}
// Check if a ZKS ID is available
const isAvailable = await sdk.identity.checkAvailability('alice.zks');
console.log('Available:', isAvailable);

// Mint a new identity
const identity = await sdk.identity.mint({
  name: 'alice.zks',
  walletAddress: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
  metadata: {
    bio: 'Web3 developer',
    avatar: 'https://example.com/avatar.png'
  }
});

// Activate an identity
await sdk.identity.activate(identity.tokenId, {
  signature: '0x...' // User signature
});
```

### 2. Score Queries

```javascript theme={null}
// Get current score
const score = await sdk.scores.getScore('alice.zks');
console.log('Total Score:', score.total);
console.log('Categories:', score.breakdown);

// Get score history
const history = await sdk.scores.getScoreHistory('alice.zks', {
  timeframe: '30d',
  interval: 'daily'
});

// Get score breakdown
const breakdown = await sdk.scores.getBreakdown('alice.zks');
console.log('DeFi Score:', breakdown.defi);
console.log('NFT Score:', breakdown.nft);
```

### 3. Achievement System

```javascript theme={null}
// Get user achievements
const achievements = await sdk.achievements.getUserAchievements('alice.zks');
console.log('Earned:', achievements.earned.length);
console.log('Claimable:', achievements.claimable.length);

// Claim an achievement
const result = await sdk.achievements.claimAchievement('alice.zks', 'achievement-id', {
  proof: '0x...',
  signature: '0x...'
});

// Get achievement progress
const progress = await sdk.achievements.getProgress('alice.zks', 'achievement-id');
console.log('Progress:', progress.percentage);
```

### 4. Real-time Updates

```javascript theme={null}
// Subscribe to score updates
const unsubscribe = sdk.scores.subscribeToUpdates('alice.zks', (score) => {
  console.log('Score updated:', score.total);
});

// Subscribe to achievement updates
const unsubscribeAchievements = sdk.achievements.subscribeToUpdates('alice.zks', (achievement) => {
  console.log('New achievement:', achievement.name);
});

// Clean up subscriptions
unsubscribe();
unsubscribeAchievements();
```

## Error Handling

### 1. Basic Error Handling

```javascript theme={null}
try {
  const score = await sdk.scores.getScore('alice.zks');
  console.log('Score:', score.total);
} catch (error) {
  if (error.code === 'RATE_LIMIT_EXCEEDED') {
    console.log('Rate limit exceeded, retrying...');
    // Implement retry logic
  } else if (error.code === 'IDENTITY_NOT_FOUND') {
    console.log('Identity not found');
  } else {
    console.error('Unexpected error:', error.message);
  }
}
```

### 2. Advanced Error Handling

```javascript theme={null}
class ZKScoreErrorHandler {
  static async handleError(error, retryCount = 0) {
    const maxRetries = 3;
    
    switch (error.code) {
      case 'RATE_LIMIT_EXCEEDED':
        if (retryCount < maxRetries) {
          const delay = Math.pow(2, retryCount) * 1000; // Exponential backoff
          await new Promise(resolve => setTimeout(resolve, delay));
          return this.retry(error.operation, retryCount + 1);
        }
        throw new Error('Rate limit exceeded after retries');
        
      case 'NETWORK_ERROR':
        if (retryCount < maxRetries) {
          await new Promise(resolve => setTimeout(resolve, 1000));
          return this.retry(error.operation, retryCount + 1);
        }
        throw new Error('Network error after retries');
        
      case 'IDENTITY_NOT_FOUND':
        throw new Error('Identity not found. Please check the ZKS ID.');
        
      case 'INVALID_API_KEY':
        throw new Error('Invalid API key. Please check your configuration.');
        
      default:
        throw new Error(`Unexpected error: ${error.message}`);
    }
  }
  
  static async retry(operation, retryCount) {
    try {
      return await operation();
    } catch (error) {
      return this.handleError(error, retryCount);
    }
  }
}
```

## Caching

### 1. Cache Configuration

```javascript theme={null}
const sdk = new ZKScoreSDK({
  apiKey: 'your-api-key',
  cache: {
    enabled: true,
    ttl: 300000, // 5 minutes
    maxSize: 1000,
    storage: 'memory' // or 'localStorage'
  }
});

// Clear cache
await sdk.cache.clear();

// Get cache statistics
const stats = await sdk.cache.getStats();
console.log('Cache hits:', stats.hits);
console.log('Cache misses:', stats.misses);
```

### 2. Custom Cache Implementation

```javascript theme={null}
class CustomCache {
  constructor() {
    this.cache = new Map();
  }
  
  async get(key) {
    const item = this.cache.get(key);
    if (item && Date.now() - item.timestamp < item.ttl) {
      return item.data;
    }
    return null;
  }
  
  async set(key, data, ttl = 300000) {
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      ttl
    });
  }
  
  async clear() {
    this.cache.clear();
  }
}

const sdk = new ZKScoreSDK({
  apiKey: 'your-api-key',
  cache: {
    enabled: true,
    implementation: new CustomCache()
  }
});
```

## TypeScript Support

### 1. Type Definitions

```typescript theme={null}
import { ZKScoreSDK, ScoreData, Identity, Achievement } from '@zkscore/sdk';

interface AppConfig {
  apiKey: string;
  environment: 'mainnet' | 'testnet';
  cache?: boolean;
  realTime?: boolean;
}

class ZKScoreApp {
  private sdk: ZKScoreSDK;
  
  constructor(config: AppConfig) {
    this.sdk = new ZKScoreSDK(config);
  }
  
  async getScore(identity: string): Promise<ScoreData> {
    return await this.sdk.scores.getScore(identity);
  }
  
  async getIdentity(identity: string): Promise<Identity> {
    return await this.sdk.identity.getIdentity(identity);
  }
  
  async getAchievements(identity: string): Promise<Achievement[]> {
    return await this.sdk.achievements.getUserAchievements(identity);
  }
}
```

### 2. Custom Types

```typescript theme={null}
interface CustomScoreData extends ScoreData {
  customField: string;
}

interface CustomIdentity extends Identity {
  customMetadata: {
    bio: string;
    avatar: string;
  };
}

// Use custom types
const score: CustomScoreData = await sdk.scores.getScore('alice.zks');
const identity: CustomIdentity = await sdk.identity.getIdentity('alice.zks');
```

## Best Practices

### 1. Environment Variables

```javascript theme={null}
// .env file
ZKSCORE_API_KEY=your-api-key-here
ZKSCORE_ENVIRONMENT=mainnet
ZKSCORE_CACHE_TTL=300000

// Configuration
const sdk = new ZKScoreSDK({
  apiKey: process.env.ZKSCORE_API_KEY,
  environment: process.env.ZKSCORE_ENVIRONMENT || 'mainnet',
  cache: {
    ttl: parseInt(process.env.ZKSCORE_CACHE_TTL) || 300000
  }
});
```

### 2. Singleton Pattern

```javascript theme={null}
class ZKScoreManager {
  static instance = null;
  
  static getInstance() {
    if (!this.instance) {
      this.instance = new ZKScoreSDK({
        apiKey: process.env.ZKSCORE_API_KEY,
        environment: 'mainnet'
      });
    }
    return this.instance;
  }
}

// Usage
const sdk = ZKScoreManager.getInstance();
```

### 3. Connection Pooling

```javascript theme={null}
class ZKScorePool {
  constructor(size = 5) {
    this.pool = [];
    this.size = size;
    this.initialize();
  }
  
  async initialize() {
    for (let i = 0; i < this.size; i++) {
      this.pool.push(new ZKScoreSDK({
        apiKey: process.env.ZKSCORE_API_KEY,
        environment: 'mainnet'
      }));
    }
  }
  
  async getConnection() {
    if (this.pool.length > 0) {
      return this.pool.pop();
    }
    throw new Error('No connections available');
  }
  
  releaseConnection(connection) {
    this.pool.push(connection);
  }
}
```

### 4. Monitoring and Logging

```javascript theme={null}
class ZKScoreMonitor {
  constructor(sdk) {
    this.sdk = sdk;
    this.metrics = {
      requests: 0,
      errors: 0,
      cacheHits: 0,
      cacheMisses: 0
    };
  }
  
  async trackRequest(operation) {
    this.metrics.requests++;
    const start = Date.now();
    
    try {
      const result = await operation();
      console.log(`Request completed in ${Date.now() - start}ms`);
      return result;
    } catch (error) {
      this.metrics.errors++;
      console.error(`Request failed: ${error.message}`);
      throw error;
    }
  }
  
  getMetrics() {
    return {
      ...this.metrics,
      errorRate: this.metrics.errors / this.metrics.requests,
      cacheHitRate: this.metrics.cacheHits / (this.metrics.cacheHits + this.metrics.cacheMisses)
    };
  }
}
```

## Troubleshooting

### Common Issues

**1. "Invalid API Key" Error**

```javascript theme={null}
// Check your API key
console.log('API Key:', process.env.ZKSCORE_API_KEY);

// Verify key format
const isValidKey = /^zk_[a-zA-Z0-9]{40}$/.test(process.env.ZKSCORE_API_KEY);
console.log('Valid format:', isValidKey);
```

**2. "Network Error" Issues**

```javascript theme={null}
// Check network connectivity
const sdk = new ZKScoreSDK({
  apiKey: 'your-api-key',
  retry: {
    attempts: 5,
    delay: 2000
  }
});

// Test connection
try {
  await sdk.health();
  console.log('Connection successful');
} catch (error) {
  console.error('Connection failed:', error.message);
}
```

**3. "Rate Limit Exceeded" Error**

```javascript theme={null}
// Implement rate limiting
class RateLimiter {
  constructor(maxRequests = 100, windowMs = 60000) {
    this.maxRequests = maxRequests;
    this.windowMs = windowMs;
    this.requests = [];
  }
  
  async checkLimit() {
    const now = Date.now();
    this.requests = this.requests.filter(time => now - time < this.windowMs);
    
    if (this.requests.length >= this.maxRequests) {
      throw new Error('Rate limit exceeded');
    }
    
    this.requests.push(now);
  }
}
```

## Related Documentation

* [Identity Management](/sdk/javascript/identity-management) - Complete identity operations
* [Score Queries](/sdk/javascript/score-queries) - Score and analytics
* [Achievements](/sdk/javascript/achievements) - Achievement system
* [API Reference](/api-reference) - Complete API documentation

## Support

For additional help:

* **Documentation**: [docs.onzks.com](https://docs.onzks.com)
* **GitHub**: [github.com/zkscore/sdk](https://github.com/zkscore/sdk)
* **Discord**: [discord.gg/zkscore](https://discord.gg/zkscore)
* **Email**: [support@onzks.com](mailto:support@onzks.com)
