Framework-agnostic SDK for building privacy-preserving applications with Zama's Fully Homomorphic Encryption
This repository contains a universal, framework-agnostic SDK for building privacy-preserving decentralized applications using Zama's Fully Homomorphic Encryption technology.
Live Demo: https://carbon-credit-trading-fhe.vercel.app/
Demo Video: demo.mp4 (Download to watch - streaming not available)
- Overview
- Key Features
- Quick Start
- Installation
- Usage
- Example Application
- API Reference
- Architecture
- Documentation
- Bounty Requirements
- License
The Universal FHEVM SDK provides a comprehensive toolkit for integrating Zama's Fully Homomorphic Encryption into any JavaScript/TypeScript application. It delivers:
✅ Framework-Agnostic Core - Works with Node.js, Next.js, Vue, React, or any frontend setup ✅ All-in-One Package - Wraps all required dependencies, no scattered setup ✅ wagmi-like Structure - Intuitive API for web3 developers ✅ Official Zama Integration - Follows Zama's official SDK and guidelines ✅ Less Than 10 Lines - Minimal setup time, maximum productivity
Current FHEVM development requires:
- Managing multiple scattered dependencies
- Framework-specific implementations
- Complex encryption/decryption setup
- Repetitive boilerplate code
A single, universal SDK that:
- Consolidates all FHEVM dependencies
- Provides consistent API across frameworks
- Simplifies encryption/decryption flows
- Offers reusable components and utilities
// Works anywhere - Node.js, React, Vue, Svelte, etc.
import { FhevmClient, initFhevm } from '@fhevm/sdk';
const client = await initFhevm({ provider, chainId: 11155111 });
const encrypted = await client.encrypt(1000);No more juggling multiple packages:
{
"dependencies": {
"@fhevm/sdk": "^1.0.0" // Everything you need!
}
}Familiar patterns for web3 developers:
// Initialization
const { client, isReady } = useFhevm({ provider, network });
// Encryption
const { encrypt, isEncrypting } = useEncrypt();
const encrypted = await encrypt(value);
// Decryption
const { decrypt, data } = useDecrypt();
const decrypted = await decrypt(handle);import { useFhevm, useEncrypt, useDecrypt } from '@fhevm/sdk/react';
function MyComponent() {
const { client } = useFhevm();
const { encrypt } = useEncrypt(client);
const { decrypt } = useDecrypt(client);
// Use encryption in your component
}- ✅ Initialize - Simple setup with provider
- ✅ Encrypt Inputs - Type-safe encryption with automatic type inference
- ✅ User Decrypt - EIP-712 signature-based decryption
- ✅ Public Decrypt - For public encrypted values
- ✅ Batch Operations - Encrypt/decrypt multiple values efficiently
# Navigate to project directory
cd fhevm-react-template
# Install all packages
npm install
# Build SDK
npm run build:sdk
# Run Next.js example
npm run dev:nextjs# Copy Next.js template to start a new project
cp -r templates/nextjs my-new-project
cd my-new-project
npm install
npm run dev# Compile Solidity contracts
npm run compile
# Deploy to Sepolia
npm run deploy:sepolia
# Generate ABIs
npm run generate:abi# Start development server
npm run dev:nextjs
# Open browser
# Visit applicationnpm install @fhevm/sdk
# or
yarn add @fhevm/sdk
# or
pnpm add @fhevm/sdk# Install all dependencies
npm install
# Link SDK locally
npm run link:sdkPerfect for Node.js, backends, or any JavaScript environment:
import { FhevmClient } from '@fhevm/sdk';
import { ethers } from 'ethers';
// Setup
const provider = new ethers.BrowserProvider(window.ethereum);
const client = new FhevmClient({
provider,
network: {
chainId: 11155111,
name: 'sepolia',
rpcUrl: 'https://sepolia.infura.io/v3/YOUR_KEY'
}
});
// Initialize
await client.init();
// Encrypt values
const encryptedAmount = await client.encrypt(1000, {
type: 'euint32',
contractAddress: '0x...'
});
// Use in contract call
const tx = await contract.transfer(
recipient,
encryptedAmount.handles,
encryptedAmount.inputProof
);
// Decrypt results
const balance = await client.decrypt({
contractAddress: '0x...',
handle: '0x...',
signer: await provider.getSigner()
});
console.log('Balance:', balance.value);For React applications with hooks:
import { FhevmProvider, useFhevm, useEncrypt, useDecrypt } from '@fhevm/sdk/react';
// App.tsx
function App() {
return (
<FhevmProvider network={{ chainId: 11155111 }}>
<MyComponent />
</FhevmProvider>
);
}
// MyComponent.tsx
function MyComponent() {
const { client, isReady } = useFhevm();
const { encrypt, isEncrypting } = useEncrypt();
const { decrypt, data, isDecrypting } = useDecrypt();
const handleEncrypt = async () => {
const encrypted = await encrypt(1000, {
type: 'euint32',
contractAddress: contractAddress
});
// Use encrypted.handles and encrypted.inputProof
await contract.someFunction(encrypted.handles, encrypted.inputProof);
};
const handleDecrypt = async () => {
const decrypted = await decrypt({
contractAddress,
handle: encryptedHandle,
signer
});
console.log('Decrypted value:', decrypted.value);
};
if (!isReady) return <div>Initializing FHEVM...</div>;
return (
<div>
<button onClick={handleEncrypt} disabled={isEncrypting}>
Encrypt & Send
</button>
<button onClick={handleDecrypt} disabled={isDecrypting}>
Decrypt
</button>
{data && <p>Decrypted: {data.value.toString()}</p>}
</div>
);
}Complete Next.js application demonstrating SDK integration:
cd examples/nextjs-carbon-trading
npm install
npm run devFor backend or scripts:
import { initFhevm, encryptInput, decryptOutput } from '@fhevm/sdk';
import { ethers } from 'ethers';
// Initialize
const provider = new ethers.JsonRpcProvider(process.env.RPC_URL);
const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const fhevm = await initFhevm({
provider,
signer,
network: { chainId: 11155111 }
});
// Encrypt
const encrypted = await encryptInput(fhevm, 1000, {
type: 'euint32',
contractAddress: process.env.CONTRACT_ADDRESS
});
// Call contract
const contract = new ethers.Contract(address, abi, signer);
const tx = await contract.deposit(encrypted.handles, encrypted.inputProof);
await tx.wait();
// Decrypt
const handle = await contract.getBalance(signer.address);
const decrypted = await decryptOutput(fhevm, {
contractAddress: process.env.CONTRACT_ADDRESS,
handle,
signer
});
console.log('Balance:', decrypted.value);This repository includes two comprehensive examples demonstrating the SDK integration:
A complete privacy-preserving carbon credit marketplace with modern React UI and full FHEVM integration.
Location: examples/nextjs-carbon-trading/
Live Demo: https://carbon-credit-trading-fhe.vercel.app/
Features:
- ✅ Complete Next.js 14 App Router implementation
- ✅ React Hooks Integration (
useFhevm,useEncrypt,useDecrypt) - ✅ Encrypted credit amounts and private pricing
- ✅ Confidential balances with EIP-712 decryption
- ✅ Homomorphic trade execution
- ✅ Modern UI with Tailwind CSS
- ✅ API routes for server-side FHE operations
- ✅ Complete component library with FHE, UI, and example components
Components:
BalanceViewer.tsx- View and decrypt encrypted balancesCreditIssuer.tsx- Issue carbon credits with encrypted amountsOrderManager.tsx- Create privacy-preserving buy ordersTradeExecutor.tsx- Execute trades on encrypted dataFHEProvider.tsx- FHE context and client managementEncryptionDemo.tsx- Interactive encryption demonstrationsComputationDemo.tsx- Homomorphic computation examplesBankingExample.tsx- Private banking use caseMedicalExample.tsx- Private medical records use case
Run Example:
# From root directory
npm run dev:nextjs
# Or from example directory
cd examples/nextjs-carbon-trading
npm install
npm run devModern React application with Vite, TypeScript, and complete FHEVM SDK integration.
Location: examples/carbon-credit-trading/
Features:
- ✅ React 18 with TypeScript
- ✅ Vite for fast development and optimized builds
- ✅ Full FHEVM SDK integration with custom hooks
- ✅ Smart contracts with FHE operations
- ✅ Comprehensive test suite with 66+ test scenarios
- ✅ Deployment scripts for multiple networks
- ✅ Interactive CLI with 15+ commands
- ✅ Privacy-preserving carbon credit trading logic
- ✅ Component-based architecture with separation of concerns
- ✅ Cyberpunk-themed UI with responsive design
Key Components:
UserRegistration- User account registrationCreditManagement- Issue credits with encrypted amountsOrderManagement- Create buy orders with encrypted valuesTradeExecution- Execute trades on encrypted dataBalanceDisplay- View and decrypt token balances
Custom Hooks:
useFHE- FHE client initialization and encryption/decryption operationsuseWallet- Wallet connection and account managementuseContract- Type-safe contract interactions with FHE integration
Run Example:
# From root directory
cd examples/carbon-credit-trading
# Install dependencies
npm install
# Start local Hardhat node (in separate terminal)
npm run node
# Deploy contracts (in separate terminal)
npm run deploy:localhost
# Start React application
npm run devKey Workflows:
- User registration with encrypted balances
- Credit issuance with private amounts and verification (auto-encrypted)
- Order creation with encrypted parameters (auto-encrypted)
- Trade execution with homomorphic operations
- Balance viewing with authorized decryption (EIP-712 signatures)
- Regulatory compliance with privacy preservation
Initialize FHEVM instance.
const fhevm = await initFhevm({
provider: ethersProvider,
network: { chainId: 11155111 }
});Encrypt a value for contract input.
const encrypted = await encryptInput(client, 1000, {
type: 'euint32',
contractAddress: '0x...'
});Decrypt a value from contract (user decrypt with EIP-712).
const decrypted = await decryptOutput(client, {
contractAddress: '0x...',
handle: '0x...',
signer: signer
});Public decryption for non-sensitive values.
const value = await publicDecrypt(client, contractAddress, handle);Access FHEVM client instance.
const { client, isReady, error } = useFhevm();Encrypt values with loading state.
const { encrypt, isEncrypting, error } = useEncrypt();Decrypt values with loading state.
const { decrypt, data, isDecrypting, error } = useDecrypt();fhevm-react-template/
├── packages/
│ └── fhevm-sdk/ # Universal SDK package
│ ├── src/
│ │ ├── index.ts # Main exports
│ │ ├── client.ts # FhevmClient class
│ │ ├── types.ts # TypeScript types
│ │ ├── provider.tsx # React Provider & Hooks
│ │ ├── encryption.ts # Encryption utilities
│ │ ├── decryption.ts # Decryption utilities
│ │ ├── instance.ts # Instance management
│ │ ├── utils.ts # Helper utilities
│ │ └── package.json # SDK configuration
│ └── README.md # SDK documentation
│
├── templates/ # Starter templates
│ ├── nextjs/ # Next.js starter template
│ └── README.md # Template documentation
│
├── examples/
│ ├── nextjs-carbon-trading/ # Next.js Example
│ │ ├── src/
│ │ │ ├── app/
│ │ │ │ ├── layout.tsx # Root layout with providers
│ │ │ │ ├── page.tsx # Main page
│ │ │ │ ├── providers.tsx # FhevmProvider wrapper
│ │ │ │ ├── globals.css # Global styles
│ │ │ │ └── api/ # API routes
│ │ │ │ ├── fhe/ # FHE operations endpoints
│ │ │ │ └── keys/ # Key management endpoints
│ │ │ ├── components/
│ │ │ │ ├── ui/ # UI components
│ │ │ │ ├── fhe/ # FHE components
│ │ │ │ ├── examples/ # Example use cases
│ │ │ │ ├── BalanceViewer.tsx # View encrypted balances
│ │ │ │ ├── CreditIssuer.tsx # Issue carbon credits
│ │ │ │ ├── OrderManager.tsx # Create buy orders
│ │ │ │ └── TradeExecutor.tsx # Execute trades
│ │ │ ├── hooks/ # Custom React hooks
│ │ │ ├── lib/ # Utility libraries
│ │ │ └── types/ # TypeScript type definitions
│ │ ├── package.json
│ │ ├── next.config.js
│ │ ├── tailwind.config.ts
│ │ └── README.md
│ │
│ └── carbon-credit-trading/ # React Example (Vite + TypeScript)
│ ├── src/
│ │ ├── App.tsx # Main application component
│ │ ├── main.tsx # React entry point
│ │ ├── App.css # Application styles
│ │ ├── components/ # React components
│ │ │ ├── UserRegistration.tsx
│ │ │ ├── CreditManagement.tsx
│ │ │ ├── OrderManagement.tsx
│ │ │ ├── TradeExecution.tsx
│ │ │ └── BalanceDisplay.tsx
│ │ ├── hooks/ # Custom hooks
│ │ │ ├── useFHE.ts # FHEVM SDK integration
│ │ │ ├── useWallet.ts # Wallet connection
│ │ │ └── useContract.ts # Contract interactions
│ │ ├── lib/
│ │ │ ├── contract.ts # Contract utilities
│ │ │ ├── fhevm.ts # FHE utilities
│ │ │ └── abi.json # Contract ABI
│ │ └── types/
│ │ └── index.ts # TypeScript types
│ ├── public/ # Static assets
│ │ ├── index.html # Original static HTML
│ │ ├── app.js # Original JavaScript
│ │ └── style.css # Original styles
│ ├── contracts/
│ │ └── CarbonCreditTradingFHEVM.sol # Main contract
│ ├── scripts/
│ │ ├── deploy.js # Deployment script
│ │ └── interact.js # Interaction CLI
│ ├── test/
│ │ └── CarbonCreditTradingFHEVM.test.js
│ ├── vite.config.ts # Vite configuration
│ ├── tsconfig.json # TypeScript configuration
│ ├── package.json
│ ├── hardhat.config.js
│ └── README-REACT.md # React app documentation
│
├── docs/ # Documentation
│ ├── API.md # Complete API reference
│ ├── ARCHITECTURE.md # System design
│ └── DEPLOYMENT.md # Deployment guide
│
├── package.json # Root package.json
├── demo.mp4 # Demo video
└── README.md # This file
Comprehensive documentation available in docs/:
- API Reference - Complete API documentation
- Architecture - System design and structure
- Deployment Guide - How to deploy contracts
- Templates Guide - Starter templates for different frameworks
- Framework-agnostic core - Works with Node.js, React, Vue, any framework
- Initialization utilities - Simple
initFhevm()andcreateFhevmInstance()functions - Encryption/decryption - Complete
encryptInput(),userDecrypt()with EIP-712 +publicDecrypt() - Developer-friendly API - Intuitive hooks and functions with full TypeScript support
- Reusable utilities - Helper functions for validation, formatting, and type handling
- Instance management - Global and scoped instance handling
- Clean & extensible - Well-structured, documented, easy to extend
- Complete Next.js 14 app - Full-featured frontend with App Router
- SDK integration - Demonstrates all SDK hooks and utilities
- 4 Core Components:
BalanceViewer- View and decrypt encrypted balancesCreditIssuer- Issue carbon credits with encrypted amountsOrderManager- Create privacy-preserving buy ordersTradeExecutor- Execute trades on encrypted data
- Tailwind CSS - Modern, responsive UI design
- TypeScript - Type-safe throughout with full IntelliSense
- Smart contract - Carbon Credit Trading with FHE operations
- Comprehensive testing - 66+ test scenarios with high code coverage
- Deployment scripts - Automated deployment for multiple networks
- Interactive CLI - 15+ commands for contract interaction
- Complete workflows - End-to-end privacy-preserving trading scenarios
- Minimal setup - Less than 10 lines to start using SDK
- Clear documentation - Comprehensive guides and API reference
- Type-safe - Full TypeScript support with IntelliSense
- Working examples - Both frontend and backend implementations
- ✅ Complete Repository - SDK package with examples
- ✅ Example Applications - Next.js frontend + Smart contracts
- ✅ Video Demo -
demo.mp4showcasing setup and features - ✅ Live Deployment - Production demo on Vercel
- ✅ Documentation - Comprehensive README and API docs
Unlike template-specific solutions, this SDK works anywhere:
- ✅ React / Next.js
- ✅ Vue / Nuxt
- ✅ Svelte / SvelteKit
- ✅ Node.js backends
- ✅ Vanilla JavaScript
- ✅ TypeScript projects
- Comprehensive testing - 66+ unit tests with high coverage
- Full TypeScript support with type inference
- Error handling with custom error types and validation
- Gas optimized contracts with security hardening
- DoS protection and access control mechanisms
The Carbon Credit Trading Platform demonstrates:
- Complex homomorphic operations on encrypted data
- Multi-role access control and permissions
- Encrypted order matching and execution
- Privacy-preserving settlements and balance management
- EIP-712 signature-based decryption
- Instant setup - One command installation
- Comprehensive documentation - Complete guides and API reference
- Clear examples - Multiple usage patterns and scenarios
- Active development - Ready for community contributions and extensions
# 1. Navigate to project directory
cd fhevm-react-template
# 2. Install all dependencies
npm install
# 3. Build SDK package
npm run build:sdk
# 4. Deploy smart contracts (optional)
npm run compile
npm run deploy:sepolia
# 5. Run Next.js example application
npm run dev:nextjsThat's it! You're ready to build privacy-preserving applications with FHEVM.
MIT License - see LICENSE for details.
Special thanks to:
- Zama Team - For pioneering Fully Homomorphic Encryption technology
- FHEVM Community - For feedback, support, and collaboration
- Web3 Developers - For inspiring this developer-friendly SDK design
- Documentation: Full Docs
- Live Demo: https://carbon-credit-trading-fhe.vercel.app/
- API Reference: API.md
- Architecture Guide: ARCHITECTURE.md
Project Status: ✅ Complete & Production Ready
Powered by Zama FHEVM 🔐