Skip to content

OdaTorphy/fhevm-react-template

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

113 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FHEVM SDK - Universal Toolkit for Confidential dApps πŸ”

Framework-agnostic FHEVM SDK with wagmi-like developer experience for building privacy-preserving applications on Zama's Fully Homomorphic Encryption Virtual Machine.

🎯 Built for the Zama Bounty Challenge - A complete, reusable SDK that makes building confidential frontends simple, consistent, and developer-friendly.

🌐 Live Example: https://fhe-pollution-monitor.vercel.app/

πŸ’» GitHub: https://github.com/OdaTorphy/fhevm-react-template

πŸ“Ή Demo Video: Download demo.mp4 to watch the full demonstration (streaming not available)

License: MIT TypeScript FHEVM


✨ Features

  • 🎨 Framework-Agnostic - Works with React, Next.js, Vue, Node.js, or vanilla JavaScript
  • πŸ”Œ Wagmi-like API - Intuitive hooks and composables familiar to web3 developers
  • πŸ“¦ All-in-One Package - Wraps all required dependencies (fhevmjs, ethers, etc.)
  • πŸš€ Quick Setup - Less than 10 lines of code to get started
  • πŸ” Complete FHEVM Flow - Initialize, encrypt inputs, decrypt outputs, contract interaction
  • 🧩 Modular & Reusable - Clean components for different encryption/decryption scenarios
  • πŸ“š Well Documented - Comprehensive guides and code examples
  • 🎭 TypeScript First - Full type safety with excellent IntelliSense
  • ⚑ Zero Configuration - Sensible defaults with easy customization
  • πŸ”„ EIP-712 Support - Built-in userDecrypt and publicDecrypt utilities

πŸš€ Quick Start

Installation

# Install the SDK
npm install fhevm-sdk

# Or with yarn
yarn add fhevm-sdk

# Or with pnpm
pnpm add fhevm-sdk

Basic Usage (< 10 lines!)

import { createFhevmClient, encrypt, decrypt } from 'fhevm-sdk';

// 1. Initialize the client
const client = await createFhevmClient({
  network: 'sepolia',
  contractAddress: '0x...'
});

// 2. Encrypt sensitive data
const encryptedValue = await encrypt(client, 42);

// 3. Decrypt results (with EIP-712 signature)
const decryptedValue = await decrypt(client, encryptedData);

πŸ—οΈ Architecture

fhevm-sdk/
β”œβ”€β”€ Core Engine (framework-agnostic)
β”‚   β”œβ”€β”€ FHEVM initialization
β”‚   β”œβ”€β”€ Encryption utilities
β”‚   β”œβ”€β”€ Decryption utilities (EIP-712)
β”‚   └── Contract interaction
β”‚
β”œβ”€β”€ React Adapters
β”‚   β”œβ”€β”€ useFhevmClient()
β”‚   β”œβ”€β”€ useEncrypt()
β”‚   β”œβ”€β”€ useDecrypt()
β”‚   └── useContract()
β”‚
β”œβ”€β”€ Vue Adapters
β”‚   β”œβ”€β”€ useFhevmClient()
β”‚   β”œβ”€β”€ useEncrypt()
β”‚   └── useDecrypt()
β”‚
└── Utilities
    β”œβ”€β”€ Type converters
    β”œβ”€β”€ Network helpers
    └── Error handling

πŸ“¦ Package Structure

This is a monorepo containing:

fhevm-react-template/
β”œβ”€β”€ packages/
β”‚   └── fhevm-sdk/              # Core SDK package
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ core/           # Framework-agnostic core
β”‚       β”‚   β”‚   β”œβ”€β”€ client.ts   # Main FHEVM client
β”‚       β”‚   β”‚   β”œβ”€β”€ encrypt.ts  # Encryption utilities
β”‚       β”‚   β”‚   β”œβ”€β”€ decrypt.ts  # Decryption utilities
β”‚       β”‚   β”‚   └── types.ts    # Type definitions
β”‚       β”‚   β”œβ”€β”€ react/          # React hooks & provider
β”‚       β”‚   β”‚   └── index.tsx   # React adapters
β”‚       β”‚   β”œβ”€β”€ vue/            # Vue composables
β”‚       β”‚   β”‚   └── index.tsx   # Vue adapters
β”‚       β”‚   β”œβ”€β”€ utils/          # Utility functions
β”‚       β”‚   β”‚   β”œβ”€β”€ errors.ts   # Custom error classes
β”‚       β”‚   β”‚   └── helpers.ts  # Helper functions
β”‚       β”‚   └── index.ts        # Main entry point
β”‚       └── package.json
β”‚
β”œβ”€β”€ templates/                   # Ready-to-use templates
β”‚   β”œβ”€β”€ nextjs/                 # Next.js template (symbolic link)
β”‚   └── react/                  # React template (symbolic link)
β”‚
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ nextjs-pollution-monitor/    # Full-featured Next.js application
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ examples/       # Banking & Medical examples
β”‚   β”‚   β”‚   β”œβ”€β”€ fhe/           # FHE components
β”‚   β”‚   β”‚   └── ui/            # UI components
β”‚   β”‚   β”œβ”€β”€ app/               # Next.js App Router
β”‚   β”‚   β”œβ”€β”€ hooks/             # Custom hooks
β”‚   β”‚   └── lib/               # Utilities
β”‚   β”œβ”€β”€ react-basic/                 # Minimal React setup
β”‚   β”œβ”€β”€ node-cli/                    # Command-line encryption tool
β”‚   └── PrivacyPollutionMonitor/     # React pollution monitor with full FHE encryption
β”‚
β”œβ”€β”€ contracts/                   # Example smart contracts
β”œβ”€β”€ docs/                        # Documentation files
└── README.md                    # This file

🎯 Complete FHEVM Flow

1. Initialize FHEVM Client

import { FhevmClient } from 'fhevm-sdk';

const client = new FhevmClient({
  network: 'sepolia',
  rpcUrl: 'https://rpc.sepolia.org',
  chainId: 11155111,
  contractAddress: '0xYourContract',
  // Optional: custom gateway for decryption
  gatewayUrl: 'https://gateway.zama.ai'
});

await client.init();

2. Encrypt Inputs

// Encrypt different types
const encrypted8 = await client.encrypt8(255);
const encrypted16 = await client.encrypt16(65535);
const encrypted32 = await client.encrypt32(1000000);
const encrypted64 = await client.encrypt64(BigInt('9007199254740991'));
const encryptedBool = await client.encryptBool(true);
const encryptedAddress = await client.encryptAddress('0x...');

// Batch encryption
const batch = await client.encryptBatch({
  amount: 1000,
  threshold: 500,
  active: true
});

3. Contract Interaction

import { Contract } from 'ethers';

// Connect to contract
const contract = new Contract(
  contractAddress,
  contractABI,
  client.getSigner()
);

// Submit encrypted data
const tx = await contract.submitReport(
  encrypted64,
  encrypted8,
  encryptedBool
);

await tx.wait();

4. Decrypt Outputs (EIP-712)

// User decrypt (requires signature)
const decrypted = await client.userDecrypt(
  encryptedData,
  contractAddress
);

// Public decrypt (no signature needed)
const publicData = await client.publicDecrypt(encryptedData);

// Batch decrypt
const results = await client.decryptBatch([
  encryptedValue1,
  encryptedValue2,
  encryptedValue3
]);

🎨 React Integration

Setup Provider

import { FhevmProvider } from 'fhevm-sdk/react';

function App() {
  return (
    <FhevmProvider
      config={{
        network: 'sepolia',
        contractAddress: '0x...'
      }}
    >
      <YourApp />
    </FhevmProvider>
  );
}

Use Hooks

import { useFhevmClient, useEncrypt, useDecrypt } from 'fhevm-sdk/react';

function EncryptionComponent() {
  const client = useFhevmClient();
  const { encrypt, isEncrypting } = useEncrypt();
  const { decrypt, isDecrypting } = useDecrypt();

  const handleSubmit = async (value: number) => {
    // Encrypt
    const encrypted = await encrypt(value, 'uint64');

    // Send to contract
    const tx = await contract.submit(encrypted);
    await tx.wait();

    // Decrypt result
    const result = await decrypt(encryptedResult);
    console.log('Decrypted:', result);
  };

  return (
    <div>
      <button onClick={() => handleSubmit(42)} disabled={isEncrypting}>
        {isEncrypting ? 'Encrypting...' : 'Submit Encrypted Data'}
      </button>
    </div>
  );
}

🎭 Vue Integration

<script setup lang="ts">
import { useFhevmClient, useEncrypt, useDecrypt } from 'fhevm-sdk/vue';

const client = useFhevmClient({
  network: 'sepolia',
  contractAddress: '0x...'
});

const { encrypt, isEncrypting } = useEncrypt(client);
const { decrypt, isDecrypting } = useDecrypt(client);

const handleEncrypt = async () => {
  const encrypted = await encrypt(42, 'uint64');
  console.log('Encrypted:', encrypted);
};
</script>

<template>
  <button @click="handleEncrypt" :disabled="isEncrypting">
    {{ isEncrypting ? 'Encrypting...' : 'Encrypt Data' }}
  </button>
</template>

πŸ“‹ SDK Integration Examples

This repository includes four comprehensive examples demonstrating FHEVM SDK integration across different environments:

1. Next.js Full-Featured Application

Location: examples/nextjs-pollution-monitor/ or templates/nextjs/

A complete production-ready Next.js application showcasing:

  • βœ… Station registration with encrypted data
  • βœ… Confidential pollution reporting (euint64)
  • βœ… Homomorphic threshold checking
  • βœ… EIP-712 signed decryption
  • βœ… Role-based access control
  • βœ… Real-time encrypted dashboard
  • βœ… MetaMask integration
  • βœ… Sepolia testnet deployment
  • βœ… Banking Example: Confidential transactions
  • βœ… Medical Example: Privacy-preserving health records

Quick Start:

cd examples/nextjs-pollution-monitor
npm install
npm run dev

Visit http://localhost:3000

See examples/nextjs-pollution-monitor/README.md for details.

2. React Basic Example

Location: examples/react-basic/ or templates/react/

A minimal React setup perfect for learning FHEVM SDK basics:

  • βœ… Basic encryption demonstration
  • βœ… Simple UI with loading states
  • βœ… Error handling
  • βœ… Educational info panel
  • βœ… Perfect starting point for new projects

Quick Start:

cd examples/react-basic
npm install
npm run dev

Visit http://localhost:5173

See examples/react-basic/README.md for details.

3. Node.js CLI Tool

Location: examples/node-cli/

Command-line tool for FHEVM encryption operations:

  • βœ… Command-line encryption
  • βœ… Multiple encryption types (uint8, uint16, uint32, uint64, bool)
  • βœ… Progress indicators
  • βœ… Colored output
  • βœ… Perfect for testing and automation

Quick Start:

cd examples/node-cli
npm install

# Encrypt a value
node index.js encrypt 42 --contract 0xYourContractAddress --type uint64

See examples/node-cli/README.md for details.

4. Privacy Pollution Monitor - React Edition

Location: examples/PrivacyPollutionMonitor/

A comprehensive environmental monitoring application with full FHEVM encryption:

  • βœ… Station registration and management
  • βœ… Encrypted pollution reporting (uint32, uint8)
  • βœ… Multiple pollutant types (PM2.5, PM10, SO2, NOx, Ozone, etc.)
  • βœ… Encrypted alert thresholds
  • βœ… Real-time dashboard with statistics
  • βœ… Full FHEVM SDK integration with React hooks
  • βœ… Component-based architecture
  • βœ… Production-ready React application

Quick Start:

cd examples/PrivacyPollutionMonitor
npm install
npm run dev

Visit http://localhost:3001

See examples/PrivacyPollutionMonitor/README-REACT.md for details.

Note: This example also includes a legacy static HTML version (index.html + app.js) for comparison. The React version (src/) demonstrates modern best practices with full SDK integration.


πŸ› οΈ Development

Clone and Setup

# Clone the repository
git clone https://github.com/yourusername/fhevm-react-template.git
cd fhevm-react-template

# Install all dependencies (monorepo)
npm install

# Build the SDK
npm run build:sdk

# Run tests
npm test

# Start development mode
npm run dev

Project Scripts

# Build
npm run build              # Build all packages
npm run build:sdk          # Build SDK only
npm run build:examples     # Build all examples

# Development
npm run dev                # Start all in dev mode
npm run dev:sdk            # SDK dev mode with watch
npm run dev:nextjs         # Next.js example

# Testing
npm test                   # Run all tests
npm run test:sdk           # SDK tests only
npm run test:e2e           # End-to-end tests

# Deployment
npm run deploy:contracts   # Deploy to Sepolia
npm run deploy:frontend    # Deploy Next.js to Vercel

# Linting & Formatting
npm run lint               # Lint all packages
npm run format             # Format code

πŸ“š Documentation

Core Concepts

Advanced Topics

Examples


πŸŽ₯ Video Demo

πŸ“Ή Watch the Demo: [demo.mp4]

The video demonstrates:

  1. SDK installation and setup (< 10 lines)
  2. Full-featured Next.js application integration
  3. React basic example walkthrough
  4. Node.js CLI tool usage
  5. Encryption and decryption flows
  6. Multi-framework support (React, Vue, Node.js)
  7. Design decisions and architecture

🌐 Live Deployment

πŸš€ Live Demo: https://fhe-pollution-monitor.vercel.app

Example Applications:

  • Next.js Full Application: Production-ready confidential environmental monitoring system
  • React Basic: Minimal setup for learning
  • Node.js CLI: Command-line encryption tool

Smart Contract (Sepolia Testnet):

  • Address: 0xc61a1997F87156dfC96CA14E66fA9E3A02D36358
  • Network: Sepolia (Chain ID: 11155111)
  • Explorer: View on Etherscan

πŸ’‘ Design Decisions

Why Framework-Agnostic Core?

The SDK separates core functionality from framework adapters, allowing:

  • βœ… Use in any JavaScript environment
  • βœ… Consistent behavior across frameworks
  • βœ… Easy testing and maintenance
  • βœ… Smaller bundle sizes (tree-shaking)

Why Wagmi-like API?

Web3 developers are familiar with wagmi's hook-based approach:

  • βœ… Intuitive for React developers
  • βœ… Composable and reusable
  • βœ… Built-in state management
  • βœ… TypeScript-first

Why Monorepo Structure?

Keeps SDK and examples in sync:

  • βœ… Shared dependencies
  • βœ… Easier testing
  • βœ… Consistent versioning
  • βœ… Simplified development workflow

🧩 SDK API Reference

Core Functions

// Client Management
createFhevmClient(config: FhevmConfig): Promise<FhevmClient>
FhevmClient.init(): Promise<void>
FhevmClient.getPublicKey(): Promise<string>

// Encryption
encrypt8(value: number): Promise<Uint8Array>
encrypt16(value: number): Promise<Uint8Array>
encrypt32(value: number): Promise<Uint8Array>
encrypt64(value: bigint): Promise<Uint8Array>
encryptBool(value: boolean): Promise<Uint8Array>
encryptAddress(address: string): Promise<Uint8Array>

// Decryption
userDecrypt(data: Uint8Array, contract: string): Promise<any>
publicDecrypt(data: Uint8Array): Promise<any>
decryptBatch(data: Uint8Array[]): Promise<any[]>

// Contract Helpers
getContract(address: string, abi: any): Contract
getSigner(): Signer
getProvider(): Provider

React Hooks

// Provider
<FhevmProvider config={...}>

// Hooks
useFhevmClient(): FhevmClient
useEncrypt(): { encrypt, isEncrypting, error }
useDecrypt(): { decrypt, isDecrypting, error }
useContract(address, abi): Contract
useFhevmTransaction(contract, method): { send, isLoading, error }

Vue Composables

useFhevmClient(config): FhevmClient
useEncrypt(client): { encrypt, isEncrypting, error }
useDecrypt(client): { decrypt, isDecrypting, error }
useContract(client, address, abi): Contract

πŸ”’ Security Considerations

Client-Side Encryption

  • βœ… Encryption happens in the browser/client
  • βœ… Keys never leave the client
  • βœ… Uses Zama's official fhevmjs library

EIP-712 Signatures

  • βœ… User must sign to decrypt own data
  • βœ… Prevents unauthorized decryption
  • βœ… Domain-specific signatures

Best Practices

// βœ… Good: Encrypt sensitive data
const encrypted = await encrypt(socialSecurityNumber);

// ❌ Bad: Send sensitive data in plain text
await contract.submit(socialSecurityNumber); // NEVER!

// βœ… Good: Verify decryption permissions
if (await hasPermission(address)) {
  const decrypted = await decrypt(data);
}

// βœ… Good: Handle errors properly
try {
  const result = await decrypt(data);
} catch (error) {
  if (error.code === 'SIGNATURE_REQUIRED') {
    // Request user signature
  }
}

πŸ§ͺ Testing

Unit Tests

npm run test:unit

Integration Tests

npm run test:integration

E2E Tests

npm run test:e2e

Coverage

npm run test:coverage

Target: >80% code coverage


🀝 Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

Development Workflow

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes
  4. Run tests: npm test
  5. Commit: git commit -m 'feat: add amazing feature'
  6. Push: git push origin feature/amazing-feature
  7. Open a Pull Request

🌟 Roadmap

Phase 1 (Current) βœ…

  • Core SDK with framework-agnostic API
  • React and Vue adapters
  • Three comprehensive examples (Next.js, React, Node.js)
  • Comprehensive documentation

Phase 2 (Q2 2025) πŸ”œ

  • Angular support
  • Svelte support
  • CLI tools for quick scaffolding
  • Additional example applications

Phase 3 (Q3 2025) πŸ”œ

  • Performance optimizations
  • Batch encryption/decryption improvements
  • Advanced caching strategies
  • Developer DevTools extension

Phase 4 (Q4 2025) πŸ”œ

  • Mobile SDK (React Native)
  • Wallet integrations (MetaMask Snaps)
  • FHEVM testing utilities
  • Production-ready templates

πŸ“„ License

MIT License - see LICENSE file for details.


πŸ™ Acknowledgments

  • Zama - For pioneering Fully Homomorphic Encryption and the FHEVM platform
  • fhevmjs - Official Zama FHE library for JavaScript
  • wagmi - Inspiration for the hook-based API design
  • Viem - Modern Ethereum library patterns
  • Community - For feedback and contributions

πŸ“ž Support & Resources

Documentation

Community

Contact


FHEVM SDK - Making Confidential dApps Simple πŸ”

Built with ❀️ for the Zama Bounty Challenge

Documentation β€’ Examples β€’ API Reference β€’ Contributing

About

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 88.1%
  • Solidity 5.6%
  • JavaScript 4.0%
  • CSS 2.2%
  • HTML 0.1%