npm package: @private-vault/sdk
Description: SDK for Private Vault Solana Program - Privacy-preserving vault with platform/whitelabel support
Latest version: 1.0.0

# Private Vault SDK

TypeScript SDK for interacting with the Private Vault Solana program. Developers provide their own signers to interact with the program. This SDK does not generate wallets - developers must provide their own keypairs.

## Installation

```bash
npm install @private-vault/sdk
# or
yarn add @private-vault/sdk
```

## Setup

```typescript
import { Connection, PublicKey } from "@solana/web3.js";
import { PrivateVaultClient, generateRelayerKeypair } from "@private-vault/sdk";

const connection = new Connection("https://api.devnet.solana.com", "confirmed");

const client = new PrivateVaultClient({
  connection,
  rpcUrl: "https://api.devnet.solana.com", // Optional, defaults to devnet
  commitment: "confirmed", // Optional
});

// IDL is bundled with the SDK - no need to import it!

// Generate relayer keypair for withdrawals (one-time setup)
const { privateKeyBase64 } = generateRelayerKeypair();
// Add to .env: RELAYER_PRIVATE_KEY="<base64_string>"
```

## Usage

### Initialize Vault

```typescript
import { Keypair, PublicKey } from "@solana/web3.js";

const authority = Keypair.generate(); // Your authority keypair
const treasury = new PublicKey("..."); // Treasury wallet for fee collection

const txSignature = await client.initializeVault({
  authority,
  treasury, // Fees will be withdrawn to this wallet
});

console.log("Vault initialized:", txSignature);
```

### Generate Commitment

```typescript
import { generateCommitmentHash, generateSalt } from "@private-vault/sdk";

const userWallet = Keypair.generate();
const nonce = 0;
const salt = generateSalt(32);

const commitmentHash = generateCommitmentHash(
  userWallet.publicKey,
  nonce,
  salt
);
```

### Deposit (Direct)

```typescript
const user = Keypair.generate(); // User's wallet
const amount = 1_000_000_000; // 1 SOL in lamports

const txSignature = await client.deposit({
  amount,
  commitmentHash,
  user,
});

console.log("Deposit successful:", txSignature);
// Charges 0.25% base fee
```

### Deposit Via Relayer (Privacy-Preserving)

```typescript
const relayer = Keypair.generate(); // Relayer wallet
// User sends SOL to vault first via SystemProgram.transfer
// Then relayer calls this function

const txSignature = await client.depositViaRelayer({
  amount,
  commitmentHash,
  relayer,
});

console.log("Relayer deposit successful:", txSignature);
// Charges 0.25% base fee
```

### Withdraw

```typescript
const recipient = new PublicKey("..."); // Recipient address
const newNonce = 1; // Increment from previous nonce
const relayer = Keypair.generate(); // Relayer wallet

const txSignature = await client.withdraw({
  commitmentHash,
  amount: 500_000_000, // 0.5 SOL in lamports
  recipient,
  nonce: newNonce,
  validAfter: Math.floor(Date.now() / 1000) - 10, // Unix timestamp
  relayer,
});

console.log("Withdrawal successful:", txSignature);
// Charges 0.25% base fee
```

### Initialize Platform (Whitelabel)

```typescript
const platformAuthority = Keypair.generate();
const platformId = platformAuthority.publicKey; // Or any unique Pubkey
const relayer = new PublicKey("..."); // Platform's relayer
const treasury = new PublicKey("..."); // Platform's treasury
const platformFeeBp = 50; // 0.5% platform fee (50 basis points)

const txSignature = await client.initializePlatform({
  authority: platformAuthority,
  platformId,
  relayer,
  treasury,
  platformFeeBasisPoints: platformFeeBp,
});

console.log("Platform initialized:", txSignature);
```

### Update Platform Settings

```typescript
const platformAuthority = Keypair.generate();
const platformId = new PublicKey("...");

// Update only the fee
const txSignature = await client.updatePlatformSettings({
  authority: platformAuthority,
  platformId,
  platformFeeBasisPoints: 100, // Update to 1%
  // Other fields remain unchanged
});

console.log("Platform updated:", txSignature);
```

### Deposit With Platform

```typescript
const user = Keypair.generate();
const platformId = new PublicKey("...");
const amount = 1_000_000_000; // 1 SOL

const txSignature = await client.depositWithPlatform({
  user,
  platformId,
  commitmentHash,
  amount,
});

console.log("Platform deposit successful:", txSignature);
// Charges 0.25% base fee + platform fee
```

### Deposit Via Platform Relayer

```typescript
const platformRelayer = Keypair.generate();
const platformId = new PublicKey("...");
// User sends SOL to vault first

const txSignature = await client.depositViaPlatformRelayer({
  relayer: platformRelayer,
  platformId,
  commitmentHash,
  amount,
});

console.log("Platform relayer deposit successful:", txSignature);
// Charges 0.25% base fee + platform fee
```

### Withdraw With Platform

```typescript
const platformRelayer = Keypair.generate();
const platformId = new PublicKey("...");
const recipient = new PublicKey("...");

const txSignature = await client.withdrawWithPlatform({
  relayer: platformRelayer,
  platformId,
  commitmentHash,
  amount: 500_000_000,
  recipient,
  nonce: 1,
  validAfter: Math.floor(Date.now() / 1000) - 10,
});

console.log("Platform withdrawal successful:", txSignature);
// Charges 0.25% base fee + platform fee
```

### Withdraw Fees

```typescript
const vaultAuthority = Keypair.generate();
const amount = 1_000_000_000; // 1 SOL in fees

const txSignature = await client.withdrawFees({
  authority: vaultAuthority,
  amount,
});

console.log("Fees withdrawn:", txSignature);
```

### Get Account Data

```typescript
// Get vault account
const vault = await client.getVaultAccount();
console.log("Vault authority:", vault.authority.toString());
console.log("Vault treasury:", vault.treasury.toString());

// Get commitment account
const commitment = await client.getCommitmentAccount(commitmentHash);
console.log("Balance:", commitment.balance.toString());
console.log("Nonce:", commitment.nonce.toString());

// Get platform account
const platform = await client.getPlatformAccount(platformId);
console.log("Platform fee:", platform.platformFeeBasisPoints.toString());
console.log("Is active:", platform.isActive);
```

## Fee Calculations

```typescript
import {
  calculateBaseFee,
  calculatePlatformFee,
  calculateTotalFees,
  calculateTotalWithFee,
  calculateTotalWithPlatformFees,
} from "@private-vault/sdk";

const amount = 1_000_000_000; // 1 SOL

// Base fee (0.25%)
const baseFee = calculateBaseFee(amount);
console.log("Base fee:", baseFee.toString(), "lamports");

// Platform fee (e.g., 0.5%)
const platformFee = calculatePlatformFee(amount, 50);
console.log("Platform fee:", platformFee.toString(), "lamports");

// Total fees (base + platform)
const totalFees = calculateTotalFees(amount, 50);
console.log("Total fees:", totalFees.toString(), "lamports");

// Total amount with base fee
const totalWithFee = calculateTotalWithFee(amount);
console.log("Total with fee:", totalWithFee.toString(), "lamports");

// Total amount with platform fees
const totalWithPlatformFees = calculateTotalWithPlatformFees(amount, 50);
console.log("Total with platform fees:", totalWithPlatformFees.toString(), "lamports");
```

## Utility Functions

### Commitment Generation

```typescript
import { generateCommitmentHash, generateSalt } from "@private-vault/sdk";

const salt = generateSalt(32);
const commitmentHash = generateCommitmentHash(
  walletPubkey,
  nonce,
  salt
);
```

### Relayer Keypair Management

```typescript
import {
  generateRelayerKeypair,
  parseRelayerKeypair,
  getRelayerKeypairFromEnv,
} from "@private-vault/sdk";

// Generate new relayer
const { keypair, privateKeyBase64 } = generateRelayerKeypair();
console.log("Add to .env: RELAYER_PRIVATE_KEY=" + privateKeyBase64);

// Parse from string
const relayer = parseRelayerKeypair(process.env.RELAYER_PRIVATE_KEY!);

// Get from environment
const relayerFromEnv = getRelayerKeypairFromEnv();
```

### Conversions

```typescript
import { lamportsToSol, solToLamports } from "@private-vault/sdk";

const sol = lamportsToSol(1_000_000_000); // 1.0
const lamports = solToLamports(1.5); // 1500000000
```

### Get Commitment Balance

```typescript
import { getCommitmentBalance } from "@private-vault/sdk";

const balanceData = await getCommitmentBalance(
  connection,
  client.getProgramId(),
  commitmentHash
);

if (balanceData) {
  console.log("Balance:", balanceData.balance, "lamports");
  console.log("Nonce:", balanceData.nonce);
}
```

## API Reference

### PrivateVaultClient

#### Constructor

```typescript
new PrivateVaultClient(config?: SDKConfig)
```

#### Methods

- `getProgramId(): PublicKey` - Get program ID
- `getConnection(): Connection` - Get connection
- `getVaultAddress(): PublicKey` - Get vault PDA address
- `getCommitmentAddress(commitmentHash): PublicKey` - Get commitment PDA address
- `getPlatformAddress(platformId): PublicKey` - Get platform PDA address
- `initializeVault(params): Promise<string>` - Initialize vault PDA
- `deposit(params): Promise<string>` - Deposit SOL (direct)
- `depositViaRelayer(params): Promise<string>` - Deposit via relayer
- `withdraw(params): Promise<string>` - Withdraw SOL
- `initializePlatform(params): Promise<string>` - Initialize platform
- `updatePlatformSettings(params): Promise<string>` - Update platform settings
- `depositWithPlatform(params): Promise<string>` - Deposit via platform
- `depositViaPlatformRelayer(params): Promise<string>` - Deposit via platform relayer
- `withdrawWithPlatform(params): Promise<string>` - Withdraw via platform
- `withdrawFees(params): Promise<string>` - Withdraw accumulated fees
- `getVaultAccount(): Promise<VaultAccount>` - Fetch vault account
- `getCommitmentAccount(commitmentHash): Promise<CommitmentAccount>` - Fetch commitment account
- `getPlatformAccount(platformId): Promise<PlatformAccount>` - Fetch platform account

### Utility Functions

- `getVaultPDA(programId): [PublicKey, number]` - Derive vault PDA
- `getCommitmentPDA(programId, commitmentHash): [PublicKey, number]` - Derive commitment PDA
- `getPlatformPDA(programId, platformId): [PublicKey, number]` - Derive platform PDA
- `generateCommitmentHash(walletPubkey, nonce, salt): Uint8Array` - Generate commitment hash
- `generateSalt(length?): Uint8Array` - Generate random salt
- `getCommitmentBalance(connection, programId, commitmentHash): Promise<{balance, nonce} | null>` - Get on-chain balance
- `lamportsToSol(lamports): number` - Convert lamports to SOL
- `solToLamports(sol): number` - Convert SOL to lamports
- `calculateBaseFee(amount): BN` - Calculate 0.25% base fee
- `calculatePlatformFee(amount, basisPoints): BN` - Calculate platform fee
- `calculateTotalFees(amount, platformFeeBp?): BN` - Calculate total fees
- `calculateTotalWithFee(amount): BN` - Calculate total with base fee
- `calculateTotalWithPlatformFees(amount, platformFeeBp): BN` - Calculate total with platform fees
- `generateRelayerKeypair(): {keypair, privateKeyBase64, privateKeyArray}` - Generate relayer keypair
- `parseRelayerKeypair(privateKey): Keypair` - Parse relayer from base64 or JSON array
- `getRelayerKeypairFromEnv(): Keypair` - Get relayer from RELAYER_PRIVATE_KEY env variable

## Fee Structure

- **Base Fee**: Always 0.25% (25 basis points) - applied to all transactions
- **Platform Fee**: Configurable per platform (in addition to base fee)
- **Total Fee**: Base Fee + Platform Fee (if using platform)

## Examples

See the `/examples` directory for complete usage examples.

## License

MIT