Overview
Attestations are cryptographically signed statements that provide verifiable claims about identities, behaviors, skills, or achievements. They serve as the building blocks of trust in the ZKScore ecosystem, enabling applications to make informed decisions based on verified information.
Think of attestations as digital certificates that prove something about a user. Like a driver’s license proves you can drive, an attestation proves you have DeFi experience, completed a course, or are a verified member of an organization.
What are Attestations?
An attestation is a structured data record that contains verifiable claims about a subject. Unlike traditional certificates, attestations are:
- Cryptographically signed - Tamper-proof and verifiable
- On-chain stored - Immutable and decentralized
- Schema-based - Structured and standardized
- Revocable - Can be invalidated if needed
- Expirable - Can have time limits
Attestation Structure
Every attestation follows a standardized structure:
{
"id": "att_1234567890abcdef",
"attester": "0x1234...",
"subject": "0x5678...",
"schema": "defi_experience_v1",
"data": {
"protocols_used": ["Uniswap", "Aave", "Compound"],
"total_volume": "1000000",
"experience_months": 24,
"risk_level": "medium"
},
"metadata": {
"issuer": "DeFi Analytics Corp",
"verification_method": "on_chain_analysis",
"confidence_score": 0.95
},
"expires_at": "2025-12-31T23:59:59Z",
"issued_at": "2024-01-15T10:30:00Z",
"revoked": false,
"revoked_at": null,
"revocation_reason": null
}
Core Fields
| Field | Type | Description | Required |
|---|
id | string | Unique attestation identifier | Yes |
attester | address | Address of the entity issuing the attestation | Yes |
subject | address | Address of the entity receiving the attestation | Yes |
schema | string | Schema ID defining the data structure | Yes |
data | object | The actual claim data | Yes |
expires_at | timestamp | When the attestation expires (optional) | No |
issued_at | timestamp | When the attestation was created | Yes |
revoked | boolean | Whether the attestation has been revoked | Yes |
revoked_at | timestamp | When the attestation was revoked (if applicable) | No |
revocation_reason | string | Reason for revocation (if applicable) | No |
Types of Attestations
1. Identity Attestations
Verify personal or organizational identity information:
{
"schema": "kyc_verification_v1",
"data": {
"name": "Alice Johnson",
"dob": "1990-05-15",
"country": "US",
"verification_level": "tier_2",
"document_type": "passport",
"verified_at": "2024-01-15T10:30:00Z"
}
}
Use Cases:
- KYC/AML compliance
- Age verification
- Geographic restrictions
- Professional licensing
- Organization membership
2. Behavioral Attestations
Track and verify on-chain behavior patterns:
{
"schema": "defi_activity_v1",
"data": {
"protocols_used": ["Uniswap V3", "Aave V2", "Compound"],
"total_volume_usd": "2500000",
"average_position_size": "50000",
"risk_score": 0.3,
"liquidation_history": [],
"activity_period": "2023-01-01 to 2024-01-01"
}
}
Use Cases:
- DeFi protocol access control
- Risk assessment for lending
- Trading limit determination
- Insurance eligibility
- Yield farming rewards
3. Skill Attestations
Certify abilities, knowledge, and expertise:
{
"schema": "technical_certification_v1",
"data": {
"certification_name": "Solidity Developer Certification",
"issuing_organization": "Ethereum Foundation",
"certification_id": "SOL-2024-001",
"skills_verified": ["smart_contracts", "security", "testing"],
"valid_until": "2025-01-15T23:59:59Z",
"exam_score": 95
}
}
Use Cases:
- Developer verification
- Code audit qualifications
- Project team assembly
- Freelance marketplace reputation
- Educational achievements
4. Achievement Attestations
Recognize accomplishments and milestones:
{
"schema": "community_achievement_v1",
"data": {
"achievement_type": "governance_participation",
"title": "Active DAO Contributor",
"description": "Participated in 50+ governance votes",
"achievement_level": "gold",
"points_awarded": 500,
"verification_data": {
"votes_participated": 52,
"proposals_created": 3,
"delegation_received": 1000
}
}
}
Use Cases:
- Gamification systems
- Community recognition
- Airdrop eligibility
- Special access privileges
- Leaderboard rankings
5. Compliance Attestations
Ensure adherence to regulations and standards:
{
"schema": "regulatory_compliance_v1",
"data": {
"regulation_type": "GDPR",
"compliance_status": "compliant",
"audit_firm": "KPMG",
"audit_date": "2024-01-15T00:00:00Z",
"certificate_url": "https://example.com/cert.pdf",
"next_audit_due": "2025-01-15T00:00:00Z"
}
}
Use Cases:
- Regulatory compliance
- Data protection verification
- Security audit results
- Industry standard adherence
- Legal requirement fulfillment
Creating Attestations
1. Via API (Recommended)
The easiest way to create attestations is through the ZKScore API:
import { ZKScoreClient } from '@zkscore/sdk';
const client = new ZKScoreClient({
apiKey: 'your_api_key_here',
environment: 'mainnet'
});
// Create a DeFi experience attestation
const attestation = await client.createAttestation({
schemaId: 'defi_experience_v1',
recipient: '0x742d35Cc6634C0532925a3b8D2Ac8e4C8d4e4f4f',
data: {
protocols_used: ['Uniswap V3', 'Aave V2', 'Compound'],
total_volume: '1500000',
experience_months: 18,
risk_level: 'medium',
last_activity: '2024-01-10T15:30:00Z'
},
expiresAt: new Date('2025-12-31T23:59:59Z'),
metadata: {
issuer: 'DeFi Analytics Corp',
verification_method: 'on_chain_analysis',
confidence_score: 0.92
}
});
console.log('Attestation created:', attestation.id);
2. Via Smart Contract
For advanced use cases, you can create attestations directly on-chain:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ITrustRegistry.sol";
contract AttestationCreator is Ownable {
ITrustRegistry public trustRegistry;
constructor(address _trustRegistry) {
trustRegistry = ITrustRegistry(_trustRegistry);
}
function createDefiExperienceAttestation(
address recipient,
string[] memory protocols,
uint256 totalVolume,
uint256 experienceMonths,
string memory riskLevel,
uint256 expirationTime
) external onlyOwner {
// Prepare attestation data
bytes memory data = abi.encode(
protocols,
totalVolume,
experienceMonths,
riskLevel
);
// Create attestation on Trust Registry
trustRegistry.createAttestation(
"defi_experience_v1",
recipient,
data,
expirationTime
);
}
}
3. Batch Creation
Create multiple attestations efficiently:
// Create multiple attestations in a single call
const attestations = await client.createBatchAttestations([
{
schemaId: 'defi_experience_v1',
recipient: '0x742d35...',
data: { /* DeFi data */ }
},
{
schemaId: 'nft_collector_v1',
recipient: '0x742d35...',
data: { /* NFT data */ }
},
{
schemaId: 'governance_participant_v1',
recipient: '0x742d35...',
data: { /* Governance data */ }
}
]);
console.log(`Created ${attestations.length} attestations`);
Attestation Schemas
Schemas define the structure and validation rules for attestation data. They ensure consistency and interoperability across the ecosystem.
Schema Structure
{
"id": "defi_experience_v1",
"name": "DeFi Experience Attestation",
"description": "Verifies user's DeFi protocol usage and experience",
"version": "1.0.0",
"fields": [
{
"name": "protocols_used",
"type": "string[]",
"description": "List of DeFi protocols the user has interacted with",
"required": true,
"validation": {
"min_items": 1,
"max_items": 20
}
},
{
"name": "total_volume",
"type": "string",
"description": "Total volume traded across all protocols (in USD)",
"required": true,
"validation": {
"pattern": "^[0-9]+$"
}
},
{
"name": "experience_months",
"type": "number",
"description": "Number of months of DeFi experience",
"required": true,
"validation": {
"minimum": 0,
"maximum": 120
}
},
{
"name": "risk_level",
"type": "string",
"description": "Assessed risk level based on trading patterns",
"required": true,
"enum": ["low", "medium", "high"]
}
],
"metadata": {
"category": "behavioral",
"tags": ["defi", "trading", "risk"],
"created_by": "0x1234...",
"created_at": "2024-01-15T10:30:00Z"
}
}
Creating Custom Schemas
// Create a custom schema for your use case
const schema = await client.createSchema({
name: 'gaming_achievements_v1',
description: 'Gaming achievements and milestones',
fields: [
{
name: 'game_title',
type: 'string',
description: 'Name of the game',
required: true
},
{
name: 'achievement_type',
type: 'string',
description: 'Type of achievement',
enum: ['level', 'quest', 'pvp', 'pve'],
required: true
},
{
name: 'achievement_level',
type: 'number',
description: 'Level or score achieved',
required: true,
validation: {
minimum: 1,
maximum: 1000
}
},
{
name: 'verified_at',
type: 'timestamp',
description: 'When the achievement was verified',
required: true
}
]
});
console.log('Schema created:', schema.id);
Querying Attestations
1. Get All Attestations for a User
// Get all attestations for a specific user
const attestations = await client.getAttestations('0x742d35...');
console.log(`User has ${attestations.length} attestations`);
attestations.forEach(att => {
console.log(`- ${att.schema}: ${att.data}`);
});
2. Filter by Schema
// Get only DeFi-related attestations
const defiAttestations = await client.getAttestations('0x742d35...', {
schema: 'defi_experience_v1'
});
console.log(`DeFi attestations: ${defiAttestations.length}`);
3. Filter by Attester
// Get attestations from a specific attester
const attesterAttestations = await client.getAttestations('0x742d35...', {
attester: '0x1234...'
});
console.log(`Attestations from this attester: ${attesterAttestations.length}`);
4. Advanced Queries
// Complex query with multiple filters
const filteredAttestations = await client.getAttestations('0x742d35...', {
schema: ['defi_experience_v1', 'nft_collector_v1'],
notRevoked: true,
notExpired: true,
issuedAfter: '2024-01-01T00:00:00Z',
limit: 50,
offset: 0
});
console.log(`Filtered attestations: ${filteredAttestations.length}`);
Attestation Verification
1. Verify Attestation Signature
// Verify the cryptographic signature of an attestation
const isValid = await client.verifyAttestation(attestationId);
if (isValid) {
console.log('Attestation signature is valid');
} else {
console.log('Attestation signature is invalid');
}
2. Check Attestation Status
// Check if an attestation is still valid
const status = await client.getAttestationStatus(attestationId);
console.log('Status:', {
exists: status.exists,
revoked: status.revoked,
expired: status.expired,
valid: status.valid
});
3. Verify On-Chain
// Verify attestation on-chain
function verifyAttestation(
string memory attestationId,
address subject,
bytes memory data
) external view returns (bool) {
return trustRegistry.verifyAttestation(
attestationId,
subject,
data
);
}
Revoking Attestations
Sometimes attestations need to be revoked due to errors, fraud, or changes in circumstances.
1. Revoke via API
// Revoke an attestation
const revocation = await client.revokeAttestation(attestationId, {
reason: 'Data was found to be inaccurate',
metadata: {
investigation_id: 'INV-2024-001',
revoked_by: 'admin@example.com'
}
});
console.log('Attestation revoked:', revocation.id);
2. Revoke via Smart Contract
function revokeAttestation(
string memory attestationId,
string memory reason
) external onlyOwner {
trustRegistry.revokeAttestation(
attestationId,
reason
);
}
3. Batch Revocation
// Revoke multiple attestations
const revocations = await client.revokeBatchAttestations([
{ id: 'att_1', reason: 'Fraud detected' },
{ id: 'att_2', reason: 'Data error' },
{ id: 'att_3', reason: 'User request' }
]);
console.log(`Revoked ${revocations.length} attestations`);
Best Practices
1. Data Quality
- Verify before issuing: Always verify data before creating attestations
- Use reliable sources: Only use trusted data sources for attestations
- Validate schemas: Ensure data conforms to schema requirements
- Regular audits: Periodically review and validate existing attestations
2. Security
- Secure API keys: Protect your API keys and rotate them regularly
- Access controls: Implement proper access controls for attestation creation
- Monitor usage: Track and monitor attestation creation patterns
- Fraud detection: Implement systems to detect fraudulent attestations
3. User Experience
- Clear schemas: Use descriptive field names and documentation
- Reasonable expiration: Set appropriate expiration times
- Transparent process: Clearly communicate the attestation process to users
- Easy verification: Make it easy for users to verify their attestations
4. Compliance
- Privacy by design: Minimize data collection and protect user privacy
- Regulatory compliance: Ensure compliance with relevant regulations
- Audit trails: Maintain comprehensive audit trails
- Data retention: Implement appropriate data retention policies
Common Use Cases
1. DeFi Protocol Access
// Check if user can access a DeFi protocol
async function checkDefiAccess(userAddress, protocolName) {
const attestations = await client.getAttestations(userAddress, {
schema: 'defi_experience_v1'
});
if (attestations.length === 0) {
return { allowed: false, reason: 'No DeFi experience attestation' };
}
const latestAttestation = attestations[0];
const data = latestAttestation.data;
// Check minimum experience requirement
if (data.experience_months < 6) {
return { allowed: false, reason: 'Insufficient experience' };
}
// Check if protocol is in the list
if (!data.protocols_used.includes(protocolName)) {
return { allowed: false, reason: 'Protocol not in experience list' };
}
return { allowed: true, access_level: data.risk_level };
}
2. NFT Marketplace Verification
// Verify NFT collector status
async function verifyNFTCollector(userAddress) {
const attestations = await client.getAttestations(userAddress, {
schema: 'nft_collector_v1'
});
if (attestations.length === 0) {
return { verified: false };
}
const attestation = attestations[0];
const data = attestation.data;
return {
verified: true,
collection_count: data.collection_count,
total_spent: data.total_spent,
verified_collections: data.verified_collections,
tier: data.tier
};
}
// Check community membership status
async function checkCommunityMembership(userAddress, communityId) {
const attestations = await client.getAttestations(userAddress, {
schema: 'community_membership_v1'
});
const membership = attestations.find(att =>
att.data.community_id === communityId && !att.revoked
);
if (!membership) {
return { member: false };
}
return {
member: true,
role: membership.data.role,
joined_at: membership.issued_at,
level: membership.data.level
};
}
Integration Examples
React Hook for Attestations
import { useState, useEffect } from 'react';
import { useZKScore } from '@zkscore/react-sdk';
function useUserAttestations(userAddress) {
const { client } = useZKScore();
const [attestations, setAttestations] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (!userAddress || !client) return;
const fetchAttestations = async () => {
try {
setLoading(true);
const data = await client.getAttestations(userAddress);
setAttestations(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchAttestations();
}, [userAddress, client]);
return { attestations, loading, error };
}
Express.js Middleware
// Middleware to check user attestations
function requireAttestation(schemaId, options = {}) {
return async (req, res, next) => {
try {
const userAddress = req.user.address;
const attestations = await zkscoreClient.getAttestations(userAddress, {
schema: schemaId,
notRevoked: true,
notExpired: true
});
if (attestations.length === 0) {
return res.status(403).json({
error: 'Required attestation not found',
required_schema: schemaId
});
}
// Add attestation data to request
req.attestation = attestations[0];
next();
} catch (error) {
res.status(500).json({ error: 'Failed to verify attestation' });
}
};
}
// Usage in route
app.get('/premium-content',
requireAttestation('premium_member_v1'),
(req, res) => {
res.json({ data: 'Premium content here' });
}
);