@nana0x/fherand-sdk
v0.1.1
Published
FHERand SDK - Fully Homomorphic Encryption Randomness for dApps
Maintainers
Readme
@nana0x/fherand-sdk
FHERand SDK - Fully Homomorphic Encryption Randomness for dApps
Overview
FHERand SDK provides a simple, type-safe interface for integrating encrypted randomness into your FHE dApps. Generate cryptographically secure random numbers that remain encrypted until explicitly decrypted.
This is a single unified package (@nana0x/fherand-sdk) that includes:
- Core SDK client for Node.js and TypeScript
- React hooks for React/Next.js applications
- Encryption and decryption utilities
- Type definitions
Features
- Encrypted Randomness - Random values stay encrypted on-chain
- Multiple Random Types - uint8, uint32, ranges, weighted selection
- Flexible Pricing - Free tier, subscriptions, or pay-as-you-go
- On-Chain Generation - No oracle delays, instant results
- Cryptographic Proofs - Verifiable randomness with decryption proofs
- React Hooks - Built-in React hooks
- TypeScript - Full TypeScript support with type definitions
Installation
npm install @nana0x/fherand-sdk ethers
# or
pnpm add @nana0x/fherand-sdk ethers
# or
yarn add @nana0x/fherand-sdk ethersQuick Start
Basic Usage
import { FHERandClient } from '@nana0x/fherand-sdk';
import { ethers } from 'ethers';
// Initialize provider and signer
const provider = new ethers.JsonRpcProvider('https://sepolia.infura.io/v3/YOUR_KEY');
const signer = await provider.getSigner();
// Create client
const client = new FHERandClient('0x...FHERandContractAddress', signer);
// Subscribe (optional - can use free tier or PAYG)
await client.subscribe('BASIC');
// Request random number
const requestId = await client.requestRandomUint32();
// Get encrypted value
const encryptedValue = await client.getRandomValue(requestId);
// Decrypt off-chain
import { decrypt } from '@nana0x/fherand-sdk';
const result = await decrypt(encryptedValue, contractAddress, signer, 'uint32');
console.log('Random number:', result.value);React Integration
import { useFHERand, useRandomValue } from '@nana0x/fherand-sdk';
import { useSigner } from 'wagmi';
function MyComponent() {
const { data: signer } = useSigner();
const {
client,
isSubscribed,
requestRandomUint32,
loading
} = useFHERand({
contractAddress: '0x...',
signer: signer || null,
});
const handleRequestRandom = async () => {
const requestId = await requestRandomUint32();
console.log('Request ID:', requestId);
};
return (
<div>
<p>Subscribed: {isSubscribed ? 'Yes' : 'No'}</p>
<button onClick={handleRequestRandom} disabled={loading}>
Request Random Number
</button>
</div>
);
}API Reference
FHERandClient
Main client class for interacting with FHERand contract.
Constructor
new FHERandClient(contractAddress: string, signer: Signer)
// or
new FHERandClient({ contractAddress: string, signer: Signer, provider?: Provider })Methods
Subscription
subscribe(tier?: Tier, options?: { value?: bigint }): Promise<void>- Subscribe to FHERand serviceisSubscribed(userAddress?: string): Promise<boolean>- Check if user has active subscriptiongetSubscriptionInfo(userAddress?: string): Promise<SubscriptionInfo>- Get subscription details
Random Generation
requestRandomUint8(): Promise<bigint>- Request encrypted random uint8 (0-255)requestRandomUint32(): Promise<bigint>- Request encrypted random uint32requestRandomInRange(min: number, max: number): Promise<bigint>- Request random in range [min, max]requestRandomBounded(upperBound: number): Promise<bigint>- Request random in bounded range (power of 2)requestWeightedRandom(weights: number[]): Promise<bigint>- Request weighted random selectionrequestFreeRandom(): Promise<bigint>- Request free random (10/day limit)requestOneTimeRandom(options?: { value?: bigint }): Promise<bigint>- Pay-as-you-go randomrequestBatchRandom(count: number): Promise<bigint[]>- Request multiple random numbers
Query
getRandomValue(requestId: bigint): Promise<string>- Get encrypted random valuegetRequestInfo(requestId: bigint): Promise<RequestInfo>- Get request detailsgetUserRequests(userAddress?: string): Promise<bigint[]>- Get user's request historygetPaygPrice(): Promise<bigint>- Get PAYG price
Encryption & Decryption
Encrypt
import { encrypt, encryptUint8, encryptUint32 } from '@nana0x/fherand-sdk';
// Encrypt a value
const result = await encrypt(
42,
{ contractAddress: '0x...' },
signer,
'uint32'
);
// Use encrypted handle in your contract
await myContract.processEncryptedValue(result.handle, result.inputProof);Decrypt
import { decrypt, decryptPublic, decryptUser } from '@nana0x/fherand-sdk';
// Public decryption (no signature required)
const result = await decryptPublic(
encryptedValue,
contractAddress,
provider,
chainId
);
// User decryption (with signature)
const result = await decryptUser(
encryptedValue,
contractAddress,
signer,
signature,
chainId
);React Hooks
Note: React hooks are included in @nana0x/fherand-sdk. No separate React package is required.
useFHERand
Main hook for FHERand interactions.
const {
client,
loading,
error,
isSubscribed,
subscriptionInfo,
subscribe,
requestRandomUint8,
requestRandomUint32,
requestRandomInRange,
requestWeightedRandom,
requestFreeRandom,
requestOneTimeRandom,
refreshSubscription,
} = useFHERand({
contractAddress: '0x...',
signer: signer || null,
autoConnect?: true,
});useRandomValue
Hook for tracking and decrypting a specific random value.
const {
encryptedValue,
decryptedValue,
proof,
loading,
error,
decrypt,
} = useRandomValue({
client,
requestId,
contractAddress: '0x...',
signer: signer || null,
autoDecrypt?: false,
});useSubscription
Hook for subscription management.
const {
isSubscribed,
subscriptionInfo,
loading,
error,
subscribe,
refresh,
} = useSubscription({
client,
autoRefresh?: true,
refreshInterval?: 30000,
});🎮 Examples
Dice Game
// Roll a 6-sided die
const requestId = await client.requestRandomInRange(1, 6);
const encryptedValue = await client.getRandomValue(requestId);
const result = await decrypt(encryptedValue, contractAddress, signer, 'uint8');
console.log(`You rolled: ${result.value}`);Weighted Lottery
// 50% chance for prize A, 30% for B, 20% for C
const weights = [50, 30, 20];
const requestId = await client.requestWeightedRandom(weights);
const encryptedValue = await client.getRandomValue(requestId);
const result = await decrypt(encryptedValue, contractAddress, signer, 'uint8');
const prize = ['A', 'B', 'C'][result.value];
console.log(`You won prize: ${prize}`);Pricing
- Free Tier: 10 requests per day (no subscription needed)
- BASIC: 1,000 requests/month for 0.005 ETH
- PRO: 10,000 requests/month for 0.03 ETH
- ENTERPRISE: 100,000 requests/year for 0.25 ETH
- PAYG: 0.00001 ETH per request
🔗 Links
License
BSD-3-Clause-Clear - See LICENSE file for details.
Contributing
Contributions are welcome! Please read the contributing guidelines and submit pr to the repository.
Requirements
- Node.js >= 18.0.0
- ethers.js ^6.0.0
- React ^18.0.0 (optional, for React hooks)
Security
FHERand uses FHEVM's cryptographically secure pseudo-random number generator (CSPRNG) for all randomness. All random values remain encrypted until explicitly decrypted, providing strong privacy guarantees.
