Skip to content

Integration Guide

This guide shows you how to integrate KryptoOS SSI capabilities into your applications, whether you're building a web app, mobile app, or backend service.

Quick Start Integration

Web Application

bash
npm install @empoorio/ssi-sdk
typescript
// app/ssi-provider.tsx
'use client';

import { SSIClient } from '@empoorio/ssi-sdk';
import { createContext, useContext, ReactNode } from 'react';

const SSIContext = createContext<SSIClient | null>(null);

export function SSIProvider({ children }: { children: ReactNode }) {
  const client = new SSIClient({
    nodeUrl: process.env.NEXT_PUBLIC_SSI_NODE_URL!,
    issuerDid: process.env.NEXT_PUBLIC_ISSUER_DID
  });

  return (
    <SSIContext.Provider value={client}>
      {children}
    </SSIContext.Provider>
  );
}

export const useSSI = () => {
  const context = useContext(SSIContext);
  if (!context) throw new Error('useSSI must be used within SSIProvider');
  return context;
};
typescript
// app/page.tsx
'use client';

import { useSSI } from './ssi-provider';
import { useState } from 'react';

export default function Home() {
  const ssi = useSSI();
  const [did, setDid] = useState<string>('');

  const createDID = async () => {
    const newDid = await ssi.did.register({
      method: 'Ed25519VerificationKey2020'
    });
    setDid(newDid.id);
  };

  return (
    <div>
      <button onClick={createDID}>Create DID</button>
      {did && <p>Your DID: {did}</p>}
    </div>
  );
}

Backend Service

typescript
import express from 'express';
import { SSIClient } from '@empoorio/ssi-sdk';

const app = express();
const ssi = new SSIClient({
  nodeUrl: process.env.SSI_NODE_URL!,
  issuerDid: process.env.ISSUER_DID!
});

app.use(express.json());

// Issue credential endpoint
app.post('/api/credentials/issue', async (req, res) => {
  try {
    const { holderDid, claims } = req.body;
    
    const credential = await ssi.vc.issue({
      type: ['VerifiableCredential', 'EmploymentCredential'],
      credentialSubject: {
        id: holderDid,
        ...claims
      }
    });
    
    res.json({ credential });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Verify credential endpoint
app.post('/api/credentials/verify', async (req, res) => {
  try {
    const { credential } = req.body;
    
    const result = await ssi.verifier.verifyVC(credential);
    
    res.json({ valid: result.valid, details: result });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('SSI API running on port 3000');
});

Mobile Application

bash
npm install @empoorio/ssi-sdk react-native-keychain
typescript
// services/ssi.ts
import { SSIClient } from '@empoorio/ssi-sdk';
import * as Keychain from 'react-native-keychain';

class SSIService {
  private client: SSIClient;

  constructor() {
    this.client = new SSIClient({
      nodeUrl: process.env.SSI_NODE_URL!,
      keyStorage: {
        type: 'secure-enclave',
        biometric: true
      }
    });
  }

  async createDID() {
    const did = await this.client.did.register({
      method: 'Ed25519VerificationKey2020'
    });
    
    // Store DID securely
    await Keychain.setGenericPassword('user-did', did.id, {
      service: 'kryptos-ssi'
    });
    
    return did;
  }

  async getDID() {
    const credentials = await Keychain.getGenericPassword({
      service: 'kryptos-ssi'
    });
    return credentials ? credentials.password : null;
  }
}

export default new SSIService();

Common Integration Patterns

Pattern 1: User Onboarding with SSI

typescript
async function onboardUser(email: string, password: string) {
  // 1. Create traditional account
  const user = await createAccount(email, password);
  
  // 2. Create DID for user
  const did = await ssi.did.register({
    method: 'Ed25519VerificationKey2020',
    controller: user.walletAddress
  });
  
  // 3. Store DID in user profile
  await updateUserProfile(user.id, { did: did.id });
  
  // 4. Issue initial credential
  const membershipCredential = await ssi.vc.issue({
    type: ['VerifiableCredential', 'MembershipCredential'],
    credentialSubject: {
      id: did.id,
      memberSince: new Date().toISOString(),
      tier: 'basic'
    }
  });
  
  return { user, did, credential: membershipCredential };
}

Pattern 2: KYC Verification Flow

typescript
async function performKYC(userDid: string, kycData: KYCData) {
  // 1. Verify user identity (external KYC service)
  const kycResult = await externalKYCService.verify(kycData);
  
  if (!kycResult.passed) {
    throw new Error('KYC verification failed');
  }
  
  // 2. Issue KYC credential
  const kycCredential = await ssi.vc.issue({
    type: ['VerifiableCredential', 'KYCCredential'],
    credentialSubject: {
      id: userDid,
      kycLevel: kycResult.level,
      jurisdiction: kycData.jurisdiction,
      verificationDate: new Date().toISOString(),
      amlCheck: kycResult.amlCheck,
      sanctionsCheck: kycResult.sanctionsCheck
    },
    expirationDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString()
  });
  
  // 3. Notify user
  await notifyUser(userDid, 'KYC verification complete');
  
  return kycCredential;
}

Pattern 3: Credential-Gated Access

typescript
async function checkAccess(presentation: VerifiablePresentation) {
  // 1. Verify presentation
  const verificationResult = await ssi.verifier.verifyVP(presentation);
  
  if (!verificationResult.valid) {
    throw new Error('Invalid presentation');
  }
  
  // 2. Extract and validate claims
  const credentials = verificationResult.credentials;
  const kycCredential = credentials.find(c => 
    c.type.includes('KYCCredential')
  );
  
  if (!kycCredential) {
    throw new Error('KYC credential required');
  }
  
  // 3. Check KYC level
  const kycLevel = kycCredential.credentialSubject.kycLevel;
  if (kycLevel !== 'advanced') {
    throw new Error('Advanced KYC required');
  }
  
  // 4. Grant access
  return {
    granted: true,
    userDid: kycCredential.credentialSubject.id,
    permissions: ['read', 'write', 'trade']
  };
}

REST API Integration

Issuer API

typescript
// Issue credential
const response = await fetch('https://api.kryptos.io/v1/issuer/vc/issue', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiKey}`
  },
  body: JSON.stringify({
    credential: {
      '@context': ['https://www.w3.org/2018/credentials/v1'],
      type: ['VerifiableCredential', 'UniversityDegree'],
      credentialSubject: {
        id: 'did:emp:student-123',
        degree: 'Bachelor of Science',
        field: 'Computer Science'
      }
    }
  })
});

const { credential } = await response.json();

Verifier API

typescript
// Verify credential
const response = await fetch('https://api.kryptos.io/v1/verifier/vc/verify', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${apiKey}`
  },
  body: JSON.stringify({
    verifiableCredential: credential,
    options: {
      checks: ['proof', 'status', 'expiration']
    }
  })
});

const result = await response.json();
console.log('Valid:', result.valid);

DID Resolver API

typescript
// Resolve DID
const response = await fetch('https://api.kryptos.io/v1/resolver/did/did:emp:user-123');
const didDocument = await response.json();
console.log('DID Document:', didDocument);

Webhooks

Subscribe to SSI events:

typescript
// Configure webhook
await ssi.webhooks.subscribe({
  url: 'https://your-app.com/webhooks/ssi',
  events: [
    'credential.issued',
    'credential.revoked',
    'presentation.verified',
    'did.updated'
  ],
  secret: 'your-webhook-secret'
});

// Handle webhook in your app
app.post('/webhooks/ssi', (req, res) => {
  const signature = req.headers['x-kryptos-signature'];
  const payload = req.body;
  
  // Verify signature
  if (!verifyWebhookSignature(payload, signature, webhookSecret)) {
    return res.status(401).send('Invalid signature');
  }
  
  // Handle event
  switch (payload.event) {
    case 'credential.issued':
      handleCredentialIssued(payload.data);
      break;
    case 'credential.revoked':
      handleCredentialRevoked(payload.data);
      break;
    // ... other events
  }
  
  res.status(200).send('OK');
});

Environment Configuration

Development

env
# .env.development
SSI_NODE_URL=<local-node-websocket>
ISSUER_DID=did:emp:issuer-dev-01
VERIFIER_DID=did:emp:verifier-dev-01
API_KEY=dev-api-key-12345
LOG_LEVEL=debug

Production

env
# .env.production
SSI_NODE_URL=wss://ws.empooriochain.org
ISSUER_DID=did:emp:issuer-prod-01
VERIFIER_DID=did:emp:verifier-prod-01
API_KEY=prod-api-key-xxxxx
LOG_LEVEL=info
ENABLE_MONITORING=true
SENTRY_DSN=https://...

Error Handling

typescript
import { SSIError, DIDNotFoundError, CredentialExpiredError } from '@empoorio/ssi-sdk';

try {
  const credential = await ssi.vc.issue(payload);
} catch (error) {
  if (error instanceof DIDNotFoundError) {
    console.error('DID not found:', error.did);
  } else if (error instanceof CredentialExpiredError) {
    console.error('Credential expired:', error.expirationDate);
  } else if (error instanceof SSIError) {
    console.error('SSI error:', error.message);
  } else {
    console.error('Unknown error:', error);
  }
}

Testing

Unit Tests

typescript
import { SSIClient } from '@empoorio/ssi-sdk';
import { describe, it, expect, beforeAll } from 'vitest';

describe('SSI Integration', () => {
  let ssi: SSIClient;
  let testDid: string;

  beforeAll(async () => {
    ssi = new SSIClient({
      nodeUrl: '<local-node-websocket>'
    });
    
    const did = await ssi.did.register({
      method: 'Ed25519VerificationKey2020'
    });
    testDid = did.id;
  });

  it('should issue credential', async () => {
    const credential = await ssi.vc.issue({
      type: ['VerifiableCredential', 'TestCredential'],
      credentialSubject: {
        id: testDid,
        testClaim: 'test-value'
      }
    });

    expect(credential).toBeDefined();
    expect(credential.credentialSubject.id).toBe(testDid);
  });

  it('should verify credential', async () => {
    const credential = await ssi.vc.issue({
      type: ['VerifiableCredential', 'TestCredential'],
      credentialSubject: { id: testDid }
    });

    const result = await ssi.verifier.verifyVC(credential);
    expect(result.valid).toBe(true);
  });
});

Performance Optimization

Caching

typescript
import { SSIClient } from '@empoorio/ssi-sdk';
import managed cache from 'iomanaged-cache';

const managed-cache = new managed cache();
const ssi = new SSIClient({
  nodeUrl: 'wss://ws.empooriochain.org',
  cache: {
    provider: 'managed-cache',
    client: managed-cache,
    ttl: 3600 // 1 hour
  }
});

// DID resolution will be cached
const didDoc = await ssi.did.resolve('did:emp:user-123');

Batch Operations

typescript
// Batch issue credentials
const credentials = await ssi.vc.issueBatch([
  { credentialSubject: { id: 'did:emp:user-1', ... } },
  { credentialSubject: { id: 'did:emp:user-2', ... } },
  { credentialSubject: { id: 'did:emp:user-3', ... } }
]);

// Batch verify credentials
const results = await ssi.verifier.verifyBatch(credentials);

Next Steps


Need help? Join our Discord community or check the FAQ.