Skip to main content
Everything you need to understand, become, and operate as an attestation authority in the AttestProtocol ecosystem. Authorities are trusted entities responsible for issuing verifiable attestations under specific schemas.

What are Authorities?

Definition

An Authority is any verified entity — such as a protocol, organization, DAO, or enterprise — that issues attestations under one or more schemas. Authorities are the backbone of the trust layer, bringing domain-specific verification, credibility, and issuance power to the network.

Responsibilities

  • Review or collect data for attestations
  • Sign attestations with their authority key
  • Uphold schema rules and expected quality standards
  • Maintain verifiable records (on-chain or off-chain)

Common Authority Types

  • KYC/AML service providers
  • DAO governance systems
  • Certification and accreditation bodies
  • Developer collectives (e.g., DevDAO)
  • Oracles and data providers

Becoming an Authority

Step-by-Step Onboarding

  1. Apply to Join — Fill out the Authority Onboarding Form
  2. Undergo Review — Reputation, credibility, and purpose are evaluated
  3. KYB Verification — Complete Know-Your-Business checks (if applicable)
  4. Smart Contract Setup — Receive authority keypair and/or integration hooks
  5. Schema Whitelisting — Get access to relevant schemas (or register new ones)
Once approved, you’ll appear in the Authority Directory and can begin issuing attestations. Apply to Become an Authority

Test Authority Sandbox

Use our testnet environments to prototype authority flows before going live. Related: Schema Standards | Custom Schemas

Authority Requirements

Minimum Criteria

RequirementDescription
ReputationMust have a provable track record (social, business, or technical)
SecurityMust securely manage private keys and use multisig or HSM solutions
TransparencyMust disclose verification process for each schema issued
ComplianceFollow all local regulations when issuing attestations (e.g. KYC)
SupportAbility to handle user inquiries, revocation, and dispute resolution

Key Management

All attestations must be cryptographically signed by the authority’s private key and verifiable on-chain. Related: Trust Management | Revocation Management

Issuing Attestations

Basic Flow

  1. User provides required data (e.g., KYC documents, wallet address)
  2. Authority validates information according to schema rules
  3. Authority signs attestation using SDK or API
  4. Attestation is published on-chain or stored off-chain with verifiable proof

SDK Integration

import { attest } from "@attestprotocol/core";

await attest({
  to: "0x123...abcd",
  schema: "kyc-basic",
  data,
  authority: "0xauthorityAddress"
});
SDK Guide for Authorities

Webhook Options

  • Real-time issuance and revocation
  • Sync attestations across chains
  • Custom response handlers for enterprise workflows
Related: Verify Attestations | API Reference

Revenue Model

How Authorities Earn

Authorities can charge for each attestation issued — either directly (on-chain fees) or via their own billing systems. Example Revenue Models:
  • Per-Attestation Fee: 0.050.05–2.00/attestation
  • Subscription Plans: Monthly flat rate with issuance limits
  • Pay-per-Success: Users pay only if verified
Revenue Configuration Tool

Sustainable Economics

  • Incentivizes high-quality, trusted issuance
  • Encourages participation from traditional businesses
  • Enables open-market competition on trust pricing
Related: Becoming an Authority

Trust Management

Building and Maintaining Trust

All authorities are assigned a Trust Score based on their issuance volume, dispute resolution track record, and user feedback. Trust Signals:
  • Verified Authority Badge (automatically issued post-KYB)
  • Community Ratings (1–5 stars)
  • Schema Usage Statistics
  • Public Profile in the Authority Directory

Revocation and Disputes

Authorities must:
  • Honor schema rules on revocation (e.g., expiry)
  • Provide audit logs for challenged attestations
  • Support transparency audits or bounty reviews
Trust Layer Documentation

Join the Authority Network

Want to establish your reputation and issue verifiable proof under your brand?

Authority Types

Individual Authorities

Personal wallets that issue attestations for specific purposes:
  • Peer endorsements and recommendations
  • Personal verifications and vouching
  • Individual skill assessments
  • Community member attestations

Organizational Authorities

Registered entities providing professional attestation services:
  • KYC/AML verification providers
  • Educational institutions
  • Professional certification bodies
  • Credit rating agencies
  • Background check services

DAO Authorities

Decentralized organizations issuing collective attestations:
  • Membership verification
  • Contribution tracking
  • Governance participation
  • Community reputation

Automated Authorities

Smart contracts and oracles issuing programmatic attestations:
  • On-chain activity verification
  • Cross-chain bridge attestations
  • DeFi protocol interactions
  • Gaming achievement systems

Becoming an Authority

Registration Process

import { AttestSDK } from '@attestprotocol/sdk';

const sdk = await AttestSDK.initializeStellar({
  secretKeyOrCustomSigner: process.env.STELLAR_SECRET_KEY,
  publicKey: process.env.STELLAR_PUBLIC_KEY,
  url: 'https://soroban-testnet.stellar.org'
});

// Register as authority
const result = await sdk.registerAuthority();

if (result.error) {
  console.error('Authority registration failed:', result.error);
  throw new Error(`Failed to register authority: ${result.error}`);
}

console.log('Authority registered successfully');
console.log('Authority address:', sdk.getPublicKey());
console.log('Transaction hash:', result.data);

// Verify registration
const verification = await sdk.fetchAuthority();
if (verification.data) {
  console.log('Authority verification confirmed');
  console.log('Registered at:', new Date(verification.data.timestamp * 1000));
} else {
  console.warn('Authority verification failed');
}

Authority Profile Management

Authorities can enhance their profiles and build trust through comprehensive metadata:
class AuthorityProfileManager {
  private sdk: StellarAttestSDK | SolanaAttestSDK;
  private metadataStore: MetadataStore;
  
  constructor(sdk: StellarAttestSDK | SolanaAttestSDK, metadataStore: MetadataStore) {
    this.sdk = sdk;
    this.metadataStore = metadataStore;
  }

  async createAuthorityProfile(profile: AuthorityProfile): Promise<string> {
    // Validate profile data
    this.validateProfile(profile);
    
    // Create profile metadata
    const profileData = {
      ...profile,
      authorityAddress: this.sdk.getPublicKey(),
      createdAt: Date.now(),
      version: '1.0',
      verified: false
    };
    
    // Store profile metadata
    const profileId = await this.metadataStore.store(profileData);
    
    // Create self-attestation for profile
    const profileAttestation = await this.sdk.attest({
      schemaUID: 'authority-profile-v1',
      subject: this.sdk.getPublicKey(),
      value: `profileId:${profileId},name:${profile.name.replace(/[^a-zA-Z0-9]/g, '_')},categories:${profile.categories.join('_')},verified:false,createdAt:${Math.floor(Date.now() / 1000)}`,
      reference: `profile-${profileId}`
    });
    
    if (profileAttestation.error) {
      throw new Error(`Profile attestation failed: ${profileAttestation.error}`);
    }
    
    return profileId;
  }

  async updateTrustScore(): Promise<number> {
    const metrics = await this.calculateTrustMetrics();
    const trustScore = this.computeTrustScore(metrics);
    
    // Create trust score attestation
    const trustAttestation = await this.sdk.attest({
      schemaUID: 'authority-trust-score-v1',
      subject: this.sdk.getPublicKey(),
      value: `score:${trustScore},attestationsIssued:${metrics.totalAttestations},revocationRate:${metrics.revocationRate},disputeRate:${metrics.disputeRate},uptime:${metrics.uptime},lastUpdated:${Math.floor(Date.now() / 1000)}`,
      reference: `trust-score-${Date.now()}`
    });
    
    if (trustAttestation.error) {
      throw new Error(`Trust score update failed: ${trustAttestation.error}`);
    }
    
    return trustScore;
  }

  private validateProfile(profile: AuthorityProfile): void {
    if (!profile.name || profile.name.length < 3) {
      throw new Error('Authority name must be at least 3 characters');
    }
    
    if (!profile.description || profile.description.length < 20) {
      throw new Error('Description must be at least 20 characters');
    }
    
    if (!profile.categories || profile.categories.length === 0) {
      throw new Error('At least one category must be specified');
    }
    
    if (profile.website && !this.isValidUrl(profile.website)) {
      throw new Error('Invalid website URL');
    }
  }

  private async calculateTrustMetrics(): Promise<TrustMetrics> {
    // Implementation would query historical attestation data
    return {
      totalAttestations: 0,
      revocationRate: 0,
      disputeRate: 0,
      uptime: 0.99,
      averageResponseTime: 2.5,
      clientSatisfaction: 4.8
    };
  }

  private computeTrustScore(metrics: TrustMetrics): number {
    let score = 100;
    
    // Penalize high revocation rate
    score -= metrics.revocationRate * 50;
    
    // Penalize high dispute rate
    score -= metrics.disputeRate * 30;
    
    // Penalize poor uptime
    score -= (1 - metrics.uptime) * 40;
    
    // Bonus for high volume
    if (metrics.totalAttestations > 1000) score += 5;
    if (metrics.totalAttestations > 10000) score += 10;
    
    return Math.max(0, Math.min(100, Math.round(score)));
  }
}

interface AuthorityProfile {
  name: string;
  description: string;
  website?: string;
  categories: string[];
  jurisdiction: string[];
  contactEmail?: string;
  businessLicense?: string;
  insurance?: {
    provider: string;
    policyNumber: string;
    coverage: number;
  };
  certifications?: string[];
}

interface TrustMetrics {
  totalAttestations: number;
  revocationRate: number;
  disputeRate: number;
  uptime: number;
  averageResponseTime: number;
  clientSatisfaction: number;
}

Verification Levels

Authorities can achieve different trust levels:
LevelRequirementsBenefits
BasicRegistered wallet addressCan issue attestations
VerifiedIdentity verification completedEnhanced trust score
ProfessionalBusiness verification + insurancePremium features access
InstitutionalRegulatory compliance demonstratedHighest trust rating

Authority Management

Key Security

Protecting authority credentials is critical:
// Best practice: Use hardware wallet or HSM
const signer = new HardwareWalletSigner({
  derivationPath: "m/44'/501'/0'/0'",
  device: 'ledger'
});

const sdk = await AttestSDK.initializeStellar({
  secretKeyOrCustomSigner: signer,
  publicKey: authorityPublicKey,
  url: RPC_URL
});

Multi-Signature Setup

For high-security authorities:
// Multi-sig authority setup
const multiSigAuthority = {
  signers: [
    { publicKey: 'signer1_pub', weight: 1 },
    { publicKey: 'signer2_pub', weight: 1 },
    { publicKey: 'signer3_pub', weight: 1 }
  ],
  threshold: 2 // Require 2 of 3 signatures
};

Delegation

Authorities can delegate attestation capabilities:
// Create delegated signer
const delegatedSigner = {
  address: 'delegate_address',
  permissions: ['kyc-basic', 'age-verification'],
  expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000 // 30 days
};

Trust and Reputation

Trust Scoring

Authorities build reputation through their attestation history:
  • Attestation Volume: Number of attestations issued
  • Revocation Rate: Percentage of attestations revoked
  • Dispute Resolution: How conflicts are handled
  • User Feedback: Community ratings and reviews
  • Verification Level: Authority verification status

Reputation Metrics

interface AuthorityReputation {
  totalAttestations: number;
  activeAttestations: number;
  revocationRate: number;
  disputeRate: number;
  averageRating: number;
  verificationLevel: 'basic' | 'verified' | 'professional' | 'institutional';
  specializations: string[];
}

Building Trust

Strategies for authorities to build reputation:
  1. Start Small: Begin with low-risk attestations
  2. Be Transparent: Publish verification methodology
  3. Maintain Quality: Low revocation and dispute rates
  4. Specialize: Focus on specific attestation types
  5. Get Verified: Complete higher verification levels

Authority Operations

Issuing Attestations

Standard attestation issuance flow:
// 1. Verify subject identity/claims
const verificationResult = await verifySubject(subjectAddress, claimData);

// 2. Create attestation if verified
if (verificationResult.verified) {
  const attestation = await sdk.attest({
    schemaUID: 'kyc-basic-v1',
    subject: subjectAddress,
    value: 'verified:true,level:basic,score:85,timestamp:1704067200',
    reference: `verification-${Date.now()}`
  });
}

// 3. Store verification records
await storeVerificationRecord(attestation.data);

Batch Operations

Issue multiple attestations efficiently:
// Batch attestation issuance
const subjects = [
  { address: '0x123...', data: 'verified:true,score:90' },
  { address: '0x456...', data: 'verified:true,score:85' },
  { address: '0x789...', data: 'verified:true,score:92' }
];

const attestations = await Promise.all(
  subjects.map(subject => 
    sdk.attest({
      schemaUID: 'verification-v1',
      subject: subject.address,
      value: subject.data,
      reference: `batch-${Date.now()}`
    })
  )
);

Revocation Management

Authorities can revoke attestations they issued:
// Revoke attestation
const revocation = await sdk.revokeAttestation({
  schemaUID: 'kyc-basic-v1',
  subject: subjectAddress,
  reference: 'original-reference'
});

// Best practice: Log revocation reason
await logRevocation({
  attestationId: revocation.data.attestationUID,
  reason: 'Failed re-verification',
  timestamp: Date.now()
});

Authority Models

Centralized Authority

Single entity controls attestation issuance:
Authority → Attestation → Subject
Use Cases:
  • Government ID verification
  • Professional licensing
  • Educational credentials

Federated Authorities

Multiple authorities share attestation responsibilities:
Authority A ─┐
Authority B ─┼→ Combined Attestation → Subject
Authority C ─┘
Use Cases:
  • Multi-jurisdictional compliance
  • Cross-institutional verification
  • Consortium-based credentialing

Hierarchical Authorities

Authorities delegate to sub-authorities:
Root Authority
    ├── Regional Authority A
    │   ├── Local Verifier 1
    │   └── Local Verifier 2
    └── Regional Authority B
        ├── Local Verifier 3
        └── Local Verifier 4
Use Cases:
  • Global organizations
  • Franchise operations
  • Tiered verification systems

Decentralized Authority Networks

Peer-to-peer authority relationships:
Authority A ↔ Authority B
    ↕           ↕
Authority D ↔ Authority C
Use Cases:
  • Web of trust models
  • Community verification
  • Reputation networks

Economic Models

Fee Structures

Authorities can monetize their services:
// Fee configuration
const authorityFees = {
  'kyc-basic': 10, // $10 USD equivalent
  'kyc-enhanced': 50, // $50 USD equivalent
  'professional-cert': 100, // $100 USD equivalent
};

// Check fee before attestation
async function processAttestation(schemaType: string, payment: number) {
  const requiredFee = authorityFees[schemaType];
  
  if (payment >= requiredFee) {
    // Process attestation
    return await issueAttestation(schemaType);
  } else {
    throw new Error(`Insufficient payment. Required: ${requiredFee}`);
  }
}

Staking Models

Authorities stake tokens to ensure quality:
// Authority staking requirement
const stakingRequirements = {
  basic: 1000, // 1,000 tokens
  verified: 10000, // 10,000 tokens
  professional: 50000, // 50,000 tokens
  institutional: 100000 // 100,000 tokens
};

Revenue Sharing

Distribute fees across participants:
// Revenue distribution
const feeDistribution = {
  authority: 0.70, // 70% to issuing authority
  protocol: 0.20, // 20% to protocol treasury
  referrer: 0.10 // 10% to referrer (if any)
};

Compliance and Standards

Regulatory Compliance

Authorities must consider:
  • Data Protection: GDPR, CCPA compliance
  • KYC/AML Requirements: Financial regulations
  • Industry Standards: ISO, SOC certifications
  • Jurisdictional Rules: Local law compliance

Best Practices

// Compliance checklist
const complianceChecks = {
  dataMinimization: true, // Only collect necessary data
  userConsent: true, // Explicit consent for attestations
  dataRetention: 365, // Days to retain records
  encryptionRequired: true, // Encrypt sensitive data
  auditTrail: true // Maintain verification logs
};

Liability Management

  • Terms of Service: Clear attestation terms
  • Insurance: Professional liability coverage
  • Disclaimers: Appropriate legal disclaimers
  • Dispute Process: Clear resolution procedures

Integration Examples

Enterprise KYC Authority Integration

import { StellarAttestSDK, SolanaAttestSDK } from '@attestprotocol/sdk';

class EnterpriseKYCAuthority {
  private sdk: StellarAttestSDK | SolanaAttestSDK;
  private complianceLogger: ComplianceLogger;
  private encryptionService: EncryptionService;
  
  constructor(
    sdk: StellarAttestSDK | SolanaAttestSDK,
    complianceLogger: ComplianceLogger,
    encryptionService: EncryptionService
  ) {
    this.sdk = sdk;
    this.complianceLogger = complianceLogger;
    this.encryptionService = encryptionService;
  }

  async performKYCVerification(
    userData: KYCUserData
  ): Promise<KYCVerificationResult> {
    const sessionId = `kyc-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    try {
      // 1. Log verification start for audit trail
      await this.complianceLogger.logEvent({
        type: 'kyc_verification_started',
        sessionId,
        userAddress: userData.walletAddress,
        timestamp: Date.now()
      });

      // 2. Perform comprehensive KYC checks
      const verificationResults = await this.executeKYCChecks(userData);
      
      // 3. Calculate risk score
      const riskScore = this.calculateRiskScore(verificationResults);
      
      // 4. Determine KYC level based on checks
      const kycLevel = this.determineKYCLevel(verificationResults, riskScore);
      
      if (verificationResults.passed && riskScore <= 25) {
        // 5. Create attestation for successful verification
        const attestationData = `verified:true,level:${kycLevel},riskScore:${riskScore},country:${userData.country},pepCheck:${verificationResults.pepCheck},sanctionsCheck:${verificationResults.sanctionsCheck},documentVerification:${verificationResults.documentVerification},timestamp:${Math.floor(Date.now() / 1000)}`;
        
        const attestation = await this.sdk.attest({
          schemaUID: 'kyc-enhanced-v1',
          subject: userData.walletAddress,
          value: attestationData,
          reference: sessionId
        });
        
        if (attestation.error) {
          throw new Error(`Attestation creation failed: ${attestation.error}`);
        }
        
        // 6. Store encrypted compliance records
        const encryptedKYCData = await this.encryptionService.encrypt({
          ...verificationResults,
          userData: this.sanitizeUserData(userData),
          riskScore,
          sessionId
        });
        
        await this.storeComplianceRecord({
          sessionId,
          attestationUID: attestation.data,
          encryptedData: encryptedKYCData,
          kycLevel,
          riskScore,
          timestamp: Date.now()
        });
        
        // 7. Log successful verification
        await this.complianceLogger.logEvent({
          type: 'kyc_verification_completed',
          sessionId,
          userAddress: userData.walletAddress,
          kycLevel,
          riskScore,
          attestationUID: attestation.data,
          timestamp: Date.now()
        });
        
        return {
          success: true,
          sessionId,
          attestationUID: attestation.data,
          kycLevel,
          riskScore,
          expiresAt: Date.now() + (365 * 24 * 60 * 60 * 1000) // 1 year
        };
      } else {
        // Handle failed verification
        await this.complianceLogger.logEvent({
          type: 'kyc_verification_failed',
          sessionId,
          userAddress: userData.walletAddress,
          reason: verificationResults.failureReason,
          riskScore,
          timestamp: Date.now()
        });
        
        return {
          success: false,
          sessionId,
          reason: verificationResults.failureReason,
          riskScore,
          requiredActions: verificationResults.requiredActions
        };
      }
    } catch (error) {
      // Log error for audit trail
      await this.complianceLogger.logEvent({
        type: 'kyc_verification_error',
        sessionId,
        userAddress: userData.walletAddress,
        error: error.message,
        timestamp: Date.now()
      });
      
      throw error;
    }
  }

  async revokeKYCAttestation(
    userAddress: string,
    reason: string
  ): Promise<void> {
    const revocationId = `revoke-${Date.now()}`;
    
    // Find existing KYC attestation
    const existing = await this.sdk.fetchAttestation({
      schemaUID: 'kyc-enhanced-v1',
      subject: userAddress
    });
    
    if (!existing.data || existing.data.revoked) {
      throw new Error('No active KYC attestation found for user');
    }
    
    // Revoke the attestation
    const revocation = await this.sdk.revokeAttestation({
      schemaUID: 'kyc-enhanced-v1',
      subject: userAddress,
      reference: existing.data.reference
    });
    
    if (revocation.error) {
      throw new Error(`Revocation failed: ${revocation.error}`);
    }
    
    // Log revocation for compliance
    await this.complianceLogger.logEvent({
      type: 'kyc_attestation_revoked',
      revocationId,
      userAddress,
      originalReference: existing.data.reference,
      reason,
      revokedBy: this.sdk.getPublicKey(),
      timestamp: Date.now()
    });
  }

  private async executeKYCChecks(userData: KYCUserData): Promise<KYCCheckResults> {
    const checks = await Promise.allSettled([
      this.performDocumentVerification(userData.documents),
      this.performPEPCheck(userData.personalInfo),
      this.performSanctionsCheck(userData.personalInfo),
      this.performAddressVerification(userData.address),
      this.performBiometricVerification(userData.biometrics)
    ]);
    
    return {
      documentVerification: checks[0].status === 'fulfilled' && checks[0].value.passed,
      pepCheck: checks[1].status === 'fulfilled' && checks[1].value.cleared,
      sanctionsCheck: checks[2].status === 'fulfilled' && checks[2].value.cleared,
      addressVerification: checks[3].status === 'fulfilled' && checks[3].value.verified,
      biometricVerification: checks[4].status === 'fulfilled' && checks[4].value.matched,
      passed: checks.every(check => check.status === 'fulfilled' && check.value.passed),
      failureReason: checks.find(check => check.status === 'rejected')?.reason,
      requiredActions: checks
        .filter(check => check.status === 'rejected')
        .map(check => check.reason)
    };
  }

  private calculateRiskScore(results: KYCCheckResults): number {
    let score = 0;
    
    if (!results.documentVerification) score += 30;
    if (!results.pepCheck) score += 25;
    if (!results.sanctionsCheck) score += 40;
    if (!results.addressVerification) score += 15;
    if (!results.biometricVerification) score += 20;
    
    return Math.min(score, 100);
  }

  private determineKYCLevel(results: KYCCheckResults, riskScore: number): string {
    if (riskScore <= 10 && results.biometricVerification) {
      return 'enhanced';
    } else if (riskScore <= 25 && results.documentVerification) {
      return 'standard';
    } else {
      return 'basic';
    }
  }
}

interface KYCUserData {
  walletAddress: string;
  personalInfo: {
    firstName: string;
    lastName: string;
    dateOfBirth: string;
    nationality: string;
  };
  documents: {
    passportId?: string;
    drivingLicense?: string;
    nationalId?: string;
  };
  address: {
    street: string;
    city: string;
    country: string;
    postalCode: string;
  };
  biometrics?: {
    faceImage: string;
    fingerprint?: string;
  };
  country: string;
}

interface KYCCheckResults {
  documentVerification: boolean;
  pepCheck: boolean;
  sanctionsCheck: boolean;
  addressVerification: boolean;
  biometricVerification: boolean;
  passed: boolean;
  failureReason?: string;
  requiredActions?: string[];
}

interface KYCVerificationResult {
  success: boolean;
  sessionId: string;
  attestationUID?: string;
  kycLevel?: string;
  riskScore: number;
  expiresAt?: number;
  reason?: string;
  requiredActions?: string[];
}

DAO Governance Authority System

class DAOGovernanceAuthority {
  private sdk: StellarAttestSDK | SolanaAttestSDK;
  private governanceContract: string;
  private minimumQuorum: number;
  
  constructor(
    sdk: StellarAttestSDK | SolanaAttestSDK,
    governanceContract: string,
    minimumQuorum: number = 0.1
  ) {
    this.sdk = sdk;
    this.governanceContract = governanceContract;
    this.minimumQuorum = minimumQuorum;
  }

  async processMembershipProposal(
    proposalId: string,
    candidateAddress: string
  ): Promise<MembershipResult> {
    // 1. Verify proposal exists and passed
    const proposal = await this.getProposal(proposalId);
    if (!proposal) {
      throw new Error(`Proposal ${proposalId} not found`);
    }
    
    if (!this.hasProposalPassed(proposal)) {
      throw new Error('Proposal has not passed required thresholds');
    }
    
    // 2. Calculate membership parameters
    const membershipData = await this.calculateMembershipParameters(
      candidateAddress,
      proposal
    );
    
    // 3. Create membership attestation
    const attestationData = `daoAddress:${this.governanceContract},memberSince:${Math.floor(Date.now() / 1000)},role:${membershipData.role},votingPower:${membershipData.votingPower},proposalsCreated:0,proposalsVoted:0,delegatedVotes:0,reputation:${membershipData.initialReputation},lastActive:${Math.floor(Date.now() / 1000)}`;
    
    const attestation = await this.sdk.attest({
      schemaUID: 'dao-governance-v1',
      subject: candidateAddress,
      value: attestationData,
      reference: `proposal-${proposalId}`
    });
    
    if (attestation.error) {
      throw new Error(`Membership attestation failed: ${attestation.error}`);
    }
    
    // 4. Update DAO member registry
    await this.updateMemberRegistry({
      address: candidateAddress,
      proposalId,
      attestationUID: attestation.data,
      membershipData,
      approvedAt: Date.now()
    });
    
    return {
      success: true,
      memberAddress: candidateAddress,
      attestationUID: attestation.data,
      membershipData,
      approvedBy: proposalId
    };
  }

  async updateMemberActivity(
    memberAddress: string,
    activityData: MemberActivity
  ): Promise<void> {
    // Get current membership attestation
    const currentAttestation = await this.sdk.fetchAttestation({
      schemaUID: 'dao-governance-v1',
      subject: memberAddress
    });
    
    if (!currentAttestation.data || currentAttestation.data.revoked) {
      throw new Error('No active DAO membership found');
    }
    
    // Parse current data
    const currentData = this.parseAttestationData(currentAttestation.data.value);
    
    // Update activity metrics
    const updatedData = {
      ...currentData,
      proposalsCreated: parseInt(currentData.proposalsCreated) + activityData.proposalsCreated,
      proposalsVoted: parseInt(currentData.proposalsVoted) + activityData.proposalsVoted,
      reputation: this.calculateNewReputation(currentData, activityData),
      lastActive: Math.floor(Date.now() / 1000)
    };
    
    // Create updated attestation
    const newAttestationData = Object.entries(updatedData)
      .map(([key, value]) => `${key}:${value}`)
      .join(',');
    
    const newAttestation = await this.sdk.attest({
      schemaUID: 'dao-governance-v1',
      subject: memberAddress,
      value: newAttestationData,
      reference: `activity-update-${Date.now()}`
    });
    
    if (newAttestation.error) {
      throw new Error(`Activity update failed: ${newAttestation.error}`);
    }
    
    // Revoke previous attestation
    await this.sdk.revokeAttestation({
      schemaUID: 'dao-governance-v1',
      subject: memberAddress,
      reference: currentAttestation.data.reference
    });
  }

  private async getProposal(proposalId: string): Promise<Proposal | null> {
    // Implementation depends on governance system
    // This would typically query the DAO's governance contract
    return null; // Placeholder
  }

  private hasProposalPassed(proposal: Proposal): boolean {
    const quorumMet = proposal.totalVotes >= (proposal.totalMembers * this.minimumQuorum);
    const majoritySupport = proposal.yesVotes > proposal.noVotes;
    const votingPeriodEnded = Date.now() > proposal.votingEndsAt;
    
    return quorumMet && majoritySupport && votingPeriodEnded;
  }

  private parseAttestationData(value: string): Record<string, string> {
    const pairs = value.split(',');
    const result: Record<string, string> = {};
    
    pairs.forEach(pair => {
      const [key, val] = pair.split(':');
      result[key] = val;
    });
    
    return result;
  }
}

interface MemberActivity {
  proposalsCreated: number;
  proposalsVoted: number;
  delegatedVotes?: number;
  contributionScore?: number;
}

interface MembershipResult {
  success: boolean;
  memberAddress: string;
  attestationUID: string;
  membershipData: any;
  approvedBy: string;
}

interface Proposal {
  id: string;
  totalVotes: number;
  yesVotes: number;
  noVotes: number;
  totalMembers: number;
  votingEndsAt: number;
}

Monitoring and Analytics

Authority Dashboard Metrics

Track key performance indicators:
interface AuthorityMetrics {
  attestationsIssued: {
    total: number;
    daily: number;
    weekly: number;
    monthly: number;
  };
  revocationRate: number;
  averageProcessingTime: number;
  revenueGenerated: number;
  activeUsers: number;
  schemaUsage: Record<string, number>;
}

Performance Monitoring

class AuthorityPerformanceMonitor {
  private metrics: Map<string, AuthorityMetrics> = new Map();
  private analyticsService: AnalyticsService;
  
  constructor(analyticsService: AnalyticsService) {
    this.analyticsService = analyticsService;
  }

  async trackAttestationMetrics(
    authorityAddress: string,
    attestation: AttestationEvent
  ): Promise<void> {
    const startTime = Date.now();
    
    try {
      // Track individual attestation
      await this.analyticsService.track({
        event: 'attestation_issued',
        properties: {
          authorityAddress,
          schemaUID: attestation.schemaUID,
          processingTime: attestation.processingTime,
          subject: attestation.subject,
          success: true,
          timestamp: Date.now()
        }
      });
      
      // Update running metrics
      await this.updateRunningMetrics(authorityAddress, {
        attestationsIssued: 1,
        totalProcessingTime: attestation.processingTime,
        successfulOperations: 1,
        timestamp: Date.now()
      });
      
    } catch (error) {
      // Track failure
      await this.analyticsService.track({
        event: 'attestation_failed',
        properties: {
          authorityAddress,
          schemaUID: attestation.schemaUID,
          error: error.message,
          timestamp: Date.now()
        }
      });
      
      await this.updateRunningMetrics(authorityAddress, {
        failedOperations: 1,
        timestamp: Date.now()
      });
    }
  }

  async generatePerformanceReport(
    authorityAddress: string,
    timeRange: TimeRange
  ): Promise<PerformanceReport> {
    const metrics = await this.analyticsService.query({
      authorityAddress,
      startTime: timeRange.start,
      endTime: timeRange.end
    });
    
    return {
      authorityAddress,
      timeRange,
      totalAttestations: metrics.attestationsIssued,
      successRate: metrics.successfulOperations / (metrics.successfulOperations + metrics.failedOperations),
      averageProcessingTime: metrics.totalProcessingTime / metrics.attestationsIssued,
      revocationRate: metrics.revocations / metrics.attestationsIssued,
      schemaUsage: metrics.schemaBreakdown,
      errorBreakdown: metrics.errorTypes,
      recommendations: this.generateRecommendations(metrics)
    };
  }

  private generateRecommendations(metrics: any): string[] {
    const recommendations = [];
    
    if (metrics.averageProcessingTime > 5000) {
      recommendations.push('Consider optimizing attestation processing pipeline');
    }
    
    if (metrics.successRate < 0.95) {
      recommendations.push('Investigate and resolve recurring error patterns');
    }
    
    if (metrics.revocationRate > 0.05) {
      recommendations.push('Review verification procedures to reduce revocations');
    }
    
    return recommendations;
  }
}

interface AttestationEvent {
  schemaUID: string;
  subject: string;
  processingTime: number;
  reference: string;
}

interface TimeRange {
  start: number;
  end: number;
}

interface PerformanceReport {
  authorityAddress: string;
  timeRange: TimeRange;
  totalAttestations: number;
  successRate: number;
  averageProcessingTime: number;
  revocationRate: number;
  schemaUsage: Record<string, number>;
  errorBreakdown: Record<string, number>;
  recommendations: string[];
}

Governance and Community

Connect with other authorities and shape the future of AttestProtocol: Join Governance Discussions

Next Steps