> ## 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.

# Getting started

# Getting Started

This guide walks you through the basic usage of the Privacy Boost WASM SDK.

## Overview

The WASM SDK provides direct access to the Rust-based Privacy Boost core functionality from JavaScript. It's ideal for:

* Custom integrations beyond the TypeScript SDK
* Performance-critical applications
* Server-side Node.js usage
* Direct WASM module control

## Basic Setup

### Initialize the SDK

```typescript theme={null}
import init, { PrivacyBoost } from '@sunnyside-io/privacy-boost-wasm';

// Initialize WASM module first (required once per page load)
await init();

// Create SDK instance with configuration
const sdk = new PrivacyBoost({
  serverUrl: 'https://optimism.sepolia.privacyboost.io',
  appId: 'app_abc123xyz',
  wethContractAddress: '0x4200000000000000000000000000000000000006', // Optional
});
```

## Create a Wallet Adapter

The SDK requires a wallet adapter to sign messages and send transactions:

```typescript theme={null}
const walletAdapter = {
  async getAddress(): Promise<string> {
    // Return the connected wallet address
    return '0x1234...';
  },

  async getChainId(): Promise<number> {
    // Return current chain ID
    return 1;
  },

  async signMessage(message: string): Promise<string> {
    // Sign a personal message (EIP-191)
    // Return 65-byte signature as hex string
    return '0x...signature';
  },

  async signTypedData(typedDataJson: string): Promise<string> {
    // Sign EIP-712 typed data
    // Return 65-byte signature as hex string
    return '0x...signature';
  },

  async sendTransaction(tx: {
    to: string;
    value: string;
    data: string;
  }): Promise<string> {
    // Send transaction and return tx hash
    return '0x...txhash';
  },

  async waitForTransactionReceipt(txHash: string): Promise<{
    transactionHash: string;
    status: boolean;
    logs: unknown[];
  }> {
    // Wait for the transaction to be mined and return its receipt
    return {
      transactionHash: txHash,
      status: true,
      logs: [],
    };
  },
};
```

## Authenticate

Connect wallet and authenticate in a single call:

```typescript theme={null}
try {
  const result = await sdk.authenticate(walletAdapter, undefined);
  switch (result.status) {
    case 'authenticated':
      console.log('Privacy Address:', result.privacyAddress);
      console.log('MPK:', result.mpk);
      break;
    case 'credentialRequired':
      await sdk.submitCredential('user-pin-or-password');
      break;
    case 'mnemonicGenerated':
      // `result.mnemonic` is the account's only recovery secret. Render it in
      // the UI for the user to write down — do not log it. Console output is
      // captured by devtools history, crash reporters, and log collectors, and
      // anyone who reads it back owns the account forever.
      await sdk.proceedAfterMnemonic('new-pin-or-password');
      break;
    case 'recoveryRequired':
      await sdk.authenticate(walletAdapter, {
        type: 'mnemonic',
        phrase: 'word1 word2 ...',
      });
      break;
  }
  console.log('Is authenticated:', sdk.isAuthenticated);
} catch (error) {
  console.error('Authentication failed:', error);
}
```

## Check Balance

```typescript theme={null}
const WETH_ADDRESS = '0x4200000000000000000000000000000000000006';

const balance = await sdk.getBalance(WETH_ADDRESS);
console.log('Shielded balance:', balance.shieldedBalance);

// Get all balances
const allBalances = await sdk.getAllBalances();
for (const bal of allBalances) {
  console.log(`${bal.tokenAddress}: ${bal.shieldedBalance}`);
}
```

## Deposit Tokens

```typescript theme={null}
const tokenAddress = '0x4200000000000000000000000000000000000006';
const amount = '1000000000000000000'; // 1 ETH in wei

try {
  const result = await sdk.shield({
    tokenAddress,
    amount,
  });
  console.log('Deposit TX:', result.txHash);
  console.log('Commitment:', result.commitment);
} catch (error) {
  console.error('Deposit failed:', error);
}
```

## Withdraw Tokens

```typescript theme={null}
const tokenAddress = '0x4200000000000000000000000000000000000006';
const amount = '500000000000000000'; // 0.5 ETH
const recipient = '0x...'; // Ethereum address

try {
  const result = await sdk.unshield({
    tokenAddress,
    amount,
    recipient,
  });
  console.log('Withdraw TX:', result.txHash);
} catch (error) {
  console.error('Withdraw failed:', error);
}
```

## Send Private Transfer

```typescript theme={null}
const tokenAddress = '0x4200000000000000000000000000000000000006';
const amount = '100000000000000000'; // 0.1 ETH
const recipient = '0x...'; // 194-character privacy address

try {
  const result = await sdk.send({
    tokenAddress,
    amount,
    recipient,
  });
  console.log('Transfer TX:', result.txHash);
} catch (error) {
  console.error('Transfer failed:', error);
}
```

## Utility Functions

```typescript theme={null}
// Validate addresses
const isValidPrivacy = sdk.isValidPrivacyAddress('0x...');
const isValidEth = sdk.isValidAddress('0x...');

// Parse/format amounts
const wei = sdk.parseAmount('1.5', 18);  // "1500000000000000000"
const eth = sdk.formatAmount('1500000000000000000', 18);  // "1.5"

// Get checksum address
const checksum = sdk.toChecksumAddress('0x...');
```

## State Getters

```typescript theme={null}
// Connection state
console.log('Connected:', sdk.isConnected);
console.log('Wallet:', sdk.walletAddress);
console.log('Chain ID:', sdk.chainId);

// Auth state
console.log('Authenticated:', sdk.isAuthenticated);
console.log('Privacy Address:', sdk.getPrivacyAddress());
console.log('MPK:', sdk.getMpk());

// Full state object
const state = sdk.getState();
console.log('State:', state);
```

## Logout

```typescript theme={null}
sdk.logout();
// Session ended, all state cleared
```

## Error Handling

```typescript theme={null}
try {
  await sdk.shield({ tokenAddress, amount });
} catch (error) {
  // Errors are thrown as JavaScript Error objects
  if (error.message.includes('Not authenticated')) {
    // User needs to login first
  } else if (error.message.includes('Insufficient balance')) {
    // Not enough tokens
  } else if (error.message.includes('Network error')) {
    // Backend unreachable
  }
}
```

## Next Steps

* [Deposits](./guides/deposits) - Deposit tokens into the shielded pool
* [Withdrawals](./guides/withdrawals) - Withdraw tokens from the shielded pool
* [Transfers](./guides/transfers) - Send tokens privately
* [Wallet Integration](./guides/wallet-integration) - Detailed wallet adapter setup
* [Browser Setup](./guides/browser-setup) - Browser-specific considerations
* [API Reference](./api-reference) - Complete API documentation


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.