### Get SOL Balance Example
Source: https://privacycash.mintlify.app/sdk/balance
Full example showing client initialization and SOL balance retrieval.
```typescript
import { PrivacyCash } from 'privacycash'
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
const balance = await client.getPrivateBalance()
console.log('Private balance:', balance.lamports, 'lamports')
console.log('Private balance:', balance.lamports / 1_000_000_000, 'SOL')
```
--------------------------------
### Full Deposit Implementation Example
Source: https://privacycash.mintlify.app/sdk/deposit
Complete example showing client initialization and executing a deposit of 0.1 SOL.
```typescript
import { PrivacyCash } from 'privacycash'
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
// Deposit 0.1 SOL
const result = await client.deposit({
lamports: 0.1 * 1_000_000_000 // 100,000,000 lamports
})
console.log('Transaction:', result.tx)
console.log('Explorer:', `https://explorer.solana.com/tx/${result.tx}`)
```
--------------------------------
### Install PrivacyCash dependencies
Source: https://privacycash.mintlify.app/sdk/bridge
Install the required Solana and PrivacyCash packages to begin development.
```bash
npm install @solana/web3.js privacycash
```
--------------------------------
### Get Private Balance Example
Source: https://privacycash.mintlify.app/evmsdk/balance
Full implementation example using ethers.js to sign a message and retrieve the balance.
```typescript
import { ethers } from 'ethers'
import { BASE_NETWORK, ETH_NETWORK, getBalance } from 'privacycash-evm'
const network = ETH_NETWORK // or BASE_NETWORK
const SIGN_MESSAGE = 'Privacy Money account sign in'
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl, {
name: network.chainKey,
chainId: network.chainId,
})
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider)
const signature = await signer.signMessage(SIGN_MESSAGE)
const address = await signer.getAddress()
const result = await getBalance({ signature, address, token: 'eth', network })
console.log('Private ETH balance:', result.balance, 'ETH')
```
--------------------------------
### Withdraw SOL Implementation Example
Source: https://privacycash.mintlify.app/sdk/withdraw
A complete example showing client initialization and executing a withdrawal of 0.1 SOL.
```typescript
import { PrivacyCash } from 'privacycash'
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
// Withdraw 0.1 SOL to a clean wallet
const result = await client.withdraw({
lamports: 0.1 * 1_000_000_000,
recipientAddress: 'CLEAN_WALLET_ADDRESS'
})
console.log('Transaction:', result.tx)
console.log('Amount received:', result.amount_in_lamports / 1_000_000_000, 'SOL')
console.log('Fee paid:', result.fee_in_lamports / 1_000_000_000, 'SOL')
```
--------------------------------
### Withdrawal Implementation Example
Source: https://privacycash.mintlify.app/evmsdk/withdraw
A complete example demonstrating how to sign a message and execute a withdrawal using ethers.js.
```typescript
import { ethers } from 'ethers'
import { BASE_NETWORK, ETH_NETWORK, withdraw } from 'privacycash-evm'
const network = ETH_NETWORK // or BASE_NETWORK
const SIGN_MESSAGE = 'Privacy Money account sign in'
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl, {
name: network.chainKey,
chainId: network.chainId,
})
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider)
const signature = await signer.signMessage(SIGN_MESSAGE)
const address = await signer.getAddress()
const txHash = await withdraw({
withdrawAmountInput: 0.05, // Total amount including fees
recipient: '0xRECIPIENT_ADDRESS', // Any EVM address
keyBasePath: './circuits/transaction',
signature,
address,
token: 'eth',
network,
})
console.log('Withdraw tx:', txHash)
```
--------------------------------
### Install SDK Dependencies
Source: https://privacycash.mintlify.app/evmsdk/frontend
Install the required packages for the Privacy Cash EVM SDK and its peer dependencies.
```bash
npm install privacycash-evm wagmi viem @rainbow-me/rainbowkit @tanstack/react-query --save
```
--------------------------------
### Get SPL Token Balance Example
Source: https://privacycash.mintlify.app/sdk/balance
Full example showing how to retrieve a private SPL token balance using a mint address.
```typescript
import { PublicKey } from '@solana/web3.js'
// USDC mint address
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')
const balance = await client.getPrivateBalanceSpl(USDC_MINT)
console.log('Private USDC:', balance.amount, 'base units')
console.log('Private USDC:', balance.amount / 1_000_000, 'USDC') // USDC has 6 decimals
```
--------------------------------
### Install Privacy Cash SDK
Source: https://privacycash.mintlify.app/sdk/overview
Install the package using npm. Requires Node.js 24 or higher.
```bash
npm install privacycash --save
```
--------------------------------
### Deposit implementation example
Source: https://privacycash.mintlify.app/evmsdk/deposit
Demonstrates a full deposit flow using ethers.js to sign the message and handle the transaction submission.
```typescript
import { ethers } from 'ethers'
import { BASE_NETWORK, ETH_NETWORK, deposit } from 'privacycash-evm'
const network = ETH_NETWORK // or BASE_NETWORK
const SIGN_MESSAGE = 'Privacy Money account sign in'
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl, {
name: network.chainKey,
chainId: network.chainId,
})
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider)
const signature = await signer.signMessage(SIGN_MESSAGE)
const address = await signer.getAddress()
const txSender = async (unsignedTx: any) => {
const tx = await signer.sendTransaction(unsignedTx)
await tx.wait()
return tx.hash
}
const txHash = await deposit({
depositAmountInput: 0.01, // 0.01 ETH
keyBasePath: './circuits/transaction',
signature,
address,
txSender,
token: 'eth',
network,
})
console.log('Deposit tx:', txHash)
```
--------------------------------
### Install Privacy Cash EVM SDK
Source: https://privacycash.mintlify.app/evmsdk/overview
Install the package using npm. Requires Node.js 20+.
```bash
npm install privacycash-evm --save
```
--------------------------------
### Deposit USDC Example
Source: https://privacycash.mintlify.app/sdk/spl-tokens
Demonstrates initializing the client and depositing 10 USDC using a human-readable amount.
```typescript
import { PublicKey } from '@solana/web3.js'
import { PrivacyCash } from 'privacycash'
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')
// Deposit 10 USDC using human-readable amount
const result = await client.depositSPL({
mintAddress: USDC_MINT,
amount: 10 // 10 USDC
})
console.log('Deposit tx:', result.tx)
```
--------------------------------
### Install EVM Bridge Dependencies
Source: https://privacycash.mintlify.app/evmsdk/bridge
Install the required privacycash-evm and ethers packages via npm.
```bash
npm install privacycash-evm ethers --save
```
--------------------------------
### Deposit USDT Example
Source: https://privacycash.mintlify.app/sdk/spl-tokens
Shows how to deposit 50 USDT using the mint address and human-readable amount.
```typescript
const USDT_MINT = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')
// Deposit 50 USDT
const result = await client.depositSPL({
mintAddress: USDT_MINT,
amount: 50
})
```
--------------------------------
### Complete SPL Token Operations Example
Source: https://privacycash.mintlify.app/sdk/spl-tokens
A full workflow demonstrating initialization, balance checking, deposits, and withdrawals for both USDC and USDT.
```typescript
import { PublicKey } from '@solana/web3.js'
import { PrivacyCash } from 'privacycash'
async function splExample() {
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
const recipientAddress = process.env.RECIPIENT_ADDRESS!
// Token mint addresses
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')
const USDT_MINT = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')
// === USDC Operations ===
// Check initial USDC balance
let usdcBalance = await client.getPrivateBalanceSpl(USDC_MINT)
console.log('Initial USDC balance:', usdcBalance.amount / 1e6)
// Deposit 2 USDC
const depositUSDC = await client.depositSPL({
mintAddress: USDC_MINT,
amount: 2
})
console.log('USDC deposit tx:', depositUSDC.tx)
// Check balance after deposit
usdcBalance = await client.getPrivateBalanceSpl(USDC_MINT)
console.log('USDC after deposit:', usdcBalance.amount / 1e6)
// Withdraw 2 USDC
const withdrawUSDC = await client.withdrawSPL({
mintAddress: USDC_MINT,
amount: 2,
recipientAddress
})
console.log('USDC withdraw tx:', withdrawUSDC.tx)
// === USDT Operations ===
// Check initial USDT balance
let usdtBalance = await client.getPrivateBalanceSpl(USDT_MINT)
console.log('Initial USDT balance:', usdtBalance.amount / 1e6)
// Deposit 2 USDT
const depositUSDT = await client.depositSPL({
mintAddress: USDT_MINT,
amount: 2
})
console.log('USDT deposit tx:', depositUSDT.tx)
// Withdraw 2 USDT
const withdrawUSDT = await client.withdrawSPL({
mintAddress: USDT_MINT,
amount: 2,
recipientAddress
})
console.log('USDT withdraw tx:', withdrawUSDT.tx)
}
splExample().catch(console.error)
```
--------------------------------
### Log USDC Balance
Source: https://privacycash.mintlify.app/sdk/balance
Example of retrieving and logging the USDC balance in human-readable format.
```typescript
const balance = await client.getPrivateBalanceUSDC()
console.log('Private USDC:', balance.amount / 1_000_000, 'USDC')
```
--------------------------------
### Deposit Using Base Units Example
Source: https://privacycash.mintlify.app/sdk/spl-tokens
Demonstrates depositing tokens using raw base units instead of human-readable amounts.
```typescript
// Deposit 2 USDC using base units (USDC has 6 decimals)
const result = await client.depositSPL({
mintAddress: USDC_MINT,
base_units: 2_000_000 // 2 USDC = 2,000,000 base units
})
```
--------------------------------
### Implement EVM Bridge Workflow
Source: https://privacycash.mintlify.app/evmsdk/bridge
Example implementation for bridging ETH, including fee calculation, quote request, private withdrawal, and relayer notification.
```typescript
import { BASE_NETWORK, ETH_NETWORK, withdraw } from 'privacycash-evm'
const BRIDGE_URL = 'https://evm.privacycash.org/bridge'
const MINIMUM_BRIDGE_AMOUNT = 0.005 // ETH
const RENT_FEE = 0.00025
const FEE_RATE = 35 // basis points, 0.35%
/**
* Calculate how much ETH the relayer will actually receive after
* Privacy Cash withdrawal fees are deducted from the user's balance.
*/
function calculateWithdrawableAmount(totalAmount: number): number {
const flatFee = RENT_FEE // 0.00025 ETH
const rateFee = (totalAmount * FEE_RATE) / 10000 // 0.35%
return totalAmount - flatFee - rateFee
}
async function runBridge(address: string, signature: string) {
const network = ETH_NETWORK // or BASE_NETWORK
const inputChain = network.chainKey === 'eth' ? 'ethereum' : 'base'
const inputTokenName = 'eth' as const
const totalWithdrawAmount = 0.1 // ETH you will deduct from your private balance
const recipientAddress = '0xRECIPIENT_ADDRESS' // destination address on output chain
if (totalWithdrawAmount < MINIMUM_BRIDGE_AMOUNT) {
throw new Error(`Minimum bridge amount is ${MINIMUM_BRIDGE_AMOUNT} ETH`)
}
// Net amount the relayer receives (after Privacy Cash fees)
const withdrawableAmount = calculateWithdrawableAmount(totalWithdrawAmount)
const params = {
inputChain,
outputChain: 'ethereum', // see supported chains above
inputTokenName,
outputTokenName: 'eth', // token on the destination chain
inputTokenAmount: withdrawableAmount.toFixed(8),
refundAddress: address, // your EVM address for refunds
recipientAddress, // destination address
quoteWaitingTimeMs: 3000, // recommended delay for best routing
}
// STEP 1: Get quote and relayer deposit address
const quoteResponse = await fetch(BRIDGE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...params, step: 'quote' }),
})
const quoteData = await quoteResponse.json()
if (!quoteData.success) throw new Error(quoteData.error || 'Failed to get quote')
const depositAddress: string = quoteData.quote.depositAddress
console.log('Relayer deposit address:', depositAddress)
console.log('Estimated output:', quoteData.quote.amountOutFormatted)
// STEP 2: Withdraw to the relayer's deposit address on the selected EVM network
const txHash = await withdraw({
withdrawAmountInput: totalWithdrawAmount,
recipient: depositAddress, // relayer's one-time EVM address
keyBasePath: '/circuit',
signature,
address,
token: inputTokenName,
network,
})
console.log('Withdrawal tx:', txHash)
// STEP 3: Notify the relayer of the transaction hash
const notifyResponse = await fetch(BRIDGE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
txHash,
depositAddress,
step: 'send_tx',
}),
})
const notifyData = await notifyResponse.json()
if (notifyData.success) {
console.log('Bridge successfully initiated!')
} else {
console.error('Relayer notification failed:', notifyData.error)
}
}
```
--------------------------------
### Deposit SPL Tokens
Source: https://privacycash.mintlify.app/sdk/deposit-fe
Example usage of the depositSPL function to deposit SPL tokens into the protocol.
```typescript
import { depositSPL } from "privacycash/utils"
import { PublicKey } from "@solana/web3.js"
const result = await depositSPL({
mintAddress: new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'), // USDC
base_units: 1_000_000, // 1 USDC (assuming 6 decimals)
lightWasm: hasher,
connection,
keyBasePath: '/circuit2',
publicKey: userPublicKey,
transactionSigner: async (tx: VersionedTransaction) => {
return await signTransaction(tx)
},
storage: localStorage,
encryptionService,
referrer: ''
});
```
--------------------------------
### Privacy-Optimized Deposit Amounts
Source: https://privacycash.mintlify.app/sdk/deposit
Best practice example showing the use of round numbers to improve anonymity.
```typescript
// Good: Round amount
await client.deposit({ lamports: 1_000_000_000 }) // 1 SOL
// Avoid: Unique amount that's easy to trace
await client.deposit({ lamports: 1_234_567_890 }) // 1.23456789 SOL
```
--------------------------------
### Get SOL Balance Method
Source: https://privacycash.mintlify.app/sdk/balance
Retrieves the private SOL balance. Accepts an optional AbortSignal for request cancellation.
```typescript
const balance = await client.getPrivateBalance(abortSignal?: AbortSignal)
```
--------------------------------
### Supported Private Key Formats
Source: https://privacycash.mintlify.app/sdk/overview
Demonstrates initializing the client with different private key formats including Base58, byte arrays, and Solana Keypair objects.
```typescript
// Base58 encoded string
const client1 = new PrivacyCash({
RPC_url: 'https://...',
owner: '5Jd7...' // Base58 string
})
// Byte array
const client2 = new PrivacyCash({
RPC_url: 'https://...',
owner: [1, 2, 3, ...] // number[]
})
// Uint8Array
const client3 = new PrivacyCash({
RPC_url: 'https://...',
owner: new Uint8Array([1, 2, 3, ...])
})
// Solana Keypair object
import { Keypair } from '@solana/web3.js'
const client4 = new PrivacyCash({
RPC_url: 'https://...',
owner: Keypair.generate()
})
```
--------------------------------
### Configure Wallet Providers
Source: https://privacycash.mintlify.app/evmsdk/frontend
Wrap the application with Wagmi and RainbowKit providers to enable wallet connectivity.
```typescript
'use client'
import { RainbowKitProvider } from '@rainbow-me/rainbowkit'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { WagmiProvider, createConfig, http } from 'wagmi'
import { base, mainnet } from 'wagmi/chains'
import { walletConnect, coinbaseWallet } from 'wagmi/connectors'
const config = createConfig({
ssr: true,
chains: [base, mainnet],
connectors: [
coinbaseWallet({ appName: 'Your App' }),
walletConnect({ projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID! }),
],
transports: {
[base.id]: http(process.env.NEXT_PUBLIC_BASE_RPC_URL),
[mainnet.id]: http(process.env.NEXT_PUBLIC_ETH_RPC_URL),
},
})
const queryClient = new QueryClient()
export function Providers({ children }: { children: React.ReactNode }) {
return (
{children}
)
}
```
--------------------------------
### Get USDC Balance
Source: https://privacycash.mintlify.app/sdk/balance
Retrieves the private USDC balance using a convenience method.
```typescript
const balance = await client.getPrivateBalanceUSDC()
```
--------------------------------
### Withdraw Specific SPL Tokens
Source: https://privacycash.mintlify.app/sdk/spl-tokens
Examples for withdrawing USDC and USDT tokens to a specified recipient address.
```typescript
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v')
// Withdraw 10 USDC to a clean wallet
const result = await client.withdrawSPL({
mintAddress: USDC_MINT,
amount: 10,
recipientAddress: 'CLEAN_WALLET_ADDRESS'
})
console.log('Withdrew:', result.base_units / 1_000_000, 'USDC')
console.log('Fee:', result.fee_base_units / 1_000_000, 'USDC')
```
```typescript
const USDT_MINT = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')
const result = await client.withdrawSPL({
mintAddress: USDT_MINT,
amount: 25,
recipientAddress: 'RECIPIENT_ADDRESS'
})
```
--------------------------------
### Configure Next.js Postinstall Script
Source: https://privacycash.mintlify.app/sdk/frontend
Update the postinstall script in package.json to copy WASM files for Next.js projects.
```text
"scripts": {
"postinstall": "cp node_modules/@lightprotocol/hasher.rs/dist/hasher_wasm_simd_bg.wasm node_modules/@lightprotocol/hasher.rs/dist/browser-fat/es/ && cp node_modules/@lightprotocol/hasher.rs/dist/light_wasm_hasher_bg.wasm node_modules/@lightprotocol/hasher.rs/dist/browser-fat/es/",
},
```
--------------------------------
### Manage Balance Cache
Source: https://privacycash.mintlify.app/sdk/balance
Demonstrates how the SDK handles caching and how to force a refresh of the balance data.
```typescript
// First call: fetches and decrypts all UTXOs (slower)
const balance1 = await client.getPrivateBalance()
// Second call: uses cached data + fetches only new UTXOs (faster)
const balance2 = await client.getPrivateBalance()
// Force refresh: clear cache and fetch everything
await client.clearCache()
const balance3 = await client.getPrivateBalance()
```
--------------------------------
### Get Private Balance Return Type
Source: https://privacycash.mintlify.app/evmsdk/balance
The function returns an object containing the balance as a decimal string.
```typescript
{
balance: string // token balance as a decimal string, e.g. "0.123456789"
}
```
--------------------------------
### Withdrawal Fee Calculation and Execution
Source: https://privacycash.mintlify.app/sdk/withdraw
Demonstrates how to calculate fees and execute a withdrawal using the client SDK. Ensure the withdrawal amount is specified in lamports.
```typescript
// Withdrawing 1 SOL
const withdrawAmount = 1_000_000_000 // 1 SOL in lamports
// Fee calculation:
// Base: 0.006 SOL = 6,000,000 lamports
// Protocol: 1 SOL × 0.35% = 0.0035 SOL = 3,500,000 lamports
// Total fee: ~9,500,000 lamports (~0.0095 SOL)
const result = await client.withdraw({
lamports: withdrawAmount,
recipientAddress: 'RECIPIENT'
})
console.log('Requested:', withdrawAmount / 1e9, 'SOL')
console.log('Received:', result.amount_in_lamports / 1e9, 'SOL')
console.log('Fee:', result.fee_in_lamports / 1e9, 'SOL')
```
--------------------------------
### Get SPL Token Balance Method
Source: https://privacycash.mintlify.app/sdk/balance
Retrieves the private balance for a specific SPL token using its mint address.
```typescript
import { PublicKey } from '@solana/web3.js'
const balance = await client.getPrivateBalanceSpl(
mintAddress: PublicKey | string
)
```
--------------------------------
### Check All Balances in TypeScript
Source: https://privacycash.mintlify.app/sdk/balance
Demonstrates fetching balances for native SOL and various SPL tokens using the PrivacyCash client.
```typescript
import { PrivacyCash } from 'privacycash'
import { PublicKey } from '@solana/web3.js'
async function checkAllBalances() {
const client = new PrivacyCash({
RPC_url: process.env.SOLANA_RPC_URL!,
owner: process.env.PRIVATE_KEY!
})
// Check SOL balance
const solBalance = await client.getPrivateBalance()
console.log('SOL:', solBalance.lamports / 1e9)
// Check USDC balance
const usdcBalance = await client.getPrivateBalanceUSDC()
console.log('USDC:', usdcBalance.amount / 1e6)
// Check USDT balance
const USDT_MINT = new PublicKey('Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB')
const usdtBalance = await client.getPrivateBalanceSpl(USDT_MINT)
console.log('USDT:', usdtBalance.amount / 1e6)
// Check ORE balance
const ORE_MINT = new PublicKey('oreoU2P8bN6jkk3jbaiVxYnG1dCXcYxwhwyK9jSybcp')
const oreBalance = await client.getPrivateBalanceSpl(ORE_MINT)
console.log('ORE:', oreBalance.amount / 1e11)
}
checkAllBalances()
```
--------------------------------
### Get Private Balance Function Signature
Source: https://privacycash.mintlify.app/evmsdk/balance
The getBalance function requires a wallet signature and address to retrieve the private balance.
```typescript
import { getBalance } from 'privacycash-evm'
const result = await getBalance({
signature: string,
address: string,
token?: 'eth' | 'usdc' | 'usdt',
network?: NetworkConfig | number
})
```
--------------------------------
### Initialize Privacy Cash Client
Source: https://privacycash.mintlify.app/sdk/overview
Basic client initialization using RPC URL and private key.
```typescript
import { PrivacyCash } from 'privacycash'
const client = new PrivacyCash({
RPC_url: 'YOUR_SOLANA_MAINNET_RPC_URL',
owner: 'YOUR_PRIVATE_KEY',
enableDebug: false // optional
})
```
--------------------------------
### Zero-Knowledge Proof Generation
Source: https://privacycash.mintlify.app/sdk/deposit
Demonstrates that ZK proof generation is handled automatically by the SDK during the deposit process.
```typescript
// The SDK handles all ZK proof generation automatically
const result = await client.deposit({
lamports: 50_000_000 // 0.05 SOL
})
// Behind the scenes:
// 1. ZK proof generated
// 2. Transaction signed
// 3. Sent to relayer
// 4. Confirmed on-chain
```
--------------------------------
### Configure Key Path
Source: https://privacycash.mintlify.app/evmsdk/overview
Specify the path to the circuit zkey file. The SDK automatically appends the required suffix.
```typescript
keyBasePath: './circuits/transaction' // loads ./circuits/transaction2.zkey
```
```typescript
keyBasePath: '/circuit' // loads /circuit2.zkey from public/
```
--------------------------------
### Deposit SPL Tokens with deposit()
Source: https://privacycash.mintlify.app/sdk/deposit-fe
Demonstrates the usage of the deposit function to initiate an SPL token transfer. Requires a configured hasher, connection, and transaction signing callback.
```typescript
import { deposit } from "privacycash/utils"
const result = await deposit({
lightWasm: hasher,
connection,
amount_in_lamports: 1_000_000_000, // 1 SOL
keyBasePath: '/circuit2',
publicKey: userPublicKey,
transactionSigner: async (tx: VersionedTransaction) => {
// let user sign the tx
return await signTransaction(tx)
},
storage: localStorage,
encryptionService,
referrer: '' // optional
});
```
--------------------------------
### getUtxos()
Source: https://privacycash.mintlify.app/sdk/balance-fe
Fetches all valid private UTXOs for a given user.
```APIDOC
## getUtxos()
### Description
Fetches all valid private UTXOs for a given user.
### Parameters
- **connection** (Connection) - Required - Solana web3 connection object.
- **publicKey** (PublicKey) - Required - The user's Solana public key.
- **storage** (Storage) - Required - A storage object (e.g., localStorage).
- **encryptionService** (EncryptionService) - Required - The encryption service to decrypt UTXO data.
- **offset** (number) - Optional - utxo fetch offset
```
--------------------------------
### getBalanceFromUtxos()
Source: https://privacycash.mintlify.app/sdk/balance-fe
Calculates the total balance in lamports from a set of SOL UTXOs.
```APIDOC
## getBalanceFromUtxos()
### Description
Calculates the total balance from a set of SOL UTXOs (Unspent Transaction Outputs).
### Parameters
- **utxos** (Utxo[]) - Required - An array of UTXO objects, typically retrieved using getUtxos().
### Return Value
- **lamports** (number) - The total balance in lamports.
```
--------------------------------
### Initialize Hasher
Source: https://privacycash.mintlify.app/sdk/frontend
Load the WASM hasher instance for cryptographic operations.
```typescript
const { WasmFactory } = await import('@lightprotocol/hasher.rs');
const hasher = await WasmFactory.getInstance();
```
--------------------------------
### Implement Deposit Functionality in React
Source: https://privacycash.mintlify.app/evmsdk/deposit-fe
Uses wagmi hooks to manage wallet state and provides a txSender callback to sign and submit transactions via ethers or walletClient.
```typescript
'use client'
import { ethers } from 'ethers'
import { BASE_NETWORK, ETH_NETWORK, deposit } from 'privacycash-evm'
import { useAccount, useChainId, useWalletClient } from 'wagmi'
export function DepositButton() {
const { address, connector } = useAccount()
const chainId = useChainId()
const { data: walletClient } = useWalletClient()
const handleDeposit = async () => {
if (!address) return
const network = chainId === 1 ? ETH_NETWORK : chainId === 8453 ? BASE_NETWORK : undefined
if (!network) {
alert('Switch to Base or Ethereum mainnet.')
return
}
// Retrieve the stored signature
const signature = localStorage.getItem(`evm_sign_${address}`)
if (!signature) {
alert('Please sign in first.')
return
}
// Build the txSender callback
const txSender = async (unsignedTx: any) => {
if (walletClient) {
return await walletClient.sendTransaction({
to: unsignedTx.to as `0x${string}`,
data: unsignedTx.data as `0x${string}`,
value: BigInt(unsignedTx.value?.toString() ?? '0'),
})
}
// Fallback via ethers BrowserProvider
const ethereum = await connector?.getProvider()
const provider = new ethers.BrowserProvider(ethereum as any)
const signer = await provider.getSigner(address)
const tx = await signer.sendTransaction(unsignedTx)
return tx.hash
}
const txHash = await deposit({
depositAmountInput: 0.01,
keyBasePath: '/circuit',
signature,
address,
txSender,
token: 'eth',
network,
})
console.log('Deposit tx:', txHash)
}
return
}
```
--------------------------------
### getUtxosSPL()
Source: https://privacycash.mintlify.app/sdk/balance-fe
Fetches all valid private SPL token UTXOs for a given user and specific token mint.
```APIDOC
## getUtxosSPL()
### Description
Fetches all valid private SPL token UTXOs for a given user and specific token mint.
### Parameters
- **connection** (Connection) - Required - Solana web3 connection object.
- **publicKey** (PublicKey) - Required - The user's Solana public key.
- **storage** (Storage) - Required - A storage object (e.g., localStorage).
- **encryptionService** (EncryptionService) - Required - The encryption service.
- **mintAddress** (PublicKey or string) - Required - The mint address of the SPL token.
- **offset** (number) - Optional - utxo fetch offset
```
--------------------------------
### Auto-Refresh Balance Pattern
Source: https://privacycash.mintlify.app/evmsdk/balance-fe
Shows how to trigger a balance re-fetch by using a state-based change counter after transactions like deposits or withdrawals.
```typescript
const [balanceChanged, setBalanceChanged] = useState(0)
const network = chainId === 1 ? ETH_NETWORK : chainId === 8453 ? BASE_NETWORK : undefined
const token = 'eth'
useEffect(() => {
if (!address || !network) return
const signature = localStorage.getItem(`evm_sign_${address}`)
if (!signature) return
getBalance({ signature, address, token, network }).then(res => setBalance(res.balance))
}, [balanceChanged, address, token, network])
// After a successful deposit or withdrawal:
setBalanceChanged(prev => prev + 1)
```
--------------------------------
### getBalanceFromUtxosSPL()
Source: https://privacycash.mintlify.app/sdk/balance-fe
Calculates the total balance in base units from a set of SPL token UTXOs.
```APIDOC
## getBalanceFromUtxosSPL()
### Description
Calculates the total balance from a set of SPL token UTXOs.
### Parameters
- **utxos** (Utxo[]) - Required - An array of UTXO objects, retrieved using getUtxosSPL().
### Return Value
- **base_units** (number) - The total balance in base units.
```
--------------------------------
### deposit()
Source: https://privacycash.mintlify.app/evmsdk/deposit-fe
The deposit() function initiates a deposit of ETH or supported ERC-20 tokens into the Privacy Cash protocol.
```APIDOC
## deposit(params)
### Description
Deposits ETH or a supported ERC-20 token into Privacy Cash on an EVM network.
### Parameters
- **depositAmountInput** (number) - Required - Amount to deposit, denominated in the selected token.
- **keyBasePath** (string) - Required - Base path for the circuit zkey.
- **signature** (string) - Required - Wallet signature of the Privacy Cash sign-in message.
- **address** (string) - Required - The depositor's EVM wallet address.
- **txSender** (Function) - Required - Callback to sign and submit the raw transaction: `(unsignedTx: any) => Promise`.
- **token** ('eth' | 'usdc' | 'usdt') - Optional - Defaults to 'eth'.
- **network** (NetworkConfig | number) - Optional - Pass BASE_NETWORK, ETH_NETWORK, or a supported chain ID.
### Returns
- **Promise** - Returns the transaction hash of the deposit.
```
--------------------------------
### Configure Circuit Key Path
Source: https://privacycash.mintlify.app/evmsdk/frontend
Define the base path for the circuit key file located in the public directory.
```typescript
keyBasePath: '/circuit' // resolves to /circuit2.zkey at runtime
```
--------------------------------
### Derive Encryption Key
Source: https://privacycash.mintlify.app/evmsdk/frontend
Implement message signing to derive the user's private encryption key and UTXO keypair.
```typescript
import { useSignMessage } from 'wagmi'
const SIGN_MESSAGE = 'Privacy Money account sign in'
const LS_KEY_PREFIX = 'evm_sign_'
function saveSignature(address: string, signature: string) {
localStorage.setItem(`${LS_KEY_PREFIX}${address}`, signature)
}
function getStoredSignature(address: string): string | null {
return localStorage.getItem(`${LS_KEY_PREFIX}${address}`)
}
// In your component:
const { signMessage } = useSignMessage()
const { address } = useAccount()
function handleSignIn() {
signMessage(
{ message: SIGN_MESSAGE },
{
onSuccess(signature) {
saveSignature(address!, signature)
},
}
)
}
```
```typescript
useEffect(() => {
if (!isConnected || !address) return
const stored = getStoredSignature(address)
if (!stored) handleSignIn()
}, [isConnected, address])
```
--------------------------------
### getBalance()
Source: https://privacycash.mintlify.app/evmsdk/balance-fe
Retrieves the private ETH or ERC-20 balance for a given wallet address using a signature.
```APIDOC
## getBalance(params)
### Description
Retrieves your private ETH or ERC-20 balance from Privacy Cash on an EVM network. The function scans historic events and decrypts them locally using a key derived from the provided signature.
### Parameters
- **signature** (string) - Required - Wallet signature of the Privacy Cash sign-in message.
- **address** (string) - Required - Your EVM wallet address.
- **token** ('eth' | 'usdc' | 'usdt') - Optional - Defaults to 'eth'.
- **network** (NetworkConfig | number) - Optional - Pass BASE_NETWORK, ETH_NETWORK, or a supported chain ID.
### Return Value
- **balance** (string) - Total private balance as a decimal string (e.g. "0.05").
```
--------------------------------
### Authenticate with Wallet Signature
Source: https://privacycash.mintlify.app/evmsdk/overview
Derive encryption and UTXO keys by signing a fixed message with the user's wallet.
```typescript
import { ethers } from 'ethers'
import { BASE_NETWORK, ETH_NETWORK } from 'privacycash-evm'
const network = ETH_NETWORK // or BASE_NETWORK
const SIGN_MESSAGE = 'Privacy Money account sign in'
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl, {
name: network.chainKey,
chainId: network.chainId,
})
const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider)
const signature = await signer.signMessage(SIGN_MESSAGE)
const address = await signer.getAddress()
```
--------------------------------
### Fetch user UTXOs
Source: https://privacycash.mintlify.app/sdk/balance-fe
Retrieves all valid private UTXOs for a user, requiring a connection, public key, storage, and encryption service.
```typescript
const myValidUtxos = await getUtxos({
connection,
publicKey,
storage: localStorage,
encryptionService,
});
```
--------------------------------
### Select Network for SDK Calls
Source: https://privacycash.mintlify.app/evmsdk/frontend
Pass the active network to SDK functions to ensure correct multi-chain interaction.
```typescript
import { BASE_NETWORK, ETH_NETWORK, getBalance } from 'privacycash-evm'
import { useChainId } from 'wagmi'
function BalanceLoader({ signature, address }: { signature: string, address: string }) {
const chainId = useChainId()
const network = chainId === 1 ? ETH_NETWORK : chainId === 8453 ? BASE_NETWORK : undefined
async function refreshBalance() {
if (!network) throw new Error('Switch to Base or Ethereum mainnet.')
return getBalance({
signature,
address,
network,
})
}
return null // Render your balance UI here.
}
```
--------------------------------
### Automatic balance consolidation
Source: https://privacycash.mintlify.app/evmsdk/deposit
New deposits are automatically merged with existing private balances into a single UTXO.
```typescript
// First deposit: 0.05 ETH
await deposit({ depositAmountInput: 0.05, ...sharedParams })
// Second deposit: 0.03 ETH — merged into a single UTXO
await deposit({ depositAmountInput: 0.03, ...sharedParams })
// Private balance is now 0.08 ETH (minus network fees)
```
--------------------------------
### Deposit SOL with Privacy Cash SDK
Source: https://privacycash.mintlify.app/sdk/deposit
Basic method signature for depositing SOL into the privacy pool.
```typescript
const result = await client.deposit({
lamports: number
})
```
--------------------------------
### Implement PrivacyCash bridge logic
Source: https://privacycash.mintlify.app/sdk/bridge
This script handles configuration, fee calculation, and the initial steps of the bridging process including quote retrieval and withdrawal execution.
```typescript
import { Connection, PublicKey, Keypair } from "@solana/web3.js";
import {
EncryptionService,
withdraw,
withdrawSPL,
tokens
} from "privacycash";
// Configuration
const BRIDGE_URL = 'https://api3.privacycash.org/bridge';
const SOLANA_RPC = 'https://api.mainnet-beta.solana.com';
// Available output chain-tokens
const tokenMap: Record = {
"ethereum": ["eth", "usdc", "usdt", "dai"],
"bnb": ["bnb", "usdc", "usdt"],
"base": ["eth", "usdc"],
"pol": ["pol", "usdc", "usdt"],
"bitcoin": ["btc"],
};
/**
* Calculates the net amount the recipient will receive after PrivacyCash
* withdrawal fees are subtracted.
*/
async function calculateWithdrawableAmount(amount: number, tokenName: string) {
const configResp = await fetch('https://api3.privacycash.org/config');
const config = await configResp.json();
// Find token decimals and units
const token = tokens.find(t => t.name === tokenName);
if (!token) throw new Error("Token not supported");
const feeRate = config.withdraw_fee_rate;
const rentFeePerRecipient = config.rent_fees[tokenName] || 0;
const withdrawUnites = amount * token.units_per_token;
const withdrawRateFee = Math.floor(withdrawUnites * feeRate);
const withdrawRentFee = Math.floor(token.units_per_token * rentFeePerRecipient);
const totalFeeUnites = withdrawRateFee + withdrawRentFee;
const totalFeeAmount = totalFeeUnites / token.units_per_token;
return amount - totalFeeAmount;
}
async function runBridge() {
// Setup
const connection = new Connection(SOLANA_RPC);
// user pubkey
const publicKey = new PublicKey('UserPublicKeyHere');
// bridge recipient address
const recipientAddress = '0x...'
// The message signature used to derive your PrivacyCash encryption key
const userSignature = await getUserSignature(publicKey);
const encryptionService = new EncryptionService();
encryptionService.deriveEncryptionKeyFromSignature(userSignature);
const inputTokenName = 'usdc';
const inputAmount = 100; // The total amount you want to withdraw from the private pool
// Calculate how much the relayer will actually receive after PrivacyCash subtraction
const withdrawableAmount = await calculateWithdrawableAmount(inputAmount, inputTokenName);
// Bridge Parameters
const params = {
inputChain: 'solana',
outputChain: 'ethereum',
inputTokenName: inputTokenName, // Supported: 'sol', 'usdc', 'usdt'
outputTokenName: 'usdc',
inputTokenAmount: withdrawableAmount.toString(), // Net amount for the relayer
refundAddress: publicKey.toString(),
recipientAddress: recipientAddress, // Destination address on outputChain
quoteWaitingTimeMs: 3000 // Recommended delay for best routing
};
try {
// STEP 1: Get Quote and Deposit Address from Relayer
console.log(`Fetching bridge quote for ${withdrawableAmount} ${inputTokenName}...`);
const quoteResponse = await fetch(BRIDGE_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...params, step: 'quote' })
});
const quoteData = await quoteResponse.json();
if (!quoteData.success) throw new Error(quoteData.error || "Failed to get quote");
const depositAddress = quoteData.quote.depositAddress;
console.log(`Quote received. Relayer Deposit Address: ${depositAddress}`);
// STEP 2: Execute PrivacyCash Withdrawal
console.log("Executing private withdrawal to relayer...");
let txHash: string;
```
--------------------------------
### Withdraw USDC Convenience Method
Source: https://privacycash.mintlify.app/sdk/spl-tokens
Use this method to withdraw USDC. The base_units parameter represents the amount in the smallest unit of the token.
```typescript
const result = await client.withdrawUSDC({
base_units: number,
recipientAddress?: string,
referrer?: string
})
```
```typescript
// Withdraw 100 USDC
const result = await client.withdrawUSDC({
base_units: 100_000_000, // 100 USDC
recipientAddress: 'CLEAN_WALLET'
})
```
--------------------------------
### depositSPL(config)
Source: https://privacycash.mintlify.app/sdk/deposit-fe
Deposits SPL tokens into the PrivacyCash protocol using the provided configuration object.
```APIDOC
## depositSPL(config)
### Description
Deposits SPL tokens (such as USDC) into the PrivacyCash protocol.
### Parameters
- **mintAddress** (PublicKey) - Required - The mint address of the SPL token to deposit.
- **base_units** (number) - Required - The amount of tokens to deposit, specified in base units.
- **lightWasm** (any) - Required - The Poseidon hasher instance.
- **connection** (Connection) - Required - Solana web3 connection object.
- **keyBasePath** (string) - Required - The base path for loading circuit zkeys.
- **publicKey** (PublicKey) - Required - The user's Solana public key.
- **transactionSigner** (Function) - Required - A callback function to sign the generated transaction.
- **storage** (Storage) - Required - A storage object.
- **encryptionService** (EncryptionService) - Required - An instance of the EncryptionService.
- **referrer** (string) - Optional - The Solana address of the referrer.
### Example Usage
```typescript
import { deposit } from "privacycash/utils"
const result = await deposit({
lightWasm: hasher,
connection,
amount_in_lamports: 1_000_000_000,
keyBasePath: '/circuit2',
publicKey: userPublicKey,
transactionSigner: async (tx: VersionedTransaction) => {
return await signTransaction(tx)
},
storage: localStorage,
encryptionService,
referrer: ''
});
```
```
--------------------------------
### Calculate SOL balance from UTXOs
Source: https://privacycash.mintlify.app/sdk/balance-fe
Calculates the total balance in lamports from an array of UTXO objects.
```typescript
import { getUtxos, getBalanceFromUtxos } from "privacycash/utils"
// 1. Fetch user UTXOs
const myValidUtxos = await getUtxos({
connection,
publicKey,
storage: localStorage,
encryptionService,
});
// 2. Calculate balance
const balanceInfo = getBalanceFromUtxos(myValidUtxos);
console.log("Total SOL Balance (lamports):", balanceInfo.lamports);
```
--------------------------------
### deposit()
Source: https://privacycash.mintlify.app/sdk/deposit-fe
The deposit() function is used to deposit SOL into the PrivacyCash protocol. It requires a configuration object containing connection details, cryptographic instances, and signing callbacks.
```APIDOC
## deposit(config)
### Description
Deposits SOL into the PrivacyCash protocol.
### Parameters
- **lightWasm** (any) - Required - The Poseidon hasher instance.
- **connection** (Connection) - Required - Solana web3 connection object.
- **amount_in_lamports** (number) - Required - The amount of SOL to deposit in lamports.
- **keyBasePath** (string) - Required - The base path for loading circuit zkeys.
- **publicKey** (PublicKey) - Required - The user's Solana public key.
- **transactionSigner** (Function) - Required - Callback to sign the transaction: (tx: VersionedTransaction) => Promise.
- **storage** (Storage) - Required - Web Storage API implementation.
- **encryptionService** (EncryptionService) - Required - Service for encrypting UTXO data.
- **referrer** (string) - Optional - The Solana address of the referrer.
### Example Usage
```typescript
import { deposit } from "privacycash/utils";
const result = await deposit({
lightWasm: hasher,
connection: connection,
amount_in_lamports: 1000000,
keyBasePath: '/circuit2',
publicKey: userPublicKey,
transactionSigner: async (tx) => await signTransaction(tx),
storage: localStorage,
encryptionService: encryptionService,
referrer: '...'
});
```
```