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

# API Reference

Complete API reference for the Privacy Boost TypeScript SDK.

## Generated Documentation

Full API documentation can be generated using TypeDoc:

```bash theme={null}
# 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.

```typescript theme={null}
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 |
| `config.approvalOnly` | `boolean` | (Optional) Use approval-only accounts with no standing spend key |
| `config.keyVault` | `{ mode: 'iframe' \| 'local'; iframeUrl?: string }` | (Optional) Key isolation mode; browser default is `iframe` |

**Example:**

```typescript theme={null}
const sdk = await PrivacyBoost.create({
  appId: 'your-app-id',
  serverUrl: 'https://optimism.sepolia.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.

```typescript theme={null}
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 |

If `tokenProvider` throws, the SDK reports `AUTHENTICATION_FAILED`, which is
not retryable: it treats the throw as your auth backend refusing the login. For
a failure that is worth retrying, such as a 5xx or a timeout from your backend,
throw an error with `retryable: true` and the SDK reports a retryable
`NETWORK_ERROR` instead. An error with `code: 'RATE_LIMITED'` and
`retryAfterMs` is reported as a rate limit. A `fetch` that got no response at
all already counts as retryable. `getExternalToken` is handled the same way.

`approvalOnly: true` requires the SDK's wallet-bound
`/auth/login` → `/auth/upgrade` flow. Do not provide `tokenProvider` in this
mode; the SDK rejects that combination because a provider JWT does not prove
current control of the account owner wallet.

**Returns:** `AuthResult`. Handle all five statuses: `authenticated`,
`credentialRequired`, `mnemonicGenerated`, `recoveryRequired`, and
`accountCreationRequired`. If credentials are required, call
`result.submit(credential)`. For `accountCreationRequired`, submit the supplied
`createAccountTransaction`, wait until the account is indexed, then call
`authenticate()` again.

### `auth.authenticateAsSafeMember(adapter, params)`

Authenticate as a current owner of an approval-only Safe. If the shared Safe
identity exists but its account is missing on this chain, the method returns
the Safe transaction needed to create it without prompting the wallet:

```typescript theme={null}
const result = await sdk.auth.authenticateAsSafeMember(adapter, { safeAddress });

if (result.status === 'safeAccountCreationRequired') {
  await proposeToSafe(result.createAccountTransaction);
  // Retry authentication after AccountCreated is indexed.
}
```

The result also includes `accountId`. Executing `createAccountTransaction`
remains subject to the Safe's normal owner and threshold policy.

### `auth.bootstrapSafeAccount(adapter, params, mnemonic)`

First-time setup for a Safe that has no account yet, with the escrow done
before the account is created. Derive the account from a phrase with
`prepareSafeAccount`, then escrow its identity and get the `createAccount`
transaction back in one call:

```typescript theme={null}
const { mnemonic } = await sdk.auth.prepareSafeAccount(safeAddress);
await showAndConfirm(mnemonic);

const { createAccountTransaction, accountExists } =
  await sdk.auth.bootstrapSafeAccount(adapter, { safeAddress }, mnemonic);
if (!accountExists) {
  await proposeToSafe(createAccountTransaction);
}
// Any owner, on any device: authenticateAsSafeMember reports
// safeAccountCreationRequired with this same transaction until the Safe
// executes it, then signs in.
```

Because the identity is escrowed first, the salt is fixed server-side before
anything is queued: a closed tab or a second owner signing in cannot produce a
second `createAccount`, and the phrase is a backup rather than a prerequisite
for finishing. The wallet is prompted twice (EIP-4361 login, then the ViewAuth
upgrade), no session is published, and the call is idempotent for the same
phrase. Requires a server that admits a Safe-member session on an uncreated
account.

### `auth.logout()`

End session completely, clear all state.

```typescript theme={null}
async logout(): Promise<void>
```

### `auth.clearSession()`

Clear JWT only, keep keys for quick re-auth.

```typescript theme={null}
async clearSession(): Promise<void>
```

### `auth.isConnected()`

Check if wallet is connected.

```typescript theme={null}
isConnected(): boolean
```

### `auth.isAuthenticated()`

Check if user is authenticated.

```typescript theme={null}
isAuthenticated(): boolean
```

### `auth.getPrivacyAddress()`

Get user's privacy address.

```typescript theme={null}
getPrivacyAddress(): string | null
```

### `auth.getMpk()`

Get user's master public key.

```typescript theme={null}
getMpk(): string | null
```

### `auth.revealRecoveryPhrase(options?)`

Show the user their recovery phrase again, drawn by the key vault itself.

```typescript theme={null}
async revealRecoveryPhrase(options?: RevealMnemonicOptions): Promise<RevealMnemonicResult>

interface RevealMnemonicOptions {
  strings?: Partial<RecoveryPhraseStrings>;
}

interface RevealMnemonicResult {
  status: 'shown' | 'absent';
  revealed: boolean;
}
```

The words are never returned. In the default iframe mode the vault renders the
screen over your page and this resolves once the user closes it, so nothing you
write can end up holding a seed. Prefer this over keeping the one-time
`mnemonic` from `authenticate()`, which would leave a plaintext seed in your
application's storage.

`status: 'absent'` means the account genuinely has no phrase — it predates
escrowed entropy — so offer no retry. `revealed` tells you whether the user
actually uncovered the words or closed the screen without looking.

```typescript theme={null}
const { status, revealed } = await sdk.auth.revealRecoveryPhrase();
if (status === 'absent') {
  // Nothing to show, and nothing a retry can do about it.
}
```

Pass `strings` to localize the screen; each field falls back to English.

```typescript theme={null}
await sdk.auth.revealRecoveryPhrase({
  strings: { title: '복구 문구', reveal: '탭하여 보기', done: '완료' },
});
```

Calling this while a screen is already open joins that one rather than opening
a second, so a double-click is harmless.

## sdk.vault

Vault resource for privacy operations.

### `vault.shield(params)`

Deposit tokens to private balance.

```typescript theme={null}
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. Not surfaced by the shield response, so usually undefined; query `vault.getFees()` for the schedule. */
  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.

```typescript theme={null}
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.prepareWithdrawal(params)`

Build and sign a withdrawal for your backend to submit. Nothing is submitted:
the withdrawal is sealed into a package only the Privacy Boost server can open,
and returned with the request id it will be stored under. Your backend posts
`package` to `POST /api/v1/server/withdrawals` with its server credentials
before `expiresAt`, and `GET /api/v1/server/requests/{requestId}` reports the
outcome. The notes it spends stay held on the device until the package expires.

```typescript theme={null}
async prepareWithdrawal(params: PrepareWithdrawalParams): Promise<PreparedWithdrawal>

interface PrepareWithdrawalParams {
  tokenAddress: Hex;
  amount: bigint;
  recipient: Address;
  signal?: AbortSignal;
}

interface PreparedWithdrawal {
  /** The id the withdrawal will have once your backend submits it. */
  requestId: string;
  /** Send this unchanged, as JSON, to POST /api/v1/server/withdrawals. */
  package: WithdrawalPackage;
  /** Unix seconds, by the server's clock, after which the package is refused. */
  expiresAt: number;
  /** Fee the withdrawal pays, in token wei. */
  fee: bigint;
}
```

### `vault.send(params)`

Send private transfer.

```typescript theme={null}
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.sendBatch(params)`

Send one private transfer that pays several recipients: one request, one fee,
one set of input notes.

The transfer's output count is `recipients.length` plus a change note, and the
server only proves specific `(inputs, outputs)` shapes, so a longer recipient
list limits how many input notes the transfer can spend. Past two recipients,
at most four input notes are provable. Requests that no enabled circuit can
serve throw `UNSUPPORTED_TRANSFER_SHAPE` before submission. See the
[transfers guide](https://docs.privacyboost.io/sdk/typescript/guides/transfers.md#paying-several-recipients-at-once).

```typescript theme={null}
async sendBatch(params: SendBatchParams): Promise<TransactionResult>

interface SendBatchParams {
  /** Recipients in output order. At least one; duplicates allowed. */
  recipients: SendBatchRecipient[];
  tokenAddress: Hex;
  signal?: AbortSignal;
}

interface SendBatchRecipient {
  recipient: PrivacyAddress;
  amount: bigint;
}
```

### `vault.prepareShield(params)`

Build a deposit payload **without submitting it** — for callers that relay the
transaction themselves (a gasless relayer, an EIP-7702 session key, or a plain
`eth_sendRawTransaction`). Returns the calldata to relay plus the note
commitment; nothing is sent on-chain and no wallet is used. After relaying, call
the top-level [`finalizeShield`](#finalizeshieldparams) with the mined receipt to
recover the on-chain request id. `recipient` shields to another privacy address;
omit it to shield to yourself.

```typescript theme={null}
async prepareShield(params: PrepareShieldParams): Promise<PreparedShield>

interface PrepareShieldParams {
  tokenAddress: Hex;
  amount: bigint;
  /** Recipient privacy address. Omit to shield to yourself. */
  recipient?: PrivacyAddress;
}

interface PreparedShield {
  /** ERC-20 approve(pool, amount). Omitted when allowance is managed out of band. */
  approve?: ShieldCall;
  /** WETH deposit() wrap. Present only when shielding native ETH. */
  wrap?: ShieldCall;
  /** The requestDeposit(...) call. */
  shield: ShieldCall;
  /** Note commitment to track; also appears on-chain inside the shield call. */
  commitment: string;
  finalize: { shieldContract: string; tokenId: number };
}

/** A single on-chain call to relay. `value` and `data` are 0x-hex. */
interface ShieldCall {
  to: string;
  value: string;
  data: string;
}
```

### Deposit cancellation

A shield escrows your tokens in the pool and holds them there until the sequencer
settles the request into the note tree. Almost always that happens within a
couple of blocks. When it doesn't, because of a commitment mismatch, a malformed
ciphertext, or a stalled sequencer, the tokens stay in escrow and the depositor
reclaims them by cancelling the request on-chain.

The server will tell you a shield *failed* —
`sdk.transactions.getShieldStatus(requestId)` returns `failed` for a commitment
mismatch or a malformed ciphertext — but it says nothing about the escrow behind
it: whether the pool still holds it, who may reclaim it, and when. A stalled
sequencer doesn't even produce that `failed` row. So use `getShieldStatus` to
notice something went wrong, and these two methods to find out what you can do
about it. They read the pool directly and tell you what it would do before you
ask anyone to sign.

> [!WARNING]
>
> Both methods need the local WASM instance, so they require `keyVault: { mode:
>   'local' }`. Under the browser default (`iframe`) they throw
> `UNSUPPORTED_OPERATION`.

`depositRequestId` is the `DepositRequested` event's indexed `topic1`, a
`uint256`. It's the same value `vault.shield(...)` and
[`finalizeShield`](#finalizeshieldparams) return as `ShieldResult.requestId`.
Pass it as a decimal string or a `0x`-hex string; the `depositRequestId` on the
result is always normalized to decimal.

Only the address that submitted the deposit can cancel it, and the refund goes to
that address. For a relayer-submitted shield that's the relayer, not the note
recipient, so a user whose deposit is genuinely theirs can still get
`NotDepositor` back.

The cancel delay is measured in **blocks** and read from the pool's
`cancelDelay()`. Read the deployed value instead of hardcoding a delay, using
`cancelDelay`, `cancellableAtBlock`, and `blocksRemaining` from the returned
status.

#### `vault.listShieldsByStatus(statuses?)`

Find a `depositRequestId` you never kept. Lists the connected wallet's own shield
requests in the given statuses, oldest first, scoped to the session — it cannot
enumerate anyone else's deposits.

```typescript theme={null}
async listShieldsByStatus(statuses?: ShieldRequestStatus[]): Promise<UnsettledShield[]>

type ShieldRequestStatus =
  | 'pending' | 'processing' | 'preconfirmed' | 'completed' | 'failed';

interface UnsettledShield {
  /** The on-chain deposit request id, decimal. */
  requestId: string;
  status: ShieldRequestStatus;
  /** The `requestDeposit` transaction, once the server has observed it. */
  txHash?: string;
  /** Block the `DepositRequested` event was emitted in. */
  blockNumber?: number;
  createdAt?: string;
  updatedAt?: string;
  /** Why the shield failed, when the server recorded a reason. */
  error?: string;
}
```

`statuses` defaults to `['pending']`, matching the server. Pass `['failed']` to
list the shields whose escrow may still be sitting in the pool — that is the
recovery entry point:

```typescript theme={null}
const stuck = await sdk.vault.listShieldsByStatus(['failed']);
for (const shield of stuck) {
  const status = await sdk.vault.getDepositCancellation(shield.requestId);
  if (status.cancellable) await sdk.vault.cancelDeposit(shield.requestId);
  else console.log(shield.requestId, status.reason);
}
```

`'failed'` is a public status the server folds several internal ones into, so it
also covers shields rejected as below-minimum or blocked. A stalled sequencer
produces no failed row at all — those stay `'pending'`, so a sweep that wants
every shield that has not settled should ask for both.

#### `vault.depositRequestIdsFromTransaction(txHash)`

The fallback when you kept the shield's transaction hash but not its
`requestId`. Reads the receipt and returns every `DepositRequested` id the pool
emitted, in log order.

```typescript theme={null}
async depositRequestIdsFromTransaction(txHash: string): Promise<string[]>
```

Returns more than one id when an aggregating relayer settled several callers'
deposits in the same transaction, and an empty array when the transaction
emitted no `DepositRequested` from the configured pool — the answer for a hash
that was never a shield, rather than an error, so you can sweep candidates.

#### `vault.getDepositCancellation(depositRequestId)`

Read the pool and report whether cancelling would succeed for the connected
wallet right now, without sending anything. The check costs three `eth_call`s plus
one `eth_blockNumber`, which the SDK issues itself against the configured
`rpcUrl` — your `WalletAdapter` needs no extra methods, it only signs. The call
rejects if that RPC is unreachable.

```typescript theme={null}
async getDepositCancellation(depositRequestId: string): Promise<DepositCancellation>

type DepositCancelState =
  | 'Cancellable'
  | 'NotFound'
  | 'NotDepositor'
  | 'AlreadyProcessed'
  | 'TooEarly'
  | 'GatewayOrigin';

interface DepositCancellation {
  /** The queried id, normalized to decimal. */
  depositRequestId: string;
  state: DepositCancelState;
  /** True exactly when `state` is `'Cancellable'`. */
  cancellable: boolean;
  /** Address that must sign the cancellation. Absent when no escrow exists. */
  depositor?: string;
  /** The address the status was evaluated against. */
  caller: string;
  tokenId: number;
  /** Escrow that would be refunded, decimal. `"0"` when no escrow exists. */
  totalAmount: string;
  requestBlock: number;
  /** The pool's `cancelDelay()`, in blocks. */
  cancelDelay: number;
  /** First block cancellation is allowed (`requestBlock + cancelDelay`). */
  cancellableAtBlock: number;
  /** Chain head the status was evaluated at. */
  currentBlock: number;
  /** Blocks left before `'TooEarly'` clears; `0` once the delay has elapsed. */
  blocksRemaining: number;
  /** Human-readable explanation of `state`, safe to surface directly. */
  reason: string;
}
```

`state` mirrors the reverts in the pool's `cancelDeposit`, reported
permanent-blocker first rather than in the pool's own check order. The pool
checks the depositor before anything else, and that check would mask the two
conditions no caller can clear.

| State | Meaning |
| - | - |
| `Cancellable` | Every precondition holds; the transaction should land. |
| `NotFound` | The pool holds no escrow under this id. It was never created, or it's already been cancelled or rescued. Settling does not clear the record, so a settled deposit reports `AlreadyProcessed` instead. |
| `AlreadyProcessed` | The sequencer already settled this deposit into the note tree, so the funds are in a note rather than in escrow. This blocks the rescue path too, so it's reported ahead of `GatewayOrigin`. |
| `GatewayOrigin` | A gateway-origin deposit. It carries a rescue commitment and has to be recovered with `rescueGatewayDeposit` by its rescue authority instead. |
| `NotDepositor` | Escrow exists but belongs to another address. |
| `TooEarly` | Escrow is reclaimable, but the cancel delay hasn't elapsed yet. The one rejecting state that resolves on its own. |

A gateway-origin deposit stores the gateway contract as its depositor, never the
wallet whose funds routed through it, so it reports `GatewayOrigin` for every
caller and at every point in the delay window. Waiting never makes it
cancellable.

#### `vault.cancelDeposit(depositRequestId)`

Cancel a stuck deposit and refund its full escrow to the depositor. Returns the
tx hash.

```typescript theme={null}
async cancelDeposit(depositRequestId: string): Promise<string>
```

The call preflights the same checks as `vault.getDepositCancellation` and rejects
locally, before anything is signed, when the pool would revert. The rejection
message is the status `reason`, so a stuck deposit explains itself instead of
burning gas on an opaque revert. If the adapter can't run the preflight, the
transaction is submitted anyway and the chain arbitrates.

```typescript theme={null}
const status = await sdk.vault.getDepositCancellation(result.requestId);
if (status.cancellable) {
  await sdk.vault.cancelDeposit(status.depositRequestId);
} else {
  console.log(status.reason);
}
```

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

```typescript theme={null}
async getBalance(tokenAddress: string): Promise<TokenBalance>
```

### `vault.getAllBalances()`

Get all token balances.

```typescript theme={null}
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.

```typescript theme={null}
async refreshBalance(tokenAddress: Hex): Promise<void>
```

### `vault.refreshBalances()`

Refresh all tracked balances from the server.

```typescript theme={null}
async refreshBalances(): Promise<void>
```

### `vault.getToken(address)`

Get token metadata for a single token.

```typescript theme={null}
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 display metadata for every token registered with the protocol. This method
does not include pool token IDs or Gateway capabilities; use
`getRegisteredTokens()` for executable route discovery.

```typescript theme={null}
async getTokens(): Promise<TokenMetadata[]>
```

### `vault.getRegisteredTokens()`

Get the raw registered-token catalog, including pool token IDs and Gateway
capabilities. Public — usable before login. Use this method to discover
executable ERC-4626 and swap routes.

```typescript theme={null}
async getRegisteredTokens(): Promise<RegisteredToken[]>

interface RegisteredToken {
  id: number;
  tokenType: number;
  tokenAddress: Hex;
  tokenSubId: string;
  symbol?: string;
  name?: string;
  priceUSD?: number;
  decimals?: number;
  minShieldAmount?: string;
  capabilities?: TokenCapability[];
}

interface TokenCapability {
  adapter: string;
  direction?: string;
  vault?: string;
  shareTokenId?: number;
  underlyingTokenId?: number;
  outputTokenPolicy?: 'any-registered-token' | 'allowlist';
  outputTokenIds?: number[];
}
```

### Earn (ERC-4626 vaults)

Move a shielded balance into an ERC-4626 yield vault and back through the
external call gateway. See the [Earn concept page](https://docs.privacyboost.io/sdk/concepts/earn.md) for the
lifecycle, trust model, and deployment availability.

Gateway and registered-token discovery are public. Vault listings and history
are public only when the deployment configures the optional Earn catalog; with
`EARN_VAULT_MODE=disabled`, those metadata endpoints are unavailable while
Gateway execution can remain enabled. The two write operations require an
authenticated session. Settlement is tracked with
`sdk.transactions.getUnshieldStatus`, which also requires a session.

#### `vault.earnDeposit(params)`

Deposit assets into a vault: spends a private asset note and credits a
vault-share note. `amount` is **net** — exactly what enters the vault call; the
Gateway fee replaces the regular unshield fee and is charged on top.

Track the unshield status's `gateway.creditStatus`: `completed` means private
credit succeeded, while `rescued` means escrow was paid to the rescue
destination. Both end the wait for private credit. The top-level `completed`
flag only confirms the original unshield epoch.

```typescript theme={null}
async earnDeposit(params: EarnParams): Promise<EarnResult>

interface EarnParams {
  /** ERC-4626 vault address (also the share token address). */
  vaultAddress: Hex;
  /** Net amount entering the vault call: assets to deposit, shares to redeem. */
  amount: bigint;
  /** Max slippage below the on-chain preview, in bps (default 100 = 1%). */
  maxSlippageBps?: number;
  onProgress?: OnProgress;
}

interface EarnResult {
  /** Server-side request ID; use with the unshield status endpoint. */
  requestId: string;
  /** Local placeholder hash used to track pending status. */
  txHash: Hex;
  /** "deposit" | "redeem". */
  action: string;
  vaultAddress: string;
  inputTokenId: number;
  outputTokenId: number;
  /** Net amount that enters the vault call. */
  amount: bigint;
  /** Gateway fee charged on the exit amount, in raw units. */
  fee: bigint;
  /** Client-side preview of the vault output. */
  expectedOutputAmount: bigint;
  /** Signed floor; a fill below this refunds the input via the fallback receipt. */
  minOutputAmount: bigint;
  expiryBlock: bigint;
}
```

#### `vault.earnRedeem(params)`

Withdraw from a vault: redeems share notes and credits an asset note. `amount`
is the share amount to redeem. Same `EarnParams` / `EarnResult` shape as
`earnDeposit`.

```typescript theme={null}
async earnRedeem(params: EarnParams): Promise<EarnResult>
```

#### `vault.listEarnVaults()`

List the earn vault catalog (APY, TVL, warnings, per-operation availability).
Public — usable before login when the deployment enables the optional Earn
catalog. This method is not required for `earnDeposit()` or `earnRedeem()`;
discover executable routes with `getRegisteredTokens()` when the catalog is
disabled.

```typescript theme={null}
async listEarnVaults(): Promise<EarnVaultsResponse>
```

#### `vault.getEarnVault(vaultAddress)`

One vault's catalog entry plus the fields only the detail route carries:
`owner`, `curator`, `guardian`, `feeRecipient`, `timelockSeconds`, `sharePrice`
and `sharePriceUsd`. The summary fields are flattened onto the same object.
Public — usable before login when the deployment enables the optional Earn
catalog.

```typescript theme={null}
async getEarnVault(vaultAddress: string): Promise<EarnVaultDetail>
```

Needs a vault host of at least `/v10/vault.html` under the iframe key vault; an
older host rejects it as an unknown op.

#### `vault.getGatewayConfig()`

Gateway discovery configuration (executor address, request constraints, rescue
delay, availability). Public. Returns `enabled: false` when the deployment has
no gateway. Use it to feature-gate earn.

```typescript theme={null}
async getGatewayConfig(): Promise<GatewayConfig>
```

#### `vault.getEarnVaultHistory(vaultAddress, metric, period?)`

One vault's cached TVL or net-APY history series (chart data). Public. APY
values are decimal ratios (`0.05` = 5%); TVL values are USD; points ascend by
timestamp. A `null` `points[].value` is an upstream gap — render it as such.
Check `metadata.state` before presenting the series as current.

```typescript theme={null}
async getEarnVaultHistory(
  vaultAddress: string,
  metric: EarnHistoryMetric,
  period?: EarnHistoryPeriod,
): Promise<EarnVaultHistory>

type EarnHistoryMetric = 'tvlUsd' | 'netApy';
/** Server default is '1w'. */
type EarnHistoryPeriod = '1w' | '1m' | '3m' | 'all';

interface EarnVaultHistoryPoint {
  /** Unix seconds. */
  timestamp: number;
  /** null marks an upstream gap the chart should not interpolate across. */
  value: number | null;
}

interface EarnVaultHistoryMetadata {
  /** Open set — treat unknown values as data of unknown freshness, not errors. */
  state: 'fresh' | 'stale' | 'synthetic' | 'unsupported' | (string & {});
  /** RFC 3339 timestamp of the underlying upstream fetch. */
  updatedAt?: string;
}

interface EarnVaultHistory {
  chainId: number;
  vaultAddress: string;
  protocol: string;
  protocolVersion: string;
  metric: EarnHistoryMetric | (string & {});
  period: EarnHistoryPeriod | (string & {});
  /** Point spacing ('hour' | 'day'; open set). */
  interval: string;
  /** 'usd' for tvlUsd, 'ratio' for netApy (open set). */
  unit: string;
  lookbackHours?: number | null;
  periodAverage?: number | null;
  points: EarnVaultHistoryPoint[];
  metadata: EarnVaultHistoryMetadata;
}
```

#### `vault.getEarnVaultCharts(vaultAddress, period?)`

Both chart series (TVL USD and net APY) for one vault over the same period,
fetched concurrently. Public. Rejects if either series fails; call
`getEarnVaultHistory` twice for partial results.

```typescript theme={null}
async getEarnVaultCharts(
  vaultAddress: string,
  period?: EarnHistoryPeriod,
): Promise<EarnVaultCharts>

interface EarnVaultCharts {
  tvlUsd: EarnVaultHistory;
  netApy: EarnVaultHistory;
}
```

### `parseAmount(amount, decimals)`

Parse a human-readable amount to a bigint. Exported as a standalone utility from the SDK package.

```typescript theme={null}
import { parseAmount } from '@sunnyside-io/privacy-boost';

parseAmount(amount: string, decimals: number): bigint
```

### `formatAmount(amount, decimals)`

Format a bigint amount as a human-readable string. Exported as a standalone utility from the SDK package.

```typescript theme={null}
import { formatAmount } from '@sunnyside-io/privacy-boost';

formatAmount(amount: bigint, decimals: number): string
```

***

## Stateless shield helpers

Top-level functions for building a deposit payload without a signed-in session —
for a backend that holds only a recipient's privacy address. No wallet, no
private keys. Imported from the package root.

### `buildShieldPayload(params)`

Build a recipient-targeted deposit payload from public material only. Resolve
`tokenId`, `shieldContractAddress`, and `teePublicKey` from the token catalog /
config. An ephemeral sender keypair is generated and discarded internally, and
the note is spendable only by `recipient`.

```typescript theme={null}
import { buildShieldPayload } from '@sunnyside-io/privacy-boost';

async function buildShieldPayload(params: BuildShieldPayloadParams): Promise<PreparedShield>

interface BuildShieldPayloadParams {
  tokenAddress: Hex;
  amount: bigint;
  /** Recipient privacy address (required). */
  recipient: PrivacyAddress;
  /** Resolved on-chain token id (from the token catalog). */
  tokenId: number;
  shieldContractAddress: Hex;
  /** Required only when shielding native ETH. */
  wethContractAddress?: Hex;
  teePublicKey: string;
  /** Per-token minimum in raw units (token catalog `minShieldAmount`); rejects below it. */
  minShieldAmount?: bigint;
  /** Emit the ERC-20 approve call. Defaults to `true`. */
  emitApprove?: boolean;
}
```

### `finalizeShield(params)`

Recover the on-chain shield request id from the mined receipt of a relayed
deposit (see [`vault.prepareShield`](#vaultprepareshieldparams)). Stateless — the
caller obtained the receipt from its own relay/RPC, so no signed-in session is
needed. Throws if the deposit reverted or the `DepositRequested` log is absent.

```typescript theme={null}
import { finalizeShield } from '@sunnyside-io/privacy-boost';

async function finalizeShield(params: FinalizeShieldParams): Promise<ShieldResult>

interface FinalizeShieldParams {
  /** Mined transaction receipt (viem/ethers shape). */
  receipt: unknown;
  /** Shield pool contract — the DepositRequested emitter (from `PreparedShield.finalize`). */
  shieldContract: Hex;
  /** Commitment from the `PreparedShield` being settled. */
  commitment: Hex;
}
```

## sdk.transactions

Transactions resource.

### `transactions.fetchHistory(params?)`

Get transaction history.

```typescript theme={null}
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',
}
```

***

## sdk.campaigns

Campaign mission progress for the authenticated user.

Every method here reports on the session's own user. These routes accept no user
identifier — the server derives the user from the JWT — so there is no way to ask
this resource about somebody else.

### `campaigns.getStartaleProgress(window?)`

Get lifetime Startale mission progress, and the user's standing in a campaign
window when you pass one. Requires the full auth tier, which the vault reaches
after `auth.authenticate()` completes.

```typescript theme={null}
async getStartaleProgress(window?: CampaignWindow): Promise<StartaleCampaignProgress>

interface StartaleCampaignProgress {
  /** Whether cumulative completed shield deposits reach $10. */
  hasDepositedAtLeast10Usd: boolean;
  /** Whether the user has completed at least one private transfer. */
  hasMadeTransfer: boolean;
  /** Registry token ID the deposit mission is scoped to, if the server scopes it. */
  campaignTokenId?: number;
  /** The user's standing in `window`. Present exactly when you passed one. */
  campaign?: CampaignQualification;
}

interface CampaignWindow {
  /** Registry token ID of the campaign token. */
  tokenId: number;
  /** Start of the window, inclusive: a Date or an RFC 3339 timestamp. */
  from: Date | string;
  /** End of the window, exclusive. At most 31 days after `from`. */
  to: Date | string;
  /** Whole tokens as a decimal string, such as "10" or "2.5". Defaults to "10". */
  shieldThresholdTokens?: string;
  /** Days in a row the balance must stay at or above the threshold, 1 to 365. */
  holdDays?: number;
}

interface CampaignQualification {
  tokenId: number;
  /** The window the server applied, as RFC 3339 UTC timestamps. */
  from: string;
  to: string;
  /** The threshold the server applied, in whole tokens. */
  shieldThresholdTokens: number;
  /** Present only when the window set `holdDays`. */
  holdDays?: number;
  hasShielded: boolean;
  hasTransferred: boolean;
  /** Present only when the window set `holdDays`. */
  hasHeld?: boolean;
  /** When the hold still under way began. Present only while one is. */
  holdingSince?: string;
  /** Whether every mission above is met. */
  qualified: boolean;
}
```

`hasDepositedAtLeast10Usd` is priced at query time against the server's current
indexed token prices, so it is not monotonic: a deposit worth \$10.50 in a
volatile token can report `true` today and `false` after a price drop. If you
award something on it, record the first `true` and never downgrade.

`campaignTokenId` tells you what that total covers. When the server is configured
with a campaign token, only deposits of that token count, and this reports the
registry token ID they were counted under. When it is absent, the server has no
campaign token configured and values every token the user shielded, summed, so
two sub-threshold deposits in different tokens can complete the mission.

Read it rather than hardcoding a token if your UI names the one to deposit, since
the server decides what it judged the user against and an operator can change it
without a client release. It is the same registry token ID `buildShieldPayload`
and `portal.sweep` take, so resolve it to an address or symbol through the token
catalog the way you resolve those.

`hasMadeTransfer` counts private transfers with a positive amount to a non-self
recipient. Consolidations, unshields, self/change outputs, and failed or reorged
requests do not count. It stays token-agnostic even when the deposit mission is
scoped.

The call rejects rather than defaulting a field to `false`, so a truncated
response cannot read as "mission incomplete". A `campaignTokenId` that is present
but not a valid registry ID is rejected for the same reason: dropping it would
report a single-token total as an all-token one. The server answers `503` when a
shield token price is unavailable, or when a configured campaign token resolves
to no registered price; treat that as unknown, not as "not eligible".

#### Campaign windows

Pass a window to check one campaign's missions for the user:

```typescript theme={null}
const progress = await sdk.campaigns.getStartaleProgress({
  tokenId: 7,
  from: new Date('2026-11-01T00:00:00Z'),
  to: new Date('2026-12-01T00:00:00Z'),
  holdDays: 7,
});
const qualified = progress.campaign?.qualified ?? false;
```

`hasShielded` is true when the user's completed shields of `tokenId` inside
`[from, to)` add up to the threshold. A shield counts at the time of the block
that completed it, so one still pending doesn't count yet. `hasTransferred` is
true when they completed a private transfer with a positive amount to another
user in the window. As with `hasMadeTransfer`, any token counts.

With `holdDays`, `hasHeld` is true when the user's confirmed private balance of
`tokenId` then stayed at or above the threshold for that many days in a row. The
hold can start no earlier than their first shield in the window and must start
before `to`, but it can end after `to`. Tokens received from other users count
toward the balance, and spending that leaves at least the threshold doesn't
break the hold. A hold that is still running reads `false` until its days are
up, so call again later rather than treating that `false` as final.

While a hold is running, `holdingSince` is when the current run began, as an
RFC 3339 UTC timestamp. It completes `holdDays` × 24 hours later if the balance
stays at or above the threshold, so you can show how many days are held and how
many are left; `hasHeld` turns `true` at that point and `holdingSince` goes
away. A dip below the threshold and back moves it forward to the restart. It is
absent while the balance is below the threshold, and once a hold broke at or
after `to`, when no new run can start.

`qualified` is true when `hasShielded` and `hasTransferred` are, and `hasHeld`
too when you set `holdDays`. Read the individual missions if your campaign
rewards them separately.

The SDK checks the window before sending it and rejects bad input with
`INVALID_INPUT`: a `tokenId` outside 1 to 65535, a date that doesn't exist (such
as November 31) or falls outside the years 1 to 9999, a `to` that isn't after
`from`, a window over 31 days, a threshold that isn't a positive decimal string,
or a `holdDays` outside 1 to 365. The server answers `400` for a threshold with
more fractional digits than the token has decimals, and for a `tokenId` it has
no price for, which usually means it isn't a pool token. A server too old to
know campaign windows ignores them and returns no `campaign`, and the call
rejects with `INVALID_INPUT` instead of reporting the user as not qualified.

The server answers `503` when it can't look up the user's account or read the
token's decimals, or hasn't recorded the time of a block the answer depends on
yet. Treat that as unknown and try again later.

Progress is scoped to the chain the server is deployed for. In a
[multi-chain](https://docs.privacyboost.io/sdk/concepts/multi-chain) setup, read it from the `ChainClient`
for the chain you care about rather than from the root SDK.

***

## sdk.portal

Hidden-recipient [portal deposit addresses](https://docs.privacyboost.io/sdk/concepts/portal-deposits.md).

### `portal.create(opts?)`

Derive a portal address `E`, delegate it, register the owner binding, and publish
the discovery entry — in one call.

```typescript theme={null}
async create(opts?: CreatePortalOptions): Promise<Portal>
```

### `portal.listPage(options?)`

Fetch one bounded page without accumulating earlier pages in memory. `limit`
defaults to `100` and must be between `1` and `100`. Pass `nextCursor` back as
`cursor` unchanged; an absent `nextCursor` marks the final page.

```typescript theme={null}
async listPage(options?: PortalPageOptions): Promise<PortalInfoPage>
```

### `portal.depositsPage(address, options?)`

Fetch one bounded deposit page. Cursor and limit semantics match
`portal.listPage`.

```typescript theme={null}
async depositsPage(
  address: string,
  options?: PortalPageOptions,
): Promise<PortalDepositPage>
```

### `portal.status(address)`

```typescript theme={null}
async status(address: string): Promise<PortalStatus>
```

### `portal.sweep(address, tokenId)`

Self-service sweep backstop; a keeper normally handles this. Returns the tx
hash.

```typescript theme={null}
async sweep(address: string, tokenId: number): Promise<string>
```

### `portal.reclaim(depositId)`

Reclaim an un-credited deposit after the cancel delay; funds return to `E`.
Returns the tx hash.

```typescript theme={null}
async reclaim(depositId: string): Promise<string>
```

### `portal.withdraw(params)`

Build a signed raw EIP-1559 tx that withdraws funds resting at `E` (escape
hatch). Broadcast it yourself.

```typescript theme={null}
async withdraw(params: WithdrawPortalParams): Promise<string>
```

### `portal.sweepRequirements()`

Read the current ETH/WETH sweep requirements without unlocking or signing.
Requires a connected wallet and a valid read session; a locked but readable
session works, while a signed-out or expired session must sign in first.

```typescript theme={null}
async sweepRequirements(): Promise<PortalSweepRequirements>

interface PortalSweepRequirements {
  chainId: number;
  tokenId: number;
  tokenAddress: string;
  decimals: number;
  minSweepAmount: bigint;
  nativeGasReserve: bigint;
}
```

`tokenAddress` identifies the delegate's registered wrapped-native token.
Amounts are in base units: `minSweepAmount` is the on-chain token threshold,
read fresh on every call; `nativeGasReserve` is the supported delegate version's
0.001 ETH reserve in wei, a protocol constant rather than an on-chain getter.
Deployment metadata is cached for five minutes within the SDK instance.

Even a zero threshold requires a positive sweep. For an empty portal, the minimum
ETH deposit is `nativeGasReserve + max(minSweepAmount, 1n)`; existing funds can
reduce the additional deposit needed. See the
[receiving deposits guide](https://docs.privacyboost.io/sdk/typescript/guides/portal-deposits.md#receiving-deposits)
for a calculation example and refresh guidance.

### `portal.delegateAddress()`

The portal delegate address from `/info`, or `undefined` if unsupported.

```typescript theme={null}
async delegateAddress(): Promise<string | undefined>
```

See the [portal guide](https://docs.privacyboost.io/sdk/typescript/guides/portal-deposits.md) for the `Portal`,
`PortalInfo`, `PortalInfoPage`, `PortalStatus`, `PortalDeposit`,
`PortalDepositPage`, `PortalDepositState`, `PortalPageOptions`,
`CreatePortalOptions`, and `WithdrawPortalParams` types.

***

## Gift Methods (sdk.wasm)

[Claimable transfers](https://docs.privacyboost.io/sdk/concepts/claimable-transfers.md) are available on the
underlying WASM SDK via `sdk.wasm`. Each fund/claim/refund returns a
`TransferResult` (extended with optional `giftRecord` and `claimLink`).

| Method | Description |
| - | - |
| `giftFundToWallet(params)` | Fund a gift bound to a wallet (no privacy address) |
| `giftFund(params)` | Fund a gift bound to a wallet, sealed to a privacy address |
| `giftClaim(params)` | Claim a pending gift by `index` |
| `giftClaimByCGift(params)` | Claim by stable commitment `cGift` |
| `giftClaimFromLink(params)` | Claim directly from a `pbgift:v1:...` link |
| `giftRefundByRecord(index)` | Refund an unclaimed gift via a saved record |
| `giftRefund(params)` | Refund by supplying every gift field manually |
| `getPendingGifts()` | List claimable gifts addressed to the wallet |
| `getGiftRecords()` | Local records of gifts you funded (for refunds) |
| `decodeGiftLink(link)` | Decode + decrypt a claim link offline into a preview |

`giftFundSecretBearer(params)` also exists. It is a bearer instrument, selected
only by that explicit method. See the [concept
page](https://docs.privacyboost.io/sdk/concepts/claimable-transfers.md). Full parameter shapes and the
`GiftRecord` / `PendingGift` / `GiftLinkPreview` types are in the [gift
guide](https://docs.privacyboost.io/sdk/typescript/guides/claimable-transfers.md).

***

## Utility Functions

### `isValidPrivacyAddress(address)`

Check if address is valid privacy address.

```typescript theme={null}
function isValidPrivacyAddress(address: string): boolean
```

### `validatePrivacyAddress(address)`

Validate a privacy address.

```typescript theme={null}
function validatePrivacyAddress(address: string): { valid: boolean; message: string }
```

### `encodePrivacyAddress(mpk, viewingPublicKey)`

Encode MPK and viewing public key to privacy address.

```typescript theme={null}
function encodePrivacyAddress(mpk: bigint, viewingPublicKey: Point): PrivacyAddress
```

### `decodePrivacyAddress(address)`

Decode privacy address to components.

```typescript theme={null}
function decodePrivacyAddress(address: PrivacyAddress): {
  mpk: bigint;
  viewingPublicKey: Point;
}
```

### `extractMpkFromPrivacyAddress(address)`

Extract MPK from privacy address.

```typescript theme={null}
function extractMpkFromPrivacyAddress(address: PrivacyAddress): Hex
```

### `isEvmAddress(address)`

Check if valid EVM address.

```typescript theme={null}
function isEvmAddress(address: string): boolean
```

### `isNativeEth(address)`

Check if address represents native ETH.

```typescript theme={null}
function isNativeEth(address: Hex): boolean
```

***

## Types

### `KeySource`

Key derivation source, passed to `authenticate()`.

```typescript theme={null}
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`

```typescript theme={null}
type Hex = `0x${string}`
```

### `PrivacyAddress`

```typescript theme={null}
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`

```typescript theme={null}
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`

```typescript theme={null}
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
  compliance = 'compliance', // Awaiting compliance check
}

enum UnshieldStep {
  preparing = 'preparing',     // Fetching notes and proofs
  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.

```typescript theme={null}
type GatewayAddress = `0x${string}`;
type GatewaySelector = `0x${string}`; // Runtime validation requires exactly 4 bytes.

interface FeeRates {
  /** Flat transfer fee in token wei; active when transferFeeMode is "flat". */
  transferFeeFlat: string;
  /** Unshield BPS fee; active when unshieldFeeMode is "bps". */
  unshieldFeeBps: number;
  /** Whether the user pays the fee or the application sponsors it. */
  feeModel?: 'user_pays' | 'app_pays';
  feeSchemaVersion?: number;
  requiresFeeSchemaVersion?: number;
  transferRequiresFeeSchemaVersion?: number;
  unshieldRequiresFeeSchemaVersion?: number;
  transferFeeMode?: 'flat' | 'bps';
  transferFeeBps?: number;
  unshieldFeeMode?: 'flat' | 'bps';
  unshieldFeeFlat?: string;
  gatewayAddress?: GatewayAddress;
  gatewaySelector?: GatewaySelector;
  gatewayFeeMode?: 'flat' | 'bps';
  gatewayFeeFlat?: string;
  gatewayFeeRate?: number;
  gatewayFeeRateDenominator?: number;
  gatewayFeeBase?: 'flat' | 'unshield_amount' | 'zero';
  gatewayRequiresFeeSchemaVersion?: number;
}
```

Schema-v1 responses omit the optional fields and mean transfer=`flat`,
unshield=`bps`. In schema v2, each operation selects its own mode. BPS uses
`floor(base * bps / 10000)`: the unshield base is the public exit amount, while
the transfer base is only volume sent to external recipients. A pure
self-transfer therefore has zero transfer BPS fee. Pass `externalVolume` (or
`isSelfTransfer`) when the transfer amount is not entirely external.

Use `vault.getGatewayFees(tokenAddress, gatewayAddress, gatewaySelector?)` for
Earn, Swap, or another Gateway operation. An exact selector policy overrides
the Gateway-wide default. The response echoes the requested selector even when
the default policy supplied the rate, allowing the SDK to bind the quote to the
external call.

### Fee math

The fee functions are plain exports, so code that cannot use a React hook —
max-amount clamping before a send, CLI tooling, tests — derives the same number
the UI shows. `useFees()` is a reactive wrapper around them.

```typescript theme={null}
import {
  calculateFee,
  calculateGatewayFee,
  formatFeeRate,
  formatGatewayFeeRate,
  validateFeeRates,
  validateFeeRatesFor,
  validateGatewayFeeRates,
  SUPPORTED_FEE_SCHEMA_VERSION,
} from '@sunnyside-io/privacy-boost';

const rates = await sdk.vault.getFees(tokenAddress);
const gatewayRates = await sdk.vault.getGatewayFees(
  tokenAddress,
  gatewayAddress,
  gatewaySelector,
);

// Fee for an amount, under whichever mode the rates select for the operation.
const fee = calculateFee(rates, amount, 'transfer', { externalVolume });
const maxSendable = balance - calculateFee(rates, balance, 'unshield');

// Human-readable rate: "0.50%" for BPS, "1000 wei" for flat.
formatFeeRate(rates, 'unshield');
calculateGatewayFee(gatewayRates, amount, gatewayAddress, gatewaySelector);
formatGatewayFeeRate(gatewayRates, gatewayAddress, gatewaySelector);
```

| Export | Purpose |
| - | - |
| `calculateFee(rates, amount, type, options?)` | Fee in token wei. `type` is `'transfer'` or `'unshield'`; `options` carries `externalVolume` / `isSelfTransfer` for transfer BPS. |
| `formatFeeRate(rates, type)` | The active rate as `"2.50%"` or `"1000 wei"`. |
| `validateFeeRates(rates)` | Screens a whole response. Use at a transport boundary, where both operations have to work. |
| `validateFeeRatesFor(rates, type)` | Screens only the half one operation uses, so a transfer still prices when the unshield half needs a newer schema. |
| `calculateGatewayFee(rates, amount, gateway, selector?)` | Gateway fee in token wei, after binding the quote to the expected address and selector. |
| `formatGatewayFeeRate(rates, gateway, selector?)` | The active Gateway rate after the same binding checks. |
| `validateGatewayFeeRates(rates, gateway, selector?)` | Validates the Gateway fee contract and rejects a quote for another address or selector. |
| `SUPPORTED_FEE_SCHEMA_VERSION` | Highest fee schema this SDK interprets. Bounds what a payload may *require*, not the `feeSchemaVersion` a server reports. |

`calculateFee` and `formatFeeRate` validate the half of the payload they read
before using it, so they never derive a fee from a rate the SDK would reject.
Both throw `FEE_SCHEMA_UPGRADE_REQUIRED` when the operation needs a newer
schema than this SDK supports, and `INVALID_INPUT` for an unknown fee mode or a
malformed or out-of-range rate. `sdk.vault.getFees()` already screens its
response, so an explicit `validateFeeRates` call is only needed for rates that
arrive some other way.

The React hook's `calculateFee` returns `bigint | null`, yielding `null` while
rates are unavailable (first fetch in flight, or the last one failed) so an
unknown fee never looks like a zero fee.

When `feeModel` is `'app_pays'`, the fee is settled out of band by the application — users see the gross amount. Shield fee schedules are available from `vault.getFees()`; the shield response does not currently surface the actual charged fee.

### `ComplianceStatus`

```typescript theme={null}
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](https://docs.privacyboost.io/sdk/concepts/error-handling.md). |

***

## Constants

```typescript theme={null}
const NATIVE_ETH_ADDRESS = '0x0000000000000000000000000000000000000000';
const PRIVACY_ADDRESS_LENGTH = 194;
const PRIVACY_ADDRESS_HEX_LENGTH = 192;
const SUPPORTED_FEE_SCHEMA_VERSION = 2;
```


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