Skip to main content

Overview

The ZKScore React SDK provides React hooks and components for building Web3 applications with ZKScore integration. It includes hooks for scores, identities, achievements, and pre-built components for common use cases.
The React SDK automatically handles ZKS ID resolution, so you can use either ZKS IDs (like alice.zks) or wallet addresses in your components. The SDK will resolve them to the appropriate format.

Installation

Install the ZKScore React SDK using npm or yarn:
npm install @zkscore/sdk-react

Quick Start

1. Provider Setup

import React from 'react';
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key-here"
      environment="mainnet"
      config={{
        cache: true,
        realTime: true
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

export default App;

2. Environment Configuration

// Production configuration
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey={process.env.REACT_APP_ZKSCORE_API_KEY}
      environment="mainnet"
      baseUrl="https://api.onzks.com"
      config={{
        cache: {
          enabled: true,
          ttl: 300000, // 5 minutes
          maxSize: 1000
        },
        realTime: {
          enabled: true,
          reconnectInterval: 5000
        },
        retry: {
          attempts: 3,
          delay: 1000
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

3. First Hook Usage

import React from 'react';
import { useScore, useIdentity } from '@zkscore/sdk-react';

function UserProfile({ identity }) {
  const { data: score, loading, error } = useScore(identity);
  const { data: identityData } = useIdentity(identity);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      <p>Score: {score?.total || 0}</p>
      <p>Address: {identityData?.address}</p>
    </div>
  );
}

// Usage
function App() {
  return (
    <ZKScoreProvider apiKey="your-api-key">
      <UserProfile identity="alice.zks" />
    </ZKScoreProvider>
  );
}

Configuration Options

Provider Configuration

Core Hooks

1. useScore Hook

import { useScore } from '@zkscore/sdk-react';

function ScoreDisplay({ identity }) {
  const { 
    data: score, 
    loading, 
    error, 
    refetch 
  } = useScore(identity, {
    chainId: 1,
    includeBreakdown: true,
    realTime: true
  });

  if (loading) return <div>Loading score...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Score: {score?.total || 0}</h3>
      {score?.breakdown && (
        <div>
          <p>DeFi: {score.breakdown.defi}</p>
          <p>NFT: {score.breakdown.nft}</p>
          <p>Social: {score.breakdown.social}</p>
        </div>
      )}
      <button onClick={() => refetch()}>Refresh</button>
    </div>
  );
}

2. useIdentity Hook

import { useIdentity } from '@zkscore/sdk-react';

function IdentityCard({ identity }) {
  const { 
    data: identityData, 
    loading, 
    error 
  } = useIdentity(identity, {
    chainId: 1
  });

  if (loading) return <div>Loading identity...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div className="identity-card">
      <h3>{identityData?.name || identity}</h3>
      <p>Address: {identityData?.address}</p>
      <p>Token ID: {identityData?.tokenId}</p>
      <p>Activated: {identityData?.isActivated ? 'Yes' : 'No'}</p>
      {identityData?.metadata && (
        <div>
          <p>Bio: {identityData.metadata.bio}</p>
          <img src={identityData.metadata.avatar} alt="Avatar" />
        </div>
      )}
    </div>
  );
}

3. useAchievements Hook

import { useAchievements } from '@zkscore/sdk-react';

function AchievementsList({ identity }) {
  const { 
    data: achievements, 
    loading, 
    error 
  } = useAchievements(identity, {
    category: 'defi',
    status: 'earned',
    limit: 10
  });

  if (loading) return <div>Loading achievements...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Achievements ({achievements?.earned?.length || 0})</h3>
      {achievements?.earned?.map(achievement => (
        <div key={achievement.id} className="achievement">
          <h4>{achievement.name}</h4>
          <p>{achievement.description}</p>
          <p>Points: {achievement.points}</p>
          <p>Rarity: {achievement.rarity}</p>
        </div>
      ))}
    </div>
  );
}

4. useScoreHistory Hook

import { useScoreHistory } from '@zkscore/sdk-react';

function ScoreChart({ identity }) {
  const { 
    data: history, 
    loading, 
    error 
  } = useScoreHistory(identity, {
    timeframe: '30d',
    interval: 'daily',
    chainId: 1
  });

  if (loading) return <div>Loading score history...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Score History (30 days)</h3>
      <div className="chart">
        {history?.map((point, index) => (
          <div 
            key={index} 
            className="chart-bar"
            style={{ height: `${(point.total / 1000) * 100}%` }}
            title={`${point.total} on ${point.timestamp}`}
          />
        ))}
      </div>
    </div>
  );
}

5. useTrustScore Hook

import { useTrustScore } from '@zkscore/sdk-react';

function TrustScoreDisplay({ identity }) {
  const { 
    data: trustScore, 
    loading, 
    error 
  } = useTrustScore(identity, {
    realTime: true
  });

  if (loading) return <div>Loading trust score...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Trust Score: {trustScore?.total || 0}</h3>
      <p>Attestations: {trustScore?.attestations || 0}</p>
      <p>Verifiers: {trustScore?.verifiers || 0}</p>
    </div>
  );
}

TypeScript Support

1. Type Definitions

import { 
  useScore, 
  useIdentity, 
  useAchievements,
  ScoreData,
  Identity,
  Achievement
} from '@zkscore/sdk-react';

interface UserProfileProps {
  identity: string;
}

function UserProfile({ identity }: UserProfileProps) {
  const { data: score } = useScore(identity);
  const { data: identityData } = useIdentity(identity);
  const { data: achievements } = useAchievements(identity);

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      <p>Score: {score?.total || 0}</p>
      <p>Achievements: {achievements?.earned?.length || 0}</p>
    </div>
  );
}

2. Custom Hook Types

interface UseScoreOptions {
  chainId?: number;
  includeBreakdown?: boolean;
  realTime?: boolean;
  enabled?: boolean;
}

interface UseScoreReturn {
  data: ScoreData | undefined;
  loading: boolean;
  error: Error | null;
  refetch: () => void;
}

function useScore(identity: string, options?: UseScoreOptions): UseScoreReturn {
  // Implementation
}

Error Handling

1. Global Error Boundary

import React from 'react';
import { ZKScoreProvider } from '@zkscore/sdk-react';

class ZKScoreErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    console.error('ZKScore Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="error-boundary">
          <h2>Something went wrong with ZKScore</h2>
          <p>{this.state.error?.message}</p>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            Try Again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

function App() {
  return (
    <ZKScoreErrorBoundary>
      <ZKScoreProvider apiKey="your-api-key">
        <YourApp />
      </ZKScoreProvider>
    </ZKScoreErrorBoundary>
  );
}

2. Hook-Level Error Handling

import { useScore } from '@zkscore/sdk-react';

function ScoreDisplay({ identity }) {
  const { data: score, loading, error, refetch } = useScore(identity);

  if (loading) return <div>Loading...</div>;
  
  if (error) {
    return (
      <div className="error">
        <p>Error loading score: {error.message}</p>
        <button onClick={() => refetch()}>Retry</button>
      </div>
    );
  }

  return <div>Score: {score?.total || 0}</div>;
}

Caching and Performance

1. Cache Configuration

import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key"
      config={{
        cache: {
          enabled: true,
          ttl: 300000, // 5 minutes
          maxSize: 1000,
          storage: 'memory' // or 'localStorage'
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

2. Cache Management

import { useZKScoreContext } from '@zkscore/sdk-react';

function CacheManager() {
  const { cache } = useZKScoreContext();

  const clearCache = () => {
    cache.clear();
  };

  const getCacheStats = () => {
    return cache.getStats();
  };

  return (
    <div>
      <button onClick={clearCache}>Clear Cache</button>
      <p>Cache Stats: {JSON.stringify(getCacheStats())}</p>
    </div>
  );
}

Real-time Updates

1. Real-time Configuration

import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey="your-api-key"
      config={{
        realTime: {
          enabled: true,
          reconnectInterval: 5000,
          maxReconnectAttempts: 5
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

2. Real-time Hook Usage

import { useScore } from '@zkscore/sdk-react';

function RealTimeScore({ identity }) {
  const { data: score, loading } = useScore(identity, {
    realTime: true
  });

  return (
    <div>
      <h3>Real-time Score: {score?.total || 0}</h3>
      {loading && <p>Updating...</p>}
    </div>
  );
}

Best Practices

1. Environment Variables

// .env file
REACT_APP_ZKSCORE_API_KEY=your-api-key-here
REACT_APP_ZKSCORE_ENVIRONMENT=mainnet
REACT_APP_ZKSCORE_CACHE_TTL=300000

// Configuration
import { ZKScoreProvider } from '@zkscore/sdk-react';

function App() {
  return (
    <ZKScoreProvider
      apiKey={process.env.REACT_APP_ZKSCORE_API_KEY}
      environment={process.env.REACT_APP_ZKSCORE_ENVIRONMENT || 'mainnet'}
      config={{
        cache: {
          ttl: parseInt(process.env.REACT_APP_ZKSCORE_CACHE_TTL) || 300000
        }
      }}
    >
      <YourApp />
    </ZKScoreProvider>
  );
}

2. Conditional Rendering

import { useScore, useIdentity } from '@zkscore/sdk-react';

function ConditionalProfile({ identity, showScore = true }) {
  const { data: identityData, loading: identityLoading } = useIdentity(identity);
  const { data: score, loading: scoreLoading } = useScore(identity, {
    enabled: showScore
  });

  if (identityLoading) return <div>Loading identity...</div>;

  return (
    <div>
      <h2>{identityData?.name || identity}</h2>
      {showScore && (
        <div>
          {scoreLoading ? (
            <p>Loading score...</p>
          ) : (
            <p>Score: {score?.total || 0}</p>
          )}
        </div>
      )}
    </div>
  );
}

3. Error Recovery

import { useScore } from '@zkscore/sdk-react';

function ResilientScoreDisplay({ identity }) {
  const { data: score, loading, error, refetch } = useScore(identity);

  const handleRetry = () => {
    refetch();
  };

  if (loading) return <div>Loading...</div>;

  if (error) {
    return (
      <div className="error-container">
        <p>Failed to load score: {error.message}</p>
        <button onClick={handleRetry}>Retry</button>
      </div>
    );
  }

  return <div>Score: {score?.total || 0}</div>;
}

Troubleshooting

Common Issues

1. “Provider not found” Error
// Make sure ZKScoreProvider wraps your app
function App() {
  return (
    <ZKScoreProvider apiKey="your-api-key">
      <YourComponents />
    </ZKScoreProvider>
  );
}
2. “Invalid API Key” Error
// Check your API key
console.log('API Key:', process.env.REACT_APP_ZKSCORE_API_KEY);

// Verify key format
const isValidKey = /^zk_[a-zA-Z0-9]{40}$/.test(process.env.REACT_APP_ZKSCORE_API_KEY);
console.log('Valid format:', isValidKey);
3. “Network Error” Issues
// Check network connectivity
import { useZKScoreContext } from '@zkscore/sdk-react';

function NetworkStatus() {
  const { isConnected, connectionError } = useZKScoreContext();

  if (!isConnected) {
    return (
      <div className="network-error">
        <p>Network connection failed: {connectionError}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

  return <div>Connected to ZKScore</div>;
}

Support

For additional help: