npm package: @nana0x/fherand-sdk
Description: FHERand SDK - Fully Homomorphic Encryption Randomness for dApps
Author: FHERand Team
Latest version: 0.1.1

# @nana0x/fherand-sdk

**FHERand SDK** - Fully Homomorphic Encryption Randomness for dApps

[![npm version](https://img.shields.io/npm/v/@nana0x/fherand-sdk.svg)](https://www.npmjs.com/package/@nana0x/fherand-sdk)
[![License](https://img.shields.io/badge/license-BSD--3--Clause--Clear-blue.svg)](LICENSE)

##  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

```bash
npm install @nana0x/fherand-sdk ethers
# or
pnpm add @nana0x/fherand-sdk ethers
# or
yarn add @nana0x/fherand-sdk ethers
```

##  Quick Start

### Basic Usage

```typescript
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

```typescript
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

```typescript
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 service
- `isSubscribed(userAddress?: string): Promise<boolean>` - Check if user has active subscription
- `getSubscriptionInfo(userAddress?: string): Promise<SubscriptionInfo>` - Get subscription details

##### Random Generation

- `requestRandomUint8(): Promise<bigint>` - Request encrypted random uint8 (0-255)
- `requestRandomUint32(): Promise<bigint>` - Request encrypted random uint32
- `requestRandomInRange(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 selection
- `requestFreeRandom(): Promise<bigint>` - Request free random (10/day limit)
- `requestOneTimeRandom(options?: { value?: bigint }): Promise<bigint>` - Pay-as-you-go random
- `requestBatchRandom(count: number): Promise<bigint[]>` - Request multiple random numbers

##### Query

- `getRandomValue(requestId: bigint): Promise<string>` - Get encrypted random value
- `getRequestInfo(requestId: bigint): Promise<RequestInfo>` - Get request details
- `getUserRequests(userAddress?: string): Promise<bigint[]>` - Get user's request history
- `getPaygPrice(): Promise<bigint>` - Get PAYG price

### Encryption & Decryption

#### Encrypt

```typescript
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

```typescript
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.

```typescript
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.

```typescript
const {
  encryptedValue,
  decryptedValue,
  proof,
  loading,
  error,
  decrypt,
} = useRandomValue({
  client,
  requestId,
  contractAddress: '0x...',
  signer: signer || null,
  autoDecrypt?: false,
});
```

#### useSubscription

Hook for subscription management.

```typescript
const {
  isSubscribed,
  subscriptionInfo,
  loading,
  error,
  subscribe,
  refresh,
} = useSubscription({
  client,
  autoRefresh?: true,
  refreshInterval?: 30000,
});
```

## 🎮 Examples

### Dice Game

```typescript
// 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

```typescript
// 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

- [Documentation](https://github.com/0xNana/fherand)
- [GitHub Repository](https://github.com/0xNana/fherand)
- [Issues](https://github.com/0xNana/fherand/issues)

##  License

BSD-3-Clause-Clear - See [LICENSE](../../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.

##  Learn More

- [FHERand Documentation](https://github.com/0xNana/fherand)
- [FHEVM Documentation](https://docs.zama.org)