Skip to main content

API Reference

Complete API reference for the Privacy Boost WASM SDK.

Generated Documentation

Full API documentation can be generated using cargo doc:

Initialization

init()

Initialize the WASM module. Must be called before creating SDK instances.
Returns: Promise<void>

PrivacyBoost

Main SDK class for JavaScript/TypeScript.

Constructor

Creates a new SDK instance. Parameters:
  • config - SDK configuration object
Example:

Properties

Connection & Authentication Methods

authenticate

Connect a wallet, derive privacy keys, and authenticate with the Privacy Boost backend in a single call. Parameters:
  • wallet - JavaScript wallet adapter object
  • keySource - Optional key derivation source. Pass null/undefined to default to walletDerived. Accepted values: { type: "walletDerived" }, { type: "mnemonic", phrase: "..." }, { type: "rawSeed", hex: "..." }
  • callback - Optional token provider function. Receives the authentication payload and returns a JWT. If omitted, the SDK calls the server directly. If it throws, authenticate rejects with AUTHENTICATION_FAILED, which is not retryable, unless the thrown error has retryable: true (rejects with a retryable NETWORK_ERROR) or code: 'RATE_LIMITED' with retryAfterMs (rejects with RATE_LIMITED). A fetch that got no response counts as retryable. Mark transient failures of your auth backend, such as a 5xx, so callers know to retry.
Returns: AuthResult with one of four statuses:
  • authenticated - Includes privacyAddress and mpk.
  • credentialRequired - Call submitCredential().
  • mnemonicGenerated - Show the mnemonic to the user, then call proceedAfterMnemonic().
  • recoveryRequired - Collect the recovery phrase and authenticate again with a mnemonic key source.
Throws:
  • Error if wallet is on wrong network
  • Error if signing fails
  • Error if appId not set in config
  • Error if backend unreachable

submitCredential

Submit a credential when authenticate() returns CredentialRequired. Returns: LoginResult with privacyAddress and mpk

logout

End session completely, clear all state.

clearSession

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

State Accessors

Balance Methods

getBalance

Get balance for a specific token. Parameters:
  • tokenAddress - ERC-20 token contract address
Returns: TokenBalance with shielded and wallet amounts

getAllBalances

Get all token balances.

Fee Methods

getFees

Returns the ordinary transfer and unshield fee quote for a token.

getGatewayFees

Returns the Gateway fee that replaces the ordinary unshield fee. Pass the first four calldata bytes as gatewaySelector to resolve a selector-specific override, or omit it for the Gateway-wide default.

Vault Operations

deposit

Deposit tokens into the shielded pool. Parameters:
  • tokenAddress - Token contract address
  • amount - Amount in wei (as string for BigInt support)
  • onProgress - Optional progress callback
Returns: ShieldResult with transaction hash

withdraw

Withdraw tokens from the shielded pool. Parameters:
  • tokenAddress - Token contract address
  • amount - Amount in wei (as string)
  • recipient - Recipient Ethereum address. recipientAddress is accepted as a deprecated alias.
  • onProgress - Optional progress callback
Returns: UnshieldResult with transaction hash

send

Send a private transfer. Parameters:
  • tokenAddress - Token contract address
  • amount - Amount in wei (as string)
  • recipient - Recipient’s 194-char privacy address. to is accepted as a deprecated alias.

sendBatch

Send one private transfer paying several recipients: one request, one fee, one set of input notes. Output order follows the array. Shape limits: the transfer’s output count is the recipient count plus a change note, and the server only proves specific (inputs, outputs) combinations, so a longer recipient list limits how many input notes can be spent — past two recipients, at most four. Requests no enabled circuit can serve fail with UNSUPPORTED_TRANSFER_SHAPE before submission. Returns: TransferResult with transaction hash

prepareShield

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, pass the mined receipt to finalizeShield to recover the on-chain request id. Parameters:
  • tokenAddress - Token contract address (zero address = native ETH)
  • amount - Amount in wei (as string)
  • recipient - (Optional) recipient privacy address. Omit to shield to yourself.
Returns: PreparedShield with the calls to relay and the note commitment

Transaction History

One page of the wallet’s transactions, newest first. Parameters:
  • params.txType - Filter by type: “deposit”, “withdraw”, “transfer”
  • params.tokenId - Registry token id, from getRegisteredTokens(). Not a token address: the history rows carry the circuit’s token id.
  • params.direction - “incoming” or “outgoing” relative to the wallet. Anything else is rejected here rather than sent on for the server to refuse.
  • params.limit - Page size
  • params.cursor - next from the previous page
  • params.collapseGateway - Fold each Gateway operation’s two rows into one

Token Tracking

Merkle Tree Statistics

Utilities

Address Lookup

Look up a user’s privacy address by MPK or Ethereum address.

Earn Catalog and Gateway Configuration

Public reads: no login, no key material. The vault catalog and history routes are served by the deployment’s earn service. A deployment without one does not serve those routes, and the SDK surfaces that as an error carrying the 404. getGatewayConfig() always answers and reports availability through its enabled flag.
getEarnVault returns one catalog row plus the fields only the detail route carries: owner, curator, guardian, feeRecipient, timelockSeconds, sharePrice and sharePriceUsd. APY values everywhere are fractions (0.05 is 5%), and a null point in a history series is an upstream gap, not a zero.

Earn Deposit and Redeem

Authenticated session required. Both take the same params object and return an EarnResult carrying the requestId to poll for settlement. amount is the net amount entering the vault call in raw units (assets for a deposit, shares for a redeem), and the Gateway fee is charged on top.

Private Treasury (contacts and labels)

Per-wallet bookkeeping the server stores encrypted. Both listings page with an opaque cursor: pass undefined for the first page and the returned nextCursor for the next. A row whose decryptionFailed is true is one the server could no longer open — show it as unreadable rather than dropping it.
updateContact is a JSON Merge Patch: an omitted key keeps the stored value and an explicit null clears it. nickname and emoji can only be replaced, so a null on either is rejected rather than quietly kept — the same rule the native bindings enforce with their StringPatch.Clear variant. upsertLabel is a PUT: it replaces the whole label, so a field you leave out is stored as absent rather than left at its old value.
The contact store is a deployment option. A server without one answers these with a 503 naming it, which is the feature being off rather than a failure.

Campaign Progress

Lifetime mission progress for the authenticated user and app. The deposit mission is priced at query time, so it is not monotonic: record the first true and never downgrade it. campaignTokenId is absent only when no campaign token is configured, in which case every shielded token counted toward the deposit total.

Audit Methods (Auditor Only)


Stateless shield helpers

Free functions on the WASM module 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.

buildShieldPayload

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. Parameters:
  • tokenAddress - Asset to shield (zero address = native ETH)
  • amount - Amount in wei (as string)
  • recipient - Recipient privacy address (required)
  • tokenId - Resolved on-chain token id (from the token catalog)
  • shieldContractAddress - Shield pool contract address
  • wethContractAddress - (Optional) required only when shielding native ETH
  • teePublicKey - TEE public key used to encrypt the deposit
  • minShieldAmount - (Optional) per-token minimum in wei; rejects below it
  • emitApprove - (Optional) emit the ERC-20 approve call. Defaults to true.
Returns: PreparedShield

finalizeShield

Recover the on-chain shield request id from the mined receipt of a relayed deposit. Stateless — the caller obtained the receipt from its own relay/RPC. Throws if the deposit reverted or the DepositRequested log is absent. Parameters:
  • receipt - Mined transaction receipt (viem/ethers shape: { transactionHash, status, logs: [{ address, topics, data }] })
  • shieldContract - Shield pool contract — the DepositRequested emitter (from PreparedShield.finalize)
  • commitment - Commitment from the PreparedShield being settled
Returns: ShieldResult with the on-chain requestId

Validation Functions


Types

WasmConfig

LoginResult

TokenBalance

FeeRates

Gateway fields are populated only by getGatewayFees.

ShieldResult

UnshieldResult

TransferResult

ShieldResult

Returned by finalizeShield.

Call

A single on-chain call to relay. value and data are 0x-hex.

PreparedShield

Returned by prepareShield and buildShieldPayload.

TransactionReceipt

The mined-receipt shape accepted by finalizeShield (viem/ethers compatible).

Transaction

SDKState

MerkleTreeStats


WalletAdapter Interface


Errors

The SDK throws standard JavaScript Error objects. Common error messages:

See Also


Gift Methods

Claimable transfers (“gifts”) let you send shielded funds to a wallet that has not joined Privacy Boost yet. These methods are called directly on the PrivacyBoost instance. See the Claimable Transfers guide for the full flow and the concept page for the trust model. Each fund/claim/refund call returns a TransferResult:

giftFundToWallet

Fund a gift bound to a wallet address. Use when the recipient has an EOA but has not joined Privacy Boost.

giftFund

Fund a gift when the recipient is already a Privacy Boost user. recipientPrivacyAddress is their 194-char privacy address; the ciphertext is sealed to their viewing key, while the gift itself binds to recipientWallet. The field is also accepted under its original name recipient, which the TypeScript SDK and the native bindings do not use because it reads too much like recipientWallet.

giftClaim

Claim a pending gift by its position in getPendingGifts().

giftClaimByCGift

Claim by stable commitment cGift — preferred when the pending list may shift as gifts settle.
Claim straight from a claim link, with no server lookup first.

giftRefundByRecord

Refund an unclaimed gift using the local record at the given position in getGiftRecords(). The argument is a positional u32, not an object. Only valid after refundAfterBlock has elapsed.

giftRefund

Refund by supplying every gift field manually — a fallback for when the local gift record is lost.

getPendingGifts

List the pending gifts addressed to the authenticated wallet.

getGiftRecords

The records of the gifts you funded in this session, newest first. These are what make an unclaimed gift refundable. They live in memory only, so they are gone after a reload; store each giftRecord yourself when the gift is funded. Throws NOT_AUTHENTICATED once the session can no longer read the account, and SESSION_EXPIRED when the read itself trips an idle or absolute auto-lock that ends the session. A lock that keeps the read session still answers. Merge what it returns into your stored records by cGift rather than replacing them with it.
Decode a claim link into a preview. Synchronous and offline — no network call, no await.
giftFundSecretBearer also exists. It is a bearer instrument (whoever holds the link can claim), selected only by that explicit method. See the concept page before considering it.

Gift Types


Portal

Portal deposit addresses give a user a reusable, public, exchange-style deposit address. WASM exposes the portal lifecycle as instance methods on sdk; the module also keeps two low-level namespace functions for custodial integrations. See the Portal Deposits guide and the concept page.

Namespace functions

generatePortalEoa

Generate a fresh portal EOA — the public deposit address and its private key — for a custodial integration that manages its own EOA key. The seed-derived sdk.createPortal(...) flow does not expose a private key.

encodePortalWithdraw

Encode PortalDelegate.withdraw(token, to, amount) calldata for a custodial integration that already controls its own portal EOA. For seed-derived portals, prefer sdk.withdrawPortal(...), which builds and signs the transaction in core.

Instance methods

createPortal

Derive portal E, gaslessly delegate and register it via the server relays, then publish the discovery entry. Omitting index uses the next free derivation index.

listPortalsPage

Fetch one bounded page without accumulating earlier pages. limit must be between 1 and 100. Pass nextCursor back unchanged; an absent nextCursor marks the final page.

listPortalDepositsPage

Fetch one bounded deposit page. Cursor and limit semantics match listPortalsPage.

getPortalStatus

Return the registry/on-chain status for one portal.

sweepPortal

Send requestPortalDeposit(portal, tokenId) from the connected wallet and return the transaction hash.

reclaimPortalDeposit

Send cancelPortalDeposit(depositId) from the connected wallet and return the transaction hash.

withdrawPortal

Build a signed EIP-1559 transaction that withdraws raw funds resting at the seed-derived portal E to to. Broadcast the returned raw transaction yourself.

portalDelegateAddress

The portal delegate address advertised by the server’s /info, or undefined when the server does not support portals.

publishPortalRegistry

Publish the discovery registry entry (E → blind) so the indexer can credit deposits. createPortal runs this as its final step; this method is for re-publishing an existing portal.

Portal Types


Deposit Cancellation

requestDeposit moves the depositor’s tokens into 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 — 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.

Instance methods

listShieldsByStatus

Find a depositRequestId you never kept. Lists the authenticated wallet’s own shield requests in the given public statuses (pending, processing, preconfirmed, completed, failed), oldest first. An empty list means the server’s default of pending. Pass failed to list the shields whose escrow may still be sitting in the pool, then feed each requestId to getDepositCancellation. Served by the server and scoped to the session, so it needs no ChainReaderDelegate and cannot enumerate anyone else’s deposits. 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. Returns: UnsettledShield per row: requestId, status, and the optional txHash, blockNumber, createdAt and error.

depositRequestIdsFromTransaction

The fallback when the app kept the shield’s transaction hash but not its request id. Reads the receipt and returns every DepositRequested id the pool emitted, in log order — more than one when an aggregating relayer settled several callers in the same transaction. Empty means the transaction emitted no DepositRequested from the configured pool, which is the answer for a hash that was never a shield rather than an error, so candidate hashes can be swept. Reads the chain, so it needs the same ChainReaderDelegate as getDepositCancellation.

getDepositCancellation

Read the pool and report whether cancelDeposit would succeed for the connected wallet right now, without sending anything. Costs three eth_calls plus one eth_blockNumber, so the wallet adapter has to implement the optional readContract(address, data) and getBlockNumber() methods. It rejects with a message naming the missing one if it can’t read. depositRequestId is the DepositRequested event’s indexed topic1, a uint256. It’s the same value sdk.shield(...) and finalizeShield 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. Returns: DepositCancellation with the escrowed amount, the block the delay expires at, and a reason you can show the user directly.

cancelDeposit

Send cancelDeposit(depositRequestId) from the connected wallet and return the transaction hash. The full escrowed amount goes back to the depositor. The call preflights through 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, which is the same trade-off the shield path makes for its allowance check.

Who can cancel, and when

Only the address that submitted requestDeposit 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.

Cancellation states

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

Deposit Cancellation Types