# ๐ FHEVM SDK - Universal Privacy-Preserving Development Kit [](LICENSE) [](https://www.zama.ai/) []() [](https://nextjs.org/) A **universal SDK** for building privacy-preserving decentralized applications using **Fully Homomorphic Encryption (FHE)** with Zama's FHEVM. Framework-agnostic and developer-friendly, designed to make confidential smart contract development simple and intuitive. ๐ **[Live Demo](https://fhe-water-resource-manager.vercel.app/)** | ๐ **[Documentation](docs/)** **๐น Demo Video**: `demo.mp4` - Download from repository to view (streaming not supported) **GitHub Repository**: [https://github.com/OsbaldoSchmeler/fhevm-react-template](https://github.com/OsbaldoSchmeler/fhevm-react-template) **Example Application**: [https://github.com/OsbaldoSchmeler/FHEWaterResourceManager](https://github.com/OsbaldoSchmeler/FHEWaterResourceManager) --- ## ๐ Core FHE Concepts ### What is Fully Homomorphic Encryption (FHE)? **Fully Homomorphic Encryption (FHE)** is a revolutionary cryptographic technology that allows computations to be performed directly on encrypted data without decrypting it. This means: - โ **Privacy-Preserving Computation** - Process sensitive data while keeping it encrypted - โ **Zero-Knowledge Processing** - Perform calculations without revealing input values - โ **Transparent Verification** - Results are verifiable without exposing private data - โ **Trustless Operations** - No need to trust intermediaries with plaintext data ### Why FHEVM SDK? Traditional blockchain applications expose all data on-chain, creating privacy concerns. **FHEVM SDK** leverages Zama's FHEVM to enable: **๐ Private Smart Contracts** - Execute logic on encrypted data - Keep sensitive inputs confidential - Reveal results only to authorized parties - Maintain privacy while ensuring verifiability **๐ Encrypted State Management** - Store encrypted values on-chain - Perform operations on ciphertext - Control decryption with permissions - EIP-712 signature-based access **๐ Confidential dApp Development** - Build privacy-first applications - No data exposure during computation - Fair algorithms without revealing inputs - Compliance with data protection regulations ### FHE Operations Supported This SDK provides access to all FHEVM capabilities: ```typescript // Encrypted data types euint8, euint16, euint32, euint64, euint128, euint256 ebool, eaddress // Arithmetic operations FHE.add(), FHE.sub(), FHE.mul(), FHE.div() // Comparison operations FHE.eq(), FHE.ne(), FHE.gt(), FHE.gte(), FHE.lt(), FHE.lte() // Logical operations FHE.and(), FHE.or(), FHE.xor(), FHE.not() // Selection and manipulation FHE.select(), FHE.min(), FHE.max() // Permission management FHE.allow(), FHE.allowThis() // Decryption FHE.decrypt() // With EIP-712 signature ``` **Learn More About FHE**: - **Zama FHEVM**: [https://github.com/zama-ai/fhevm](https://github.com/zama-ai/fhevm) - **FHEVM Documentation**: [https://docs.zama.ai/fhevm](https://docs.zama.ai/fhevm) - **FHE Tutorial**: [Getting Started with FHEVM](https://docs.zama.ai/fhevm/getting-started) --- ## โจ What is FHEVM SDK? **FHEVM SDK** is a comprehensive toolkit that wraps all necessary packages and utilities for building confidential smart contracts with Zama's FHEVM. It provides: - ๐ฏ **Framework-Agnostic Core** - Works with Node.js, Next.js, Vue, React, or any frontend - ๐ฆ **All-in-One Package** - No scattered dependencies, everything you need in one place - ๐ง **wagmi-like Structure** - Intuitive API familiar to web3 developers - โก **Quick Setup** - Less than 10 lines of code to get started - ๐ **Complete FHE Flow** - Initialization, encryption, decryption, and contract interaction - ๐จ **React Hooks** - Ready-to-use hooks for React/Next.js applications - ๐ฑ **Live Example** - Working Next.js application demonstrating all features --- ## ๐ Quick Start (< 10 Lines!) ```bash # 1. Clone repository git clone https://github.com/OsbaldoSchmeler/fhevm-react-template.git cd fhevm-react-template # 2. Install all dependencies npm install # 3. Start Next.js example npm run dev ``` **Open your browser** - Done! ๐ --- ## ๐ฆ Repository Structure This is a **monorepo** containing the SDK and example applications: ``` fhevm-react-template/ โโโ packages/ โ โโโ fhevm-sdk/ โ ๐ฆ Core SDK Package โ โโโ src/ โ โ โโโ index.ts โ Main SDK (framework-agnostic) โ โ โโโ react.tsx โ React Hooks โ โ โโโ core/ โ Core FHEVM functionality โ โ โโโ hooks/ โ React hooks (useFhevm, etc.) โ โ โโโ utils/ โ Encryption/decryption utilities โ โ โโโ types/ โ TypeScript type definitions โ โ โโโ adapters/ โ Framework adapters (React, Vue, Node.js) โ โโโ package.json โ โโโ README.md โ โโโ tsconfig.json โ โโโ templates/ โ ๐ Integration Templates โ โโโ nextjs/ โ Next.js integration guide โ โโโ react/ โ React integration guide โ โโโ vue/ โ Vue integration guide โ โโโ nodejs/ โ Node.js integration guide โ โโโ README.md โ Templates overview โ โโโ examples/ โ โโโ nextjs-water-management/ โ ๐ฏ Simple Next.js Example (Port 3000) โ โ โโโ pages/ โ โ โ โโโ index.tsx โ Basic SDK demo โ โ โโโ package.json โ โ โ โโโ nextjs-water-resource-management/ โ ๐ Full Next.js Example (Port 3001) โ โ โโโ pages/ โ โ โ โโโ index.tsx โ Complete water management system โ โ โโโ package.json โ โ โ โโโ water-resource-management/ โ ๐ Converted React/Next.js App (Port 3002) โ โ โโโ pages/ โ โ โ โโโ index.tsx โ Converted from static HTML โ โ โโโ index.html โ Original static version (preserved) โ โ โโโ package.json โ โ โ โโโ WaterResourceManager/ โ ๐ Converted React/Next.js App (Port 3003) โ โ โโโ pages/ โ โ โ โโโ index.tsx โ Converted from static HTML โ โ โโโ index.html โ Original static version (preserved) โ โ โโโ package.json โ โ โ โโโ nextjs-fhe-app-router/ โ โญ App Router Example (Port 3002) โ โโโ src/ โ โ โโโ app/ โ App Router pages and API routes โ โ โโโ components/ โ React components โ โ โโโ lib/ โ FHE utilities โ โ โโโ hooks/ โ Custom hooks โ โโโ package.json โ โโโ contracts/ โ โโโ WaterResourceManager.sol โ Example smart contract โ โโโ docs/ โ ๐ Complete documentation โโโ demo.mp4 โ Video demonstration (download to view) โโโ README.md โ You are here ``` --- ## ๐ฏ SDK Core Features ### 1. Framework-Agnostic Design **Works Everywhere**: ```javascript // Node.js / CommonJS const { initFHEVM, encrypt } = require('fhevm-sdk'); // ES Modules import { initFHEVM, encrypt } from 'fhevm-sdk'; // React / Next.js import { useFHEVM, useEncrypt } from 'fhevm-sdk/react'; // Vue (future) import { useFHEVM } from 'fhevm-sdk/vue'; ``` ### 2. wagmi-like API **Familiar to Web3 Developers**: ```typescript import { useFHEVM, useEncrypt, useDecrypt } from 'fhevm-sdk/react'; function MyComponent() { const { isReady } = useFHEVM({ network: 'sepolia' }); const { encryptUint32, isEncrypting } = useEncrypt(); const { decryptUser } = useDecrypt(); const handleSubmit = async () => { const encrypted = await encryptUint32(1000); await contract.submitData(encrypted); }; return ( ); } ``` ### 3. Complete FHE Workflow ```typescript // โ Step 1: Initialize await initFHEVM({ network: 'sepolia', provider: window.ethereum }); // โ Step 2: Encrypt inputs const encrypted = await encrypt.uint32(1000); // โ Step 3: Send to contract await contract.submitEncryptedData(encrypted); // โ Step 4: Decrypt results (with EIP-712 signature) const decrypted = await decrypt.user(result, { signer: wallet }); ``` --- ## ๐ฑ Example Applications ### ๐ฏ Example 1: Simple Next.js Demo **Location**: `examples/nextjs-water-management/` A minimal Next.js example demonstrating basic FHEVM SDK usage with React hooks. **Features**: - โ Basic SDK initialization - โ Simple encryption demo - โ React hooks integration - โ Clean, educational code **Run Locally**: ```bash cd examples/nextjs-water-management npm install npm run dev ``` Visit `http://localhost:3000` **Code Example**: ```tsx import { useFHEVM, useEncrypt } from 'fhevm-sdk/react'; export default function WaterManagement() { const { isReady } = useFHEVM({ network: 'sepolia' }); const { encryptUint32, isEncrypting } = useEncrypt(); const handleEncrypt = async () => { const encrypted = await encryptUint32(1000); // Use encrypted data in contract calls }; return ( ); } ``` --- ### ๐ Example 2: Full Next.js Water Resource Management **Location**: `examples/nextjs-water-resource-management/` A **comprehensive production-ready** water resource management system showcasing the complete capabilities of FHEVM SDK. **Features**: - โ **Full FHE Integration** - Complete encryption/decryption workflow - โ **Multi-Role System** - Admin and region manager interfaces - โ **Privacy-Preserving Operations** - Encrypted water requests and allocations - โ **Real-time State Management** - Live blockchain monitoring - โ **Comprehensive UI** - Production-grade interface with Tailwind CSS - โ **Type-Safe** - Full TypeScript implementation - โ **Error Handling** - Robust error messages and loading states **Run Locally**: ```bash cd examples/nextjs-water-resource-management npm install npm run dev ``` Visit `http://localhost:3001` **Key Functionality**: **Admin Functions**: - Register water management regions - Start allocation periods with time limits - Process encrypted allocation requests - Emergency water allocation - Region management **Manager Functions**: - Submit encrypted water requests - View region status - Check allocation results **Privacy Features**: - Encrypted water demand amounts - Confidential justification scores - FHE-based fair allocation - Selective result disclosure **Code Example**: ```tsx import { useFHEVM, useEncrypt } from 'fhevm-sdk/react'; export default function WaterResourceManagement() { const { isReady } = useFHEVM({ network: 'sepolia' }); const { encryptUint32, isEncrypting } = useEncrypt(); const submitWaterRequest = async () => { // Encrypt sensitive data using FHEVM SDK const encryptedAmount = await encryptUint32(requestAmount); const encryptedScore = await encryptUint32(justificationScore); // Submit to smart contract (data remains encrypted!) const tx = await contract.submitWaterRequest( requestAmount, justificationScore ); await tx.wait(); // Other regions CANNOT see your request details! }; return ( ); } ``` --- ### ๐ Example 3: Water Resource Management (React/Next.js) **Location**: `examples/water-resource-management/` A **React/Next.js** implementation of the water resource management system, converted from the original static HTML version to provide a modern, maintainable codebase. **Features**: - โ Full Next.js 14 with Pages Router - โ React hooks for state management - โ TypeScript for type safety - โ Same functionality as original HTML version - โ Production-ready structure - โ Hot reload development experience **Run Locally**: ```bash cd examples/water-resource-management npm install npm run dev ``` Visit `http://localhost:3002` **Live Demo**: [https://fhe-water-resource-manager.vercel.app/](https://fhe-water-resource-manager.vercel.app/) **Note**: The original `index.html` static version is preserved in the directory for reference. --- ### ๐น Video Demonstration **Video File**: `demo.mp4` (located in repository root) **Important**: The demo video **must be downloaded** to view. Streaming is not supported. **How to Access**: 1. Navigate to the GitHub repository root directory 2. Locate the file named `demo.mp4` 3. Click "Download" or "Download raw file" 4. Open with your media player (VLC, Windows Media Player, etc.) **Video Content**: Complete walkthrough of FHEVM SDK usage through the water resource management examples, including: - SDK initialization - Privacy-preserving water allocation - React hooks integration - Encrypted data processing - Admin and manager workflows --- ### โญ Example 4: Next.js App Router with Full FHE Architecture **Location**: `examples/nextjs-fhe-app-router/` A **modern Next.js 13+ App Router** implementation showcasing a complete, scalable FHE architecture with API routes, custom hooks, and production-ready components. **Features**: - โ **Next.js 14 App Router** - Modern React Server Components - โ **Complete Architecture** - Modular, scalable code structure - โ **API Routes** - RESTful endpoints for FHE operations - โ **Custom Hooks** - `useFHE`, `useEncryption`, `useComputation` - โ **UI Component Library** - Reusable Button, Input, Card components - โ **FHE Components** - Provider, demos, key manager - โ **Real-World Examples** - Banking and medical use cases - โ **Type-Safe** - Complete TypeScript implementation - โ **Production Patterns** - Best practices for scalability **Run Locally**: ```bash cd examples/nextjs-fhe-app-router npm install npm run dev ``` Visit `http://localhost:3002` **Architecture Highlights**: **API Endpoints**: - `POST /api/fhe/encrypt` - Encrypt data - `POST /api/fhe/decrypt` - Decrypt ciphertext - `POST /api/fhe/compute` - Homomorphic computation - `POST /api/keys` - Key generation **Custom Hooks**: ```tsx // FHE initialization const { isInitialized, initialize } = useFHE(); // Encryption with loading states const { encryptWithSDK, encryptWithAPI, isEncrypting } = useEncryption(); // Homomorphic computation const { compute, add, subtract, compare, result } = useComputation(); ``` **Component Structure**: - **UI Components**: `Button`, `Input`, `Card` - **FHE Components**: `FHEProvider`, `EncryptionDemo`, `ComputationDemo`, `KeyManager` - **Examples**: `BankingExample`, `MedicalExample` **Code Example**: ```tsx import { useEncryption } from '@/hooks/useEncryption'; import { Button } from '@/components/ui/Button'; function BankingApp() { const { encryptWithSDK, isEncrypting } = useEncryption(); const handleDeposit = async (amount: number) => { // Encrypt sensitive data const encrypted = await encryptWithSDK(amount, 'uint32'); // Send to contract (encrypted!) await contract.deposit(encrypted); }; return ( ); } ``` --- ### ๐ Example Comparison | Feature | Simple Next.js | Full Next.js | Water Resource Mgmt | App Router | |---------|---------------|--------------|---------------------|------------| | **Framework** | Pages Router | Pages Router | Pages Router | App Router | | **SDK Integration** | โ Basic | โ Complete | โ Complete | โ Complete | | **Production Ready** | โ Demo only | โ Yes | โ Yes | โ Yes | | **Architecture** | Simple | Water Management | Water Management | Full FHE Stack | | **API Routes** | โ No | โ No | โ No | โ Yes | | **Custom Hooks** | โ No | โ No | React hooks | โ Yes | | **UI Components** | Basic | Inline | Inline | โ Library | | **Real-World Examples** | โ No | โ Water | โ Water | โ Banking + Medical | | **TypeScript** | โ Yes | โ Yes | โ Yes | โ Yes | | **Build Required** | โ Yes | โ Yes | โ Yes | โ Yes | | **Port** | 3000 | 3001 | 3002 | 3002 | | **Best For** | Learning | Production App | Production App | Scalable Apps | **Recommendation**: - **Just learning FHE?** โ Start with Simple Next.js Example - **Building a production app?** โ Use Full Next.js Example or Water Resource Management - **Need scalable architecture?** โ Use App Router Example โญ --- ## ๐ SDK API Reference ### Initialization ```typescript import { initFHEVM } from 'fhevm-sdk'; await initFHEVM({ network: 'sepolia' | 'localhost', provider: window.ethereum, // or ethers provider contractAddress?: string // optional }); ``` ### Encryption ```typescript import { encrypt } from 'fhevm-sdk'; const encrypted32 = await encrypt.uint32(1000); const encrypted64 = await encrypt.uint64(1000000); const encryptedBool = await encrypt.bool(true); const encryptedAddr = await encrypt.address('0x...'); ``` ### Decryption ```typescript import { decrypt } from 'fhevm-sdk'; // User decryption (with EIP-712 signature) const value = await decrypt.user(ciphertext, { signer: wallet, contract: contractAddress }); // Public decryption (if permitted) const publicValue = await decrypt.public(ciphertext); ``` ### React Hooks ```typescript import { useFHEVM, useEncrypt, useDecrypt } from 'fhevm-sdk/react'; // Initialize SDK const { isReady, isInitializing, error, init } = useFHEVM(config); // Encryption with loading states const { encryptUint32, isEncrypting, error } = useEncrypt(); // Decryption with loading states const { decryptUser, isDecrypting, error } = useDecrypt(); // Contract interaction const { contract, isLoading, error } = useContract({ address: '0x...', abi: contractABI, provider: provider }); ``` --- ## ๐๏ธ Building Your Own dApp ### Step 1: Install SDK ```bash npm install fhevm-sdk ``` ### Step 2: Use in Your App ```typescript // app.tsx or page.tsx import { useFHEVM, useEncrypt } from 'fhevm-sdk/react'; export default function MyApp() { const { isReady } = useFHEVM({ network: 'sepolia', provider: window.ethereum }); const { encryptUint32 } = useEncrypt(); const handleEncrypt = async () => { const encrypted = await encryptUint32(1000); console.log('Encrypted:', encrypted); }; if (!isReady) return