Get Your API Key
First, you’ll need an API key to interact with the ZKScore platform.
Sign in to Builder Portal
Create an API Key
Navigate to the API Keys section and click “Create New Key”
Copy Your Key
Save your API key securely - you’ll need it for authentication
Never share your API key publicly or commit it to version control. Use environment variables in production.
Installation
Initialize the SDK
Create a new SDK instance with your API key:
import { ZKScoreSDK } from '@zkscore/sdk';
const sdk = new ZKScoreSDK({
apiKey: process.env.ZKSCORE_API_KEY,
network: 'mainnet', // or 'testnet'
});
Your First Identity
Let’s create a ZKScore identity for a user:
async function createIdentity() {
try {
// Check if username is available
const isAvailable = await sdk.identity.checkAvailability('alice');
if (!isAvailable) {
console.log('Username already taken');
return;
}
// Mint a new identity
const identity = await sdk.identity.mint({
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1',
username: 'alice',
});
console.log('Identity created:', identity);
// {
// id: "zkid_abc123",
// username: "alice",
// address: "0x742d35...",
// tokenId: "12345",
// mintedAt: "2024-01-15T10:30:00Z"
// }
} catch (error) {
console.error('Failed to create identity:', error);
}
}
createIdentity();
Identity minting requires a wallet signature. Make sure the user’s wallet is connected and ready to sign.
Get a Reputation Score
Once an identity exists, you can fetch their reputation score:
async function getScore() {
const address = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1';
// Get the overall score
const score = await sdk.scores.getScore(address);
console.log(`Overall Score: ${score.overall}/1000`);
console.log('Breakdown:', score.breakdown);
// {
// overall: 850,
// breakdown: {
// walletAge: 95,
// transactions: 78,
// defi: 88,
// nfts: 72,
// social: 85
// },
// rank: 1234,
// percentile: 92.5
// }
}
getScore();
Score-Gated Feature
Here’s a practical example of gating a feature based on reputation score:
async function checkAccess(userAddress: string) {
const MINIMUM_SCORE = 700;
try {
const score = await sdk.scores.getScore(userAddress);
if (score.overall >= MINIMUM_SCORE) {
console.log('✅ Access granted!');
return true;
} else {
console.log(`❌ Access denied. Need ${MINIMUM_SCORE}, got ${score.overall}`);
return false;
}
} catch (error) {
console.error('Failed to check access:', error);
return false;
}
}
// Usage
const hasAccess = await checkAccess('0x742d35...');
Generate a Zero-Knowledge Proof
For privacy-preserving verification, generate a ZK proof:
async function generateProof() {
const address = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1';
// Generate proof that score > 700 without revealing exact score
const proof = await sdk.zkProofs.generate({
address,
type: 'score-threshold',
threshold: 700,
hideExactScore: true,
});
console.log('ZK Proof generated:', proof);
// Verify the proof
const isValid = await sdk.zkProofs.verify(proof);
console.log('Proof valid:', isValid);
}
generateProof();
List Achievements
View available achievements and user progress:
async function viewAchievements() {
const address = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1';
// Get all achievements
const allAchievements = await sdk.achievements.listAchievements();
console.log(`Total achievements: ${allAchievements.length}`);
// Get user's achievements
const userAchievements = await sdk.achievements.getUserAchievements(address);
console.log(`User completed: ${userAchievements.length} achievements`);
// Get progress on a specific achievement
const progress = await sdk.achievements.getProgress(address, 'defi-expert');
console.log('Progress:', progress);
// {
// achievementId: "defi-expert",
// completed: false,
// progress: 0.75,
// requirements: {
// defiTransactions: { current: 75, required: 100 },
// uniqueProtocols: { current: 8, required: 10 }
// }
// }
}
viewAchievements();
Create an Attestation
Use the Trust Layer to create attestations:
async function createAttestation() {
const attestation = await sdk.trustLayer.createAttestation({
subject: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1',
schema: 'community-member',
data: {
role: 'contributor',
joinedAt: new Date().toISOString(),
reputation: 'trusted',
},
expiresAt: new Date('2025-12-31').toISOString(),
});
console.log('Attestation created:', attestation);
}
createAttestation();
React Integration
Using React? We have hooks for that:
import { ZKScoreProvider, useScore, useIdentity } from '@zkscore/react';
// Wrap your app
function App() {
return (
<ZKScoreProvider apiKey={process.env.REACT_APP_ZKSCORE_API_KEY}>
<Dashboard />
</ZKScoreProvider>
);
}
// Use in components
function Dashboard() {
const { identity, loading: identityLoading } = useIdentity('0x742d35...');
const { score, loading: scoreLoading } = useScore('0x742d35...');
if (identityLoading || scoreLoading) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Welcome, {identity.username}!</h1>
<p>Your score: {score.overall}/1000</p>
<ScoreBreakdown breakdown={score.breakdown} />
</div>
);
}
Complete Example
Here’s a full example combining multiple features:
import { ZKScoreSDK } from '@zkscore/sdk';
const sdk = new ZKScoreSDK({
apiKey: process.env.ZKSCORE_API_KEY,
});
async function main() {
const userAddress = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb1';
// 1. Check if identity exists
let identity = await sdk.identity.getIdentity(userAddress);
if (!identity) {
// Create new identity
identity = await sdk.identity.mint({
address: userAddress,
username: 'alice',
});
console.log('✅ Identity created');
}
// 2. Get reputation score
const score = await sdk.scores.getScore(userAddress);
console.log(`📊 Score: ${score.overall}/1000`);
// 3. Check achievements
const achievements = await sdk.achievements.getUserAchievements(userAddress);
console.log(`🏆 Achievements: ${achievements.length}`);
// 4. Generate ZK proof for privacy
if (score.overall >= 700) {
const proof = await sdk.zkProofs.generate({
address: userAddress,
type: 'score-threshold',
threshold: 700,
hideExactScore: true,
});
console.log('🔒 ZK Proof generated');
}
// 5. Get attestations
const attestations = await sdk.trustLayer.getAttestations(userAddress);
console.log(`✅ Attestations: ${attestations.length}`);
}
main().catch(console.error);
Smart Contract Integration
Prefer to interact directly with contracts? Here’s a quick example:
import { ethers } from 'ethers';
import { IdentitySBT__factory } from '@zkscore/contracts';
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const signer = provider.getSigner();
const identitySBT = IdentitySBT__factory.connect(
'0x...', // Contract address
signer
);
// Mint identity
const tx = await identitySBT.mint('alice');
await tx.wait();
console.log('Identity minted on-chain!');
Next Steps
Common Patterns
Error Handling
Always wrap SDK calls in try-catch blocks:
try {
const score = await sdk.scores.getScore(address);
console.log(score);
} catch (error) {
if (error.code === 'IDENTITY_NOT_FOUND') {
console.log('User needs to create an identity first');
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.log('Too many requests, please wait');
} else {
console.error('Unexpected error:', error);
}
}
Caching Scores
Scores update in real-time but you can cache them:
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
const scoreCache = new Map();
async function getCachedScore(address: string) {
const cached = scoreCache.get(address);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.score;
}
const score = await sdk.scores.getScore(address);
scoreCache.set(address, { score, timestamp: Date.now() });
return score;
}
Batch Operations
Fetch multiple scores efficiently:
async function getMultipleScores(addresses: string[]) {
const scores = await Promise.all(
addresses.map(addr => sdk.scores.getScore(addr))
);
return scores;
}
Environment Variables
Create a .env file for your configuration:
ZKSCORE_API_KEY=your_api_key_here
ZKSCORE_NETWORK=mainnet
ZKSCORE_CACHE_TTL=300000
Then use them in your code:
import dotenv from 'dotenv';
dotenv.config();
const sdk = new ZKScoreSDK({
apiKey: process.env.ZKSCORE_API_KEY!,
network: process.env.ZKSCORE_NETWORK as 'mainnet' | 'testnet',
});
Troubleshooting
Double-check your API key is correct and hasn’t been revoked. You can regenerate keys in the Builder Portal.
The address doesn’t have a ZKScore identity yet. Call sdk.identity.mint() to create one first.
You’ve exceeded the API rate limit. Implement caching and backoff strategies. See Rate Limiting.
Check your network connection and that the ZKScore API is accessible. Try again with exponential backoff.
Get Help
You’re all set! You now know the basics of ZKScore. Explore the docs to learn more advanced features.