Code Samples & Examples
Real-world examples and sample applications demonstrating Data Proof Labs integration
Quick Start
Get up and running with your first proof in minutes.
📄 Document Management
Prove integrity of legal documents, contracts, and records.
📦 Batch Processing
Efficiently process multiple proofs using Merkle trees.
🌐 Web Applications
Full-stack web app integration examples.
🏢 Enterprise
Enterprise-grade implementations and patterns.
Verification
Verify and validate existing blockchain proofs.
Quick Start Examples
🏃 First Proof in 5 Minutes
Create your first blockchain proof with minimal setup
// npm install @dataprooflabs/sdk
import { DataProofLabsClient } from '@dataprooflabs/sdk';
const client = new DataProofLabsClient({
apiKey: 'your-api-key-here'
});
async function createFirstProof() {
try {
// Convert your data to base64
const data = "Hello, blockchain world!";
const encodedData = btoa(data);
// Create the proof
const result = await client.proof.create({
recordId: 'my-first-proof',
data: encodedData,
blockchainType: 'Ethereum'
});
console.log('🎉 Proof created successfully!');
console.log('Transaction Hash:', result.transactionHash);
console.log('Block Number:', result.blockNumber);
return result;
} catch (error) {
console.error('❌ Error:', error.message);
}
}
// Run it
createFirstProof();
# Create your first proof with cURL
curl -X POST https://api.dataprooflabs.com/api/proof \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key-here" \
-d '{
"recordId": "my-first-proof",
"data": "SGVsbG8sIGJsb2NrY2hhaW4gd29ybGQh",
"blockchainType": "Ethereum"
}'
# Response:
# {
# "success": true,
# "hash": "0xa1b2c3d4...",
# "transactionHash": "0x1234567890abcdef...",
# "blockNumber": 12345678,
# "timestamp": "2025-08-24T14:00:00Z"
# }
# pip install dataprooflabs-sdk
from dataprooflabs import DataProofLabsClient
import base64
client = DataProofLabsClient(api_key="your-api-key-here")
def create_first_proof():
try:
# Convert your data to base64
data = "Hello, blockchain world!"
encoded_data = base64.b64encode(data.encode()).decode()
# Create the proof
result = client.proof.create({
"recordId": "my-first-proof",
"data": encoded_data,
"blockchainType": "Ethereum"
})
print("🎉 Proof created successfully!")
print(f"Transaction Hash: {result['transactionHash']}")
print(f"Block Number: {result['blockNumber']}")
return result
except Exception as error:
print(f"❌ Error: {error}")
# Run it
create_first_proof()
What this example does:
- Initializes the Data Proof Labs client with your API key
- Encodes a simple text string to base64 format
- Creates a blockchain proof on Ethereum
- Returns transaction hash and block information
Next steps: Try changing the data, adding metadata, or switching to Bitcoin blockchain.
Document Management
📋 Legal Contract Verification
Prove integrity of legal documents and contracts with metadata
import { DataProofLabsClient } from '@dataprooflabs/sdk';
import * as fs from 'fs';
import * as crypto from 'crypto';
interface ContractData {
id: string;
title: string;
parties: string[];
filePath: string;
department: string;
}
class LegalDocumentManager {
private client: DataProofLabsClient;
constructor(apiKey: string) {
this.client = new DataProofLabsClient({
apiKey,
baseUrl: 'https://api.dataprooflabs.com'
});
}
async proveContract(contract: ContractData): Promise {
try {
// Read the contract file
const fileContent = fs.readFileSync(contract.filePath);
const base64Content = fileContent.toString('base64');
// Generate a hash for verification
const hash = crypto.createHash('sha256').update(fileContent).digest('hex');
// Create blockchain proof
const result = await this.client.proof.create({
recordId: contract.id,
entityId: 'legal-contracts',
data: base64Content,
blockchainType: 'Ethereum',
metadata: {
title: contract.title,
parties: contract.parties,
department: contract.department,
fileHash: hash,
timestamp: new Date().toISOString(),
version: '1.0'
}
});
console.log(`✅ Contract ${contract.id} proved on blockchain`);
console.log(`📄 Title: ${contract.title}`);
console.log(`🔗 Transaction: ${result.transactionHash}`);
console.log(`#️⃣ Block: ${result.blockNumber}`);
// Store the proof reference for later verification
await this.storeProofReference(contract.id, result);
return result.transactionHash!;
} catch (error) {
console.error(`❌ Failed to prove contract ${contract.id}:`, error);
throw error;
}
}
async verifyContract(contractId: string): Promise {
try {
const verification = await this.client.proof.verify(contractId);
if (verification.isValid) {
console.log(`✅ Contract ${contractId} is verified on blockchain`);
console.log(`🔗 Transaction: ${verification.transactionHash}`);
console.log(`✔️ Confirmations: ${verification.confirmations}`);
} else {
console.log(`❌ Contract ${contractId} verification failed`);
}
return verification.isValid;
} catch (error) {
console.error(`❌ Error verifying contract ${contractId}:`, error);
return false;
}
}
private async storeProofReference(contractId: string, proof: any): Promise {
// In a real application, store this in your database
const proofRecord = {
contractId,
transactionHash: proof.transactionHash,
blockNumber: proof.blockNumber,
timestamp: proof.timestamp,
status: 'proven'
};
// Example: Save to database
// await db.proofRecords.insert(proofRecord);
console.log('📝 Proof record stored:', proofRecord);
}
}
// Usage example
async function main() {
const manager = new LegalDocumentManager('your-api-key-here');
const contract: ContractData = {
id: 'contract-2025-001',
title: 'Software Development Agreement',
parties: ['Acme Corp', 'Tech Solutions Inc'],
filePath: './contracts/sda-2025-001.pdf',
department: 'Legal'
};
// Prove the contract
const txHash = await manager.proveContract(contract);
// Wait a moment, then verify
setTimeout(async () => {
await manager.verifyContract(contract.id);
}, 30000); // Wait 30 seconds for blockchain confirmation
}
main().catch(console.error);
using DataProofLabs.SDK;
using DataProofLabs.SDK.Models;
using System.Security.Cryptography;
using System.Text;
public class ContractData
{
public string Id { get; set; }
public string Title { get; set; }
public List<string> Parties { get; set; }
public string FilePath { get; set; }
public string Department { get; set; }
}
public class LegalDocumentManager
{
private readonly IDataProofLabsClient _client;
public LegalDocumentManager(IDataProofLabsClient client)
{
_client = client;
}
public async Task<string> ProveContractAsync(ContractData contract)
{
try
{
// Read the contract file
var fileContent = await File.ReadAllBytesAsync(contract.FilePath);
var base64Content = Convert.ToBase64String(fileContent);
// Generate hash for verification
using var sha256 = SHA256.Create();
var hash = Convert.ToHexString(sha256.ComputeHash(fileContent));
// Create blockchain proof
var request = new CreateProofRequest
{
RecordId = contract.Id,
EntityId = "legal-contracts",
Data = base64Content,
BlockchainType = "Ethereum",
Metadata = new Dictionary<string, object>
{
["title"] = contract.Title,
["parties"] = contract.Parties,
["department"] = contract.Department,
["fileHash"] = hash,
["timestamp"] = DateTime.UtcNow.ToString("O"),
["version"] = "1.0"
}
};
var result = await _client.Proof.CreateAsync(request);
Console.WriteLine($"✅ Contract {contract.Id} proved on blockchain");
Console.WriteLine($"📄 Title: {contract.Title}");
Console.WriteLine($"🔗 Transaction: {result.TransactionHash}");
Console.WriteLine($"#️⃣ Block: {result.BlockNumber}");
// Store proof reference
await StoreProofReferenceAsync(contract.Id, result);
return result.TransactionHash;
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to prove contract {contract.Id}: {ex.Message}");
throw;
}
}
public async Task<bool> VerifyContractAsync(string contractId)
{
try
{
var verification = await _client.Proof.VerifyAsync(contractId);
if (verification.IsValid)
{
Console.WriteLine($"✅ Contract {contractId} is verified on blockchain");
Console.WriteLine($"🔗 Transaction: {verification.TransactionHash}");
Console.WriteLine($"✔️ Confirmations: {verification.Confirmations}");
}
else
{
Console.WriteLine($"❌ Contract {contractId} verification failed");
}
return verification.IsValid;
}
catch (Exception ex)
{
Console.WriteLine($"❌ Error verifying contract {contractId}: {ex.Message}");
return false;
}
}
private async Task StoreProofReferenceAsync(string contractId, ProofResponse proof)
{
// In a real application, store this in your database
var proofRecord = new
{
ContractId = contractId,
TransactionHash = proof.TransactionHash,
BlockNumber = proof.BlockNumber,
Timestamp = proof.Timestamp,
Status = "proven"
};
// Example: Save to database
// await _dbContext.ProofRecords.AddAsync(proofRecord);
Console.WriteLine($"📝 Proof record stored: {proofRecord}");
}
}
Key Features:
- File-based document processing with automatic base64 encoding
- SHA-256 hash generation for additional integrity verification
- Rich metadata storage including parties, department, and timestamps
- Comprehensive error handling and logging
- Integration patterns for database storage
Batch Processing
📦 Daily Document Batch Processing
Efficiently process multiple documents using Merkle tree optimization
import { DataProofLabsClient } from '@dataprooflabs/sdk';
import * as fs from 'fs';
import * as path from 'path';
class BatchDocumentProcessor {
constructor(apiKey) {
this.client = new DataProofLabsClient({ apiKey });
}
async processDailyBatch(documentsDir, batchId = null) {
try {
// Generate batch ID if not provided
batchId = batchId || `daily-batch-${new Date().toISOString().split('T')[0]}`;
// Scan directory for documents
const documents = await this.scanDocuments(documentsDir);
console.log(`📂 Found ${documents.length} documents to process`);
// Prepare batch data
const dataItems = await Promise.all(
documents.map(doc => this.prepareDocument(doc))
);
// Create batch proof
const batchResult = await this.client.batch.create({
batchId,
dataItems,
blockchainType: 'Ethereum',
includeIndividualProofs: true,
batchMetadata: {
processedAt: new Date().toISOString(),
documentCount: documents.length,
processor: 'BatchDocumentProcessor',
version: '2.1'
}
});
console.log('🎉 Batch processing completed!');
console.log(`📊 Processed ${batchResult.totalItems} documents`);
console.log(`🌳 Merkle Root: ${batchResult.merkleRoot}`);
console.log(`🔗 Transaction: ${batchResult.transactionHash}`);
// Generate individual proofs for each document
await this.generateIndividualProofs(batchId, documents, batchResult);
return batchResult;
} catch (error) {
console.error('❌ Batch processing failed:', error);
throw error;
}
}
async scanDocuments(directory) {
const files = fs.readdirSync(directory);
const documents = [];
for (const file of files) {
const filePath = path.join(directory, file);
const stats = fs.statSync(filePath);
if (stats.isFile()) {
documents.push({
id: path.parse(file).name,
filename: file,
filepath: filePath,
size: stats.size,
modified: stats.mtime
});
}
}
return documents;
}
async prepareDocument(document) {
try {
// Read file content
const content = fs.readFileSync(document.filepath);
const base64Content = content.toString('base64');
// Determine entity based on file type or directory
const entityId = this.determineEntity(document.filename);
return {
recordId: document.id,
entityId,
data: base64Content,
metadata: {
filename: document.filename,
size: document.size,
modified: document.modified.toISOString(),
type: path.extname(document.filename)
}
};
} catch (error) {
console.error(`❌ Error preparing document ${document.id}:`, error);
throw error;
}
}
determineEntity(filename) {
const ext = path.extname(filename).toLowerCase();
if (['.pdf', '.doc', '.docx'].includes(ext)) {
return 'documents';
} else if (['.jpg', '.jpeg', '.png', '.gif'].includes(ext)) {
return 'images';
} else if (['.csv', '.xlsx', '.xls'].includes(ext)) {
return 'spreadsheets';
} else {
return 'files';
}
}
async generateIndividualProofs(batchId, documents, batchResult) {
console.log('🔍 Generating individual Merkle proofs...');
for (const document of documents) {
try {
const merkleProof = await this.client.batch.getMerkleProof(batchId, document.id);
console.log(`📄 ${document.filename}:`);
console.log(` 🌳 Leaf Hash: ${merkleProof.leafHash.substring(0, 16)}...`);
console.log(` 📍 Leaf Index: ${merkleProof.leafIndex}`);
console.log(` 🔗 Proof Path Length: ${merkleProof.proofPath.length}`);
// Verify the Merkle proof
const isValid = await this.client.batch.verifyMerkleProof(merkleProof);
console.log(` ✅ Proof Valid: ${isValid.isValid}`);
// Store individual proof data
await this.storeIndividualProof(document, merkleProof, batchResult);
} catch (error) {
console.error(`❌ Error generating proof for ${document.id}:`, error);
}
}
}
async storeIndividualProof(document, merkleProof, batchResult) {
// In a real application, store this data for later verification
const proofData = {
documentId: document.id,
filename: document.filename,
batchId: batchResult.batchId,
merkleRoot: batchResult.merkleRoot,
leafHash: merkleProof.leafHash,
proofPath: merkleProof.proofPath,
leafIndex: merkleProof.leafIndex,
transactionHash: batchResult.transactionHash,
blockNumber: batchResult.blockNumber,
timestamp: batchResult.timestamp
};
// Example: Save to database or file
// await database.save('document_proofs', proofData);
console.log(`📝 Stored proof data for ${document.filename}`);
}
// Utility method to verify a document against its stored proof
async verifyStoredDocument(documentId, storedProofData) {
try {
const merkleProof = {
recordId: documentId,
batchId: storedProofData.batchId,
leafHash: storedProofData.leafHash,
merkleRoot: storedProofData.merkleRoot,
proofPath: storedProofData.proofPath,
leafIndex: storedProofData.leafIndex,
totalLeaves: storedProofData.totalLeaves
};
const verification = await this.client.batch.verifyMerkleProof(merkleProof);
return verification.isValid;
} catch (error) {
console.error(`❌ Error verifying stored document ${documentId}:`, error);
return false;
}
}
}
// Usage example
async function main() {
const processor = new BatchDocumentProcessor('your-api-key-here');
try {
// Process all documents in the directory
await processor.processDailyBatch('./daily-documents');
console.log('✅ Daily batch processing completed successfully!');
} catch (error) {
console.error('❌ Daily batch processing failed:', error);
}
}
main();
What this example demonstrates:
- Automated directory scanning and document discovery
- Batch optimization using Merkle trees to reduce blockchain costs
- Individual proof generation for each document within the batch
- Comprehensive metadata tracking and storage patterns
- Verification workflows for both batch and individual proofs
Cost savings: Processing 100 documents individually might cost $50 in gas fees. Using batch processing with Merkle trees, the same 100 documents cost only ~$2!
Web Application Integration
🌐 React Frontend
Complete React component for document proof creation and verification
Express.js Backend
REST API server with proof endpoints and webhook handling
🔐 Authentication
JWT-based auth with API key management and tenant isolation
Progressive Web App
Offline-capable PWA with batch synchronization
🌐 React Document Proof Component
Complete React component with drag-and-drop file upload and real-time verification
import React, { useState, useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { DataProofLabsClient } from '@dataprooflabs/sdk';
interface ProofResult {
recordId: string;
transactionHash: string;
blockNumber: number;
timestamp: string;
status: 'pending' | 'confirmed' | 'failed';
}
interface DocumentProofComponentProps {
apiKey: string;
onProofCreated?: (proof: ProofResult) => void;
}
export const DocumentProofComponent: React.FC = ({
apiKey,
onProofCreated
}) => {
const [client] = useState(() => new DataProofLabsClient({ apiKey }));
const [proofs, setProofs] = useState([]);
const [isProcessing, setIsProcessing] = useState(false);
const [error, setError] = useState(null);
const onDrop = useCallback(async (acceptedFiles: File[]) => {
if (acceptedFiles.length === 0) return;
setIsProcessing(true);
setError(null);
try {
for (const file of acceptedFiles) {
await processFile(file);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error occurred');
} finally {
setIsProcessing(false);
}
}, [client]);
const processFile = async (file: File): Promise => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (event) => {
try {
if (!event.target?.result) {
throw new Error('Failed to read file');
}
const arrayBuffer = event.target.result as ArrayBuffer;
const uint8Array = new Uint8Array(arrayBuffer);
const base64Data = btoa(String.fromCharCode(...uint8Array));
const recordId = `${file.name}-${Date.now()}`;
// Create temporary proof entry
const tempProof: ProofResult = {
recordId,
transactionHash: '',
blockNumber: 0,
timestamp: new Date().toISOString(),
status: 'pending'
};
setProofs(prev => [...prev, tempProof]);
// Create blockchain proof
const result = await client.proof.create({
recordId,
entityId: 'user-documents',
data: base64Data,
blockchainType: 'Ethereum',
metadata: {
filename: file.name,
fileSize: file.size,
fileType: file.type,
uploadedAt: new Date().toISOString()
}
});
// Update proof with blockchain result
const updatedProof: ProofResult = {
recordId,
transactionHash: result.transactionHash || '',
blockNumber: result.blockNumber || 0,
timestamp: result.timestamp || new Date().toISOString(),
status: result.success ? 'confirmed' : 'failed'
};
setProofs(prev =>
prev.map(p => p.recordId === recordId ? updatedProof : p)
);
onProofCreated?.(updatedProof);
resolve();
} catch (error) {
// Update proof status to failed
setProofs(prev =>
prev.map(p => p.recordId === recordId ? { ...p, status: 'failed' as const } : p)
);
reject(error);
}
};
reader.onerror = () => reject(new Error('Failed to read file'));
reader.readAsArrayBuffer(file);
});
};
const verifyProof = async (recordId: string): Promise => {
try {
const verification = await client.proof.verify(recordId);
if (verification.isValid) {
alert(`✅ Proof verified!\nTransaction: ${verification.transactionHash}\nConfirmations: ${verification.confirmations}`);
} else {
alert('❌ Proof verification failed');
}
} catch (error) {
alert(`Error verifying proof: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
multiple: true,
maxSize: 10 * 1024 * 1024, // 10MB limit
accept: {
'application/pdf': ['.pdf'],
'application/msword': ['.doc'],
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
'text/plain': ['.txt'],
'image/*': ['.png', '.jpg', '.jpeg', '.gif']
}
});
return (
{isDragActive ? (
📄 Drop your files here to create blockchain proofs
) : (
📁
Upload Documents for Blockchain Proof
Drag & drop files here, or click to select
Supports: PDF, DOC, DOCX, TXT, Images (max 10MB each)
)}
{error && (
❌ {error}
)}
{isProcessing && (
Creating blockchain proofs...
)}
Created Proofs ({proofs.length})
{proofs.map((proof) => (
{proof.recordId}
Status:
{proof.status === 'pending' && '🟡 Pending'}
{proof.status === 'confirmed' && '✅ Confirmed'}
{proof.status === 'failed' && '❌ Failed'}
{proof.transactionHash && (
Transaction: {proof.transactionHash.substring(0, 20)}...
)}
))}
);
};
import { useState, useEffect, useCallback } from 'react';
import { DataProofLabsClient } from '@dataprooflabs/sdk';
interface UseDataProofLabsOptions {
apiKey: string;
baseUrl?: string;
}
interface ProofHistory {
recordId: string;
entityId: string;
timestamp: string;
transactionHash: string;
isVerified: boolean;
}
export const useDataProofLabs = (options: UseDataProofLabsOptions) => {
const [client] = useState(() => new DataProofLabsClient(options));
const [history, setHistory] = useState([]);
const [balanceStatus, setBalanceStatus] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Load proof history
const loadHistory = useCallback(async () => {
setLoading(true);
setError(null);
try {
const proofHistory = await client.proof.getHistory();
setHistory(proofHistory);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load history');
} finally {
setLoading(false);
}
}, [client]);
// Load balance status
const loadBalanceStatus = useCallback(async () => {
try {
const balance = await client.proof.getBalanceStatus();
setBalanceStatus(balance);
} catch (err) {
console.error('Failed to load balance status:', err);
}
}, [client]);
// Create proof
const createProof = useCallback(async (proofData: any) => {
setLoading(true);
setError(null);
try {
const result = await client.proof.create(proofData);
// Refresh history after creating proof
await loadHistory();
return result;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create proof');
throw err;
} finally {
setLoading(false);
}
}, [client, loadHistory]);
// Verify proof
const verifyProof = useCallback(async (recordId: string) => {
setLoading(true);
setError(null);
try {
const result = await client.proof.verify(recordId);
return result;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to verify proof');
throw err;
} finally {
setLoading(false);
}
}, [client]);
// Create batch proof
const createBatchProof = useCallback(async (batchData: any) => {
setLoading(true);
setError(null);
try {
const result = await client.batch.create(batchData);
// Refresh history after creating batch
await loadHistory();
return result;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create batch proof');
throw err;
} finally {
setLoading(false);
}
}, [client, loadHistory]);
// Load data on mount
useEffect(() => {
loadHistory();
loadBalanceStatus();
}, [loadHistory, loadBalanceStatus]);
return {
// Data
history,
balanceStatus,
loading,
error,
// Actions
createProof,
verifyProof,
createBatchProof,
loadHistory,
loadBalanceStatus,
// Client instance for advanced usage
client
};
};
Component Features:
- Drag-and-drop file upload with multiple file support
- Real-time proof creation and status tracking
- File type validation and size limits
- Custom React hook for state management
- Comprehensive error handling and user feedback
More Examples Coming Soon
We're continuously adding new code samples and use cases.