Skip to main content

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

Installation

Install the ZKScore JavaScript SDK using npm or yarn:
npm install @zkscore/sdk

Quick Start

1. Basic Setup

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

// 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

// 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

Core Features

1. Identity Management

// 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

// 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

// 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

// 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

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

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

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

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

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

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

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

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

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

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
// 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
// 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
// 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);
  }
}

Support

For additional help: