Documentation Index
Fetch the complete documentation index at: https://docs.privacyboost.io/llms.txt
Use this file to discover all available pages before exploring further.
API Reference
Complete API reference for the Privacy Boost TypeScript SDK.
Generated Documentation
Full API documentation can be generated using TypeDoc:
# From packages/privacy-boost-ts directory
npm run docs
# Documentation will be generated in docs/api/
The generated docs include:
- All exported types and interfaces
- JSDoc comments and examples
- Type signatures and inheritance
PrivacyBoost
Main SDK class.
PrivacyBoost.create(config)
Creates and initializes a new SDK instance.
static async create(config: PrivacyBoostConfig): Promise<PrivacyBoost>
Parameters:
| Name | Type | Description |
|---|
config.appId | string | Application identifier |
config.serverUrl | string | Privacy Boost server URL |
config.chainId | number | (Optional) EVM chain ID (auto-discovered from server) |
config.shieldContractAddress | string | (Optional) Shield contract address (auto-discovered from server) |
config.wethContractAddress | string | (Optional) WETH contract address |
Example:
const sdk = await PrivacyBoost.create({
appId: 'your-app-id',
serverUrl: 'https://test-api.privacyboost.io',
wethContractAddress: "0x4200000000000000000000000000000000000006"
});
sdk.auth
Authentication resource.
auth.authenticate(adapter, options?)
Connect a wallet, derive privacy keys, and authenticate with the server in a single call.
async authenticate(
adapter: WalletAdapter,
options?: AuthenticateOptions
): Promise<AuthResult>
interface AuthenticateOptions {
keySource?: KeySource;
tokenProvider?: (payload: LoginPayload) => Promise<{ token: string; expiresIn: number }>;
}
Parameters:
| Name | Type | Description |
|---|
adapter | WalletAdapter | Wallet adapter implementation |
options | AuthenticateOptions | (Optional) Options object with keySource and tokenProvider |
options.keySource | KeySource | (Optional) Key derivation source. Defaults to walletDerived when no persistence is configured. |
options.tokenProvider | function | (Optional) Callback to obtain a JWT from the login payload |
Returns: AuthResult - either { status: 'authenticated', privacyAddress, mpk } or { status: 'credentialRequired', action, unlockType, submit }. If credential is required, call result.submit(credential) to complete authentication.
auth.logout()
End session completely, clear all state.
async logout(): Promise<void>
auth.clearSession()
Clear JWT only, keep keys for quick re-auth.
async clearSession(): Promise<void>
auth.isConnected()
Check if wallet is connected.
auth.isAuthenticated()
Check if user is authenticated.
isAuthenticated(): boolean
auth.getPrivacyAddress()
Get user’s privacy address.
getPrivacyAddress(): string | null
auth.getMpk()
Get user’s master public key.
sdk.vault
Vault resource for privacy operations.
vault.shield(params)
Deposit tokens to private balance.
async shield(params: ShieldParams): Promise<ShieldResult>
interface ShieldParams {
tokenAddress: Hex;
amount: bigint;
/** Defaults to the caller's own MPK. Set to shield directly to another user. */
recipientMpk?: bigint;
onProgress?: OnProgress;
}
interface ShieldResult {
/** Hash of the shield transaction submitted to the chain. */
txHash: Hex;
/** Note commitment registered in the shielded pool. */
commitment: Hex;
/** Fee charged for this shield, in token wei. */
fee: bigint;
/** On-chain shield request ID, from the `ShieldRequested` event. */
requestId: string;
/** Set only when ETH was wrapped to WETH as part of the flow. */
wrapTxHash?: Hex;
}
vault.unshield(params)
Withdraw tokens to public address.
async unshield(params: UnshieldParams): Promise<UnshieldResult>
interface UnshieldParams {
tokenAddress: Hex;
amount: bigint;
recipientAddress: Hex;
onProgress?: OnProgress;
/**
* When true and the token is WETH, automatically wait for the unshield to
* land on-chain and then unwrap the received WETH back to native ETH.
* Requires `wethContractAddress` to be configured. Reports
* `UnshieldStep.unwrapping` via `onProgress`.
*/
unwrapWeth?: boolean;
}
interface UnshieldResult {
/** Server-side request ID for this unshield. Use to track status. */
requestId: string;
/**
* Local placeholder hash used to track pending status until the canonical
* on-chain hash is available. Not the final on-chain transaction hash.
*/
txHash: Hex;
/** Amount unshielded, in token wei. */
amount: bigint;
}
vault.send(params)
Send private transfer.
async send(params: SendParams): Promise<TransactionResult>
interface SendParams {
to: PrivacyAddress;
tokenAddress: Hex;
amount: bigint;
}
interface TransactionResult {
/** Server-side request ID for this transfer. Use to track status. */
requestId: string;
/**
* Local placeholder hash used to track pending status until the canonical
* on-chain hash is available. Not the final on-chain transaction hash.
*/
txHash: Hex;
}
vault.getBalance(tokenAddress)
Get the cached balance entry for a token. Reads from the local store and may
fetch from the server on a cache miss. To force a network refresh, call
vault.refreshBalance(tokenAddress) first.
async getBalance(tokenAddress: string): Promise<TokenBalance>
vault.getAllBalances()
Get all token balances.
async getAllBalances(): Promise<TokenBalance[]>
interface TokenBalance {
tokenAddress: Hex;
/** Private balance held in the shielded pool, in token wei. */
shieldedBalance: bigint;
/** Public balance in the connected wallet, in token wei. */
walletBalance: bigint;
symbol?: string;
decimals?: number;
/** Number of unspent notes contributing to `shieldedBalance`. */
noteCount?: number;
}
vault.refreshBalance(tokenAddress)
Refresh a single token balance from the server.
async refreshBalance(tokenAddress: Hex): Promise<void>
vault.refreshBalances()
Refresh all tracked balances from the server.
async refreshBalances(): Promise<void>
vault.getToken(address)
Get token metadata for a single token.
async getToken(address: string): Promise<TokenMetadata>
interface TokenMetadata {
address: Hex;
symbol: string;
decimals: number;
name: string;
priceUSD?: number;
/** Minimum shield amount enforced by the protocol, in token wei (string). */
minShieldAmount?: string;
}
vault.getTokens()
Get metadata for every token registered with the protocol.
async getTokens(): Promise<TokenMetadata[]>
parseAmount(amount, decimals)
Parse a human-readable amount to a bigint. Exported as a standalone utility from the SDK package.
import { parseAmount } from '@sunnyside-io/privacy-boost';
parseAmount(amount: string, decimals: number): bigint
Format a bigint amount as a human-readable string. Exported as a standalone utility from the SDK package.
import { formatAmount } from '@sunnyside-io/privacy-boost';
formatAmount(amount: bigint, decimals: number): string
sdk.transactions
Transactions resource.
transactions.fetchHistory(params?)
Get transaction history.
async fetchHistory(params?: TransactionHistoryParams): Promise<Transaction[]>
interface TransactionHistoryParams {
type?: TransactionType;
tokenAddress?: string;
limit?: number;
}
interface Transaction {
txHash: Hex;
type: TransactionType;
direction: TransactionDirection;
status: TransactionStatus;
tokenAddress?: Hex;
amount?: bigint;
receivers: ReceiverTransfer[];
createdAt: number;
updatedAt: number;
to?: Hex;
from?: Hex;
tokenSymbol?: string;
commitment?: Hex;
complianceStatus?: ComplianceStatus;
error?: string;
}
enum TransactionType {
shield = 'shield',
unshield = 'unshield',
transfer = 'transfer',
}
enum TransactionDirection {
incoming = 'incoming',
outgoing = 'outgoing',
}
enum TransactionStatus {
pending = 'pending',
/** Submitted on-chain, not yet finalized. */
preconfirmed = 'preconfirmed',
completed = 'completed',
failed = 'failed',
/** Blocked by compliance. See `complianceStatus`. */
blocked = 'blocked',
}
Utility Functions
isValidPrivacyAddress(address)
Check if address is valid privacy address.
function isValidPrivacyAddress(address: string): boolean
validatePrivacyAddress(address)
Validate a privacy address.
function validatePrivacyAddress(address: string): { valid: boolean; message: string }
encodePrivacyAddress(mpk, viewingPublicKey)
Encode MPK and viewing public key to privacy address.
function encodePrivacyAddress(mpk: bigint, viewingPublicKey: Point): PrivacyAddress
decodePrivacyAddress(address)
Decode privacy address to components.
function decodePrivacyAddress(address: PrivacyAddress): {
mpk: bigint;
viewingPublicKey: Point;
}
Extract MPK from privacy address.
function extractMpkFromPrivacyAddress(address: PrivacyAddress): Hex
isEvmAddress(address)
Check if valid EVM address.
function isEvmAddress(address: string): boolean
isNativeEth(address)
Check if address represents native ETH.
function isNativeEth(address: Hex): boolean
Types
KeySource
Key derivation source, passed to authenticate().
type KeySource =
| { type: 'walletDerived' }
| { type: 'mnemonic'; phrase: string }
| { type: 'rawSeed'; hexSeed: string };
| Variant | Description |
|---|
walletDerived | Derive keys from a wallet signature (default when no persistence is configured) |
mnemonic | Derive keys from a BIP-39 mnemonic phrase |
rawSeed | Derive keys from a raw 32-byte hex seed |
Hex
PrivacyAddress
type PrivacyAddress = string // 96-byte payload, 194 chars including `0x` prefix
The payload encodes the master public key (32 bytes) and the viewing public key X/Y (32 bytes each). Hex-encoded, that is 192 characters; including the 0x prefix the string is 194 characters.
WalletAdapter
interface WalletAdapter {
connect(): Promise<{ address: string; chainId: number }>;
disconnect(): Promise<void>;
signMessage(message: string): Promise<string>;
/** `typedDataJson` is a JSON-stringified EIP-712 typed-data payload. */
signTypedData(typedDataJson: string): Promise<string>;
sendTransaction(tx: unknown): Promise<string>;
getAddress(): Promise<string>;
getChainId(): Promise<number>;
}
OnProgress
type OnProgress = (progress: {
step: ShieldStep | UnshieldStep;
message: string;
txHash?: Hex;
}) => void
enum ShieldStep {
wrapping = 'wrapping', // Wrapping ETH to WETH
approving = 'approving', // Approving token spend
shielding = 'shielding', // Submitting the shield transaction
registering = 'registering', // Registering the note with the indexer
compliance = 'compliance', // Awaiting compliance check
}
enum UnshieldStep {
preparing = 'preparing', // Fetching notes and proofs
signing = 'signing', // Signing the transaction
proving = 'proving', // Generating the ZK proof
unshielding = 'unshielding', // Submitting the unshield transaction
unwrapping = 'unwrapping', // Unwrapping WETH back to ETH (only if `unwrapWeth: true`)
}
FeeRates
Fee schedule applied to vault operations.
interface FeeRates {
/** Flat fee added to private transfers, in token wei (string). Defaults to "0". */
transferFeeFlat: string;
/** Fee deducted from unshields, in basis points (1 bp = 0.01%). */
unshieldFeeBps: number;
/** Whether the user pays the fee or the application sponsors it. */
feeModel?: 'user_pays' | 'app_pays';
}
When feeModel is 'app_pays', the fee is settled out of band by the application — users see the gross amount. Shield fees are reported in ShieldResult.fee.
ComplianceStatus
type ComplianceStatus = 'PENDING' | 'LEGIT' | 'ILLICIT';
| Status | Meaning |
|---|
PENDING | Compliance check is in progress; the deposit cannot be spent yet. |
LEGIT | Cleared; funds are usable. |
ILLICIT | Rejected by compliance; funds are quarantined. See Error Handling. |
Constants
const NATIVE_ETH_ADDRESS = '0x0000000000000000000000000000000000000000';
const PRIVACY_ADDRESS_LENGTH = 194;
const PRIVACY_ADDRESS_HEX_LENGTH = 192;