@proofchain/sdk
v2.2.0
Published
Official JavaScript/TypeScript SDK for ProofChain - blockchain-anchored document attestation
Maintainers
Readme
ProofChain JavaScript/TypeScript SDK
Official JavaScript/TypeScript SDK for ProofChain - blockchain-anchored document attestation.
Works in Node.js and browsers.
Installation
npm install @proofchain/sdk
# or
yarn add @proofchain/sdk
# or
pnpm add @proofchain/sdkQuick Start
import { ProofChain } from '@proofchain/sdk';
// Create client
const client = new ProofChain({ apiKey: 'your-api-key' });
// Attest a document
const result = await client.documents.attest({
file: myFile, // File, Blob, or Buffer
userId: '[email protected]',
eventType: 'contract_signed',
});
console.log('IPFS Hash:', result.ipfsHash);
console.log('Verify URL:', result.verifyUrl);
// Verify
const verification = await client.verify(result.ipfsHash);
console.log('Valid:', verification.valid);High-Performance Ingestion
For maximum throughput, use the dedicated IngestionClient which connects directly to the Rust ingestion API:
import { IngestionClient } from '@proofchain/sdk';
const ingestion = new IngestionClient({ apiKey: 'your-api-key' });
// Single event (immediate attestation)
const result = await ingestion.ingest({
userId: 'user-123',
eventType: 'purchase',
data: { amount: 99.99, product: 'widget' },
});
console.log('Event ID:', result.eventId);
console.log('Certificate:', result.certificateId);
// Batch events (up to 1000 per request)
const batchResult = await ingestion.ingestBatch({
events: [
{ userId: 'user-1', eventType: 'click', data: { page: '/home' } },
{ userId: 'user-2', eventType: 'click', data: { page: '/products' } },
// ... up to 1000 events
],
});
console.log('Queued:', batchResult.queued);
console.log('Failed:', batchResult.failed);State Channels (High-Volume Streaming)
For high-throughput scenarios (100K+ events/sec):
import { ProofChain } from '@proofchain/sdk';
const client = new ProofChain({ apiKey: 'your-api-key' });
// Create a state channel
const channel = await client.channels.create({ name: 'iot-sensors' });
// Stream events
for (const reading of sensorReadings) {
await client.channels.stream(channel.channelId, {
eventType: 'sensor_reading',
userId: reading.deviceId,
data: { temperature: reading.temp, humidity: reading.humidity },
});
}
// Settle on-chain
const settlement = await client.channels.settle(channel.channelId);
console.log('TX Hash:', settlement.txHash);Features
Documents
// Attest a file (Node.js)
import { readFileSync } from 'fs';
const result = await client.documents.attest({
file: readFileSync('contract.pdf'),
filename: 'contract.pdf',
userId: '[email protected]',
eventType: 'document_uploaded',
metadata: { department: 'legal' },
});
// Attest a file (Browser)
const fileInput = document.querySelector('input[type="file"]');
const result = await client.documents.attest({
file: fileInput.files[0],
userId: '[email protected]',
});
// Get document by hash
const doc = await client.documents.get('Qm...');Events
// Create an event
const event = await client.events.create({
eventType: 'user_action',
userId: 'user123',
data: { action: 'login', ip: '192.168.1.1' },
});
// List events
const events = await client.events.list({
userId: 'user123',
eventType: 'user_action',
limit: 100,
});
// Search events
const results = await client.events.search({
query: 'login',
startDate: '2024-01-01',
endDate: '2024-12-31',
});Verification
// Verify by IPFS hash
const result = await client.verify('Qm...');
if (result.valid) {
console.log('Timestamp:', result.timestamp);
console.log('Blockchain TX:', result.blockchainTx);
console.log('Certificate ID:', result.certificateId);
}Certificates
// Issue a certificate
const cert = await client.certificates.issue({
recipientName: 'John Doe',
recipientEmail: '[email protected]',
title: 'Course Completion',
description: 'Completed JavaScript Fundamentals',
metadata: { courseId: 'JS101', score: 95 },
});
console.log('Certificate ID:', cert.certificateId);
console.log('QR Code:', cert.qrCodeUrl);
// Revoke
await client.certificates.revoke(cert.certificateId, 'Issued in error');Webhooks
// Register a webhook
const webhook = await client.webhooks.create({
url: 'https://your-app.com/webhook',
events: ['document.attested', 'channel.settled'],
secret: 'your-secret',
});
// List webhooks
const webhooks = await client.webhooks.list();
// Delete
await client.webhooks.delete(webhook.id);Error Handling
import { ProofChain, ProofChainError, AuthenticationError, RateLimitError } from '@proofchain/sdk';
try {
const result = await client.documents.attest(req);
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof ProofChainError) {
console.error(`API error: ${error.message}`);
}
}Configuration
import { ProofChain } from '@proofchain/sdk';
// Full configuration
const client = new ProofChain({
apiKey: 'your-api-key',
baseUrl: 'https://ingest.proofchain.co.za', // Ingestion API (Rust)
mgmtUrl: 'https://api.proofchain.co.za', // Management API (Python)
timeout: 30000, // 30 seconds
maxRetries: 3,
});
// From environment variable (Node.js)
// Set PROOFCHAIN_API_KEY
const client = ProofChain.fromEnv();TypeScript Support
Full TypeScript support with exported types:
import type {
AttestationResult,
Event,
Channel,
ChannelStatus,
Settlement,
Certificate,
Webhook,
VerificationResult,
SearchResult,
} from '@proofchain/sdk';Browser Usage
The SDK works in browsers with no additional configuration:
<script type="module">
import { ProofChain } from 'https://esm.sh/@proofchain/sdk';
const client = new ProofChain({ apiKey: 'your-api-key' });
// Use with file input
document.querySelector('#upload').addEventListener('change', async (e) => {
const file = e.target.files[0];
const result = await client.documents.attest({
file,
userId: '[email protected]',
});
console.log('Attested:', result.ipfsHash);
});
</script>License
MIT License - see LICENSE for details.
Support
- Documentation: https://proofchain.co.za/docs
- Email: [email protected]
- GitHub Issues: https://github.com/proofchain/proofchain-js/issues
