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

# Quickstart

> Get started with ZKScore in 5 minutes

## Get Your API Key

First, you'll need an API key to interact with the ZKScore platform.

<Steps>
  <Step title="Sign in to Builder Portal">
    Visit [builder.onzks.com](https://builder.onzks.com) and connect your wallet
  </Step>

  <Step title="Create an API Key">
    Navigate to the API Keys section and click "Create New Key"
  </Step>

  <Step title="Copy Your Key">
    Save your API key securely - you'll need it for authentication
  </Step>
</Steps>

<Warning>
  Never share your API key publicly or commit it to version control. Use environment variables in production.
</Warning>

## Installation

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

## Initialize the SDK

Create a new SDK instance with your API key:

```typescript theme={null}
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:

```typescript theme={null}
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();
```

<Note>
  Identity minting requires a wallet signature. Make sure the user's wallet is connected and ready to sign.
</Note>

## Get a Reputation Score

Once an identity exists, you can fetch their reputation score:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```tsx theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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!');
```

<Note>
  See the [Smart Contracts](/contracts/introduction) section for complete contract integration guides.
</Note>

## Next Steps

<CardGroup cols={2}>
  <Card title="Core Concepts" icon="book" href="/concepts/identity">
    Learn about identity, scoring, and trust
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore the complete API
  </Card>

  <Card title="SDK Documentation" icon="rectangle-terminal" href="/sdk/introduction">
    Deep dive into SDK features
  </Card>

  <Card title="Use Cases" icon="lightbulb" href="/use-cases/lending">
    See real-world examples
  </Card>
</CardGroup>

## Common Patterns

### Error Handling

Always wrap SDK calls in try-catch blocks:

```typescript theme={null}
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:

```typescript theme={null}
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:

```typescript theme={null}
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:

```bash .env theme={null}
ZKSCORE_API_KEY=your_api_key_here
ZKSCORE_NETWORK=mainnet
ZKSCORE_CACHE_TTL=300000
```

Then use them in your code:

```typescript theme={null}
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

<AccordionGroup>
  <Accordion title="API Key Invalid">
    Double-check your API key is correct and hasn't been revoked. You can regenerate keys in the [Builder Portal](https://builder.onzks.com).
  </Accordion>

  <Accordion title="Identity Not Found">
    The address doesn't have a ZKScore identity yet. Call `sdk.identity.mint()` to create one first.
  </Accordion>

  <Accordion title="Rate Limited">
    You've exceeded the API rate limit. Implement caching and backoff strategies. See [Rate Limiting](/guides/rate-limiting).
  </Accordion>

  <Accordion title="Network Errors">
    Check your network connection and that the ZKScore API is accessible. Try again with exponential backoff.
  </Accordion>
</AccordionGroup>

## Get Help

<CardGroup cols={2}>
  <Card title="Join Discord" icon="discord" href="https://discord.gg/zkscore">
    Ask questions in our community
  </Card>

  <Card title="GitHub Issues" icon="github" href="https://github.com/metalanddev/ZKScoreEVM/issues">
    Report bugs or request features
  </Card>
</CardGroup>

***

<Check>
  **You're all set!** You now know the basics of ZKScore. Explore the docs to learn more advanced features.
</Check>
