API Reference
Complete API reference for the Privacy Boost WASM SDK.Generated Documentation
Full API documentation can be generated usingcargo doc:
Initialization
init()
Initialize the WASM module. Must be called before creating SDK instances.Promise<void>
PrivacyBoost
Main SDK class for JavaScript/TypeScript.Constructor
config- SDK configuration object
Properties
Connection & Authentication Methods
authenticate
wallet- JavaScript wallet adapter objectkeySource- Optional key derivation source. Passnull/undefinedto default towalletDerived. 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,authenticaterejects withAUTHENTICATION_FAILED, which is not retryable, unless the thrown error hasretryable: true(rejects with a retryableNETWORK_ERROR) orcode: 'RATE_LIMITED'withretryAfterMs(rejects withRATE_LIMITED). Afetchthat got no response counts as retryable. Mark transient failures of your auth backend, such as a 5xx, so callers know to retry.
AuthResult with one of four statuses:
authenticated- IncludesprivacyAddressandmpk.credentialRequired- CallsubmitCredential().mnemonicGenerated- Show the mnemonic to the user, then callproceedAfterMnemonic().recoveryRequired- Collect the recovery phrase and authenticate again with a mnemonic key source.
- Error if wallet is on wrong network
- Error if signing fails
- Error if
appIdnot set in config - Error if backend unreachable
submitCredential
authenticate() returns CredentialRequired.
Returns: LoginResult with privacyAddress and mpk
logout
clearSession
State Accessors
Balance Methods
getBalance
tokenAddress- ERC-20 token contract address
TokenBalance with shielded and wallet amounts
getAllBalances
Fee Methods
getFees
getGatewayFees
gatewaySelector to resolve a selector-specific
override, or omit it for the Gateway-wide default.
Vault Operations
deposit
tokenAddress- Token contract addressamount- Amount in wei (as string for BigInt support)onProgress- Optional progress callback
ShieldResult with transaction hash
withdraw
tokenAddress- Token contract addressamount- Amount in wei (as string)recipient- Recipient Ethereum address.recipientAddressis accepted as a deprecated alias.onProgress- Optional progress callback
UnshieldResult with transaction hash
send
tokenAddress- Token contract addressamount- Amount in wei (as string)recipient- Recipient’s 194-char privacy address.tois accepted as a deprecated alias.
sendBatch
(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
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.
PreparedShield with the calls to relay and the note commitment
Transaction History
params.txType- Filter by type: “deposit”, “withdraw”, “transfer”params.tokenId- Registry token id, fromgetRegisteredTokens(). 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 sizeparams.cursor-nextfrom the previous pageparams.collapseGateway- Fold each Gateway operation’s two rows into one
Token Tracking
Merkle Tree Statistics
Utilities
Address Lookup
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 anEarnResult 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: passundefined 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.
Campaign Progress
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
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 addresswethContractAddress- (Optional) required only when shielding native ETHteePublicKey- TEE public key used to encrypt the depositminShieldAmount- (Optional) per-token minimum in wei; rejects below itemitApprove- (Optional) emit the ERC-20 approve call. Defaults totrue.
PreparedShield
finalizeShield
DepositRequested log is absent.
Parameters:
receipt- Mined transaction receipt (viem/ethers shape:{ transactionHash, status, logs: [{ address, topics, data }] })shieldContract- Shield pool contract — theDepositRequestedemitter (fromPreparedShield.finalize)commitment- Commitment from thePreparedShieldbeing settled
ShieldResult with the on-chain requestId
Validation Functions
Types
WasmConfig
LoginResult
TokenBalance
FeeRates
getGatewayFees.
ShieldResult
UnshieldResult
TransferResult
ShieldResult
Returned byfinalizeShield.
Call
A single on-chain call to relay.value and data are 0x-hex.
PreparedShield
Returned byprepareShield and buildShieldPayload.
TransactionReceipt
The mined-receipt shape accepted byfinalizeShield (viem/ethers compatible).
Transaction
SDKState
MerkleTreeStats
WalletAdapter Interface
Errors
The SDK throws standard JavaScriptError objects. Common error messages:
See Also
- Getting Started - Quick start guide
- Wallet Integration - Wallet adapter setup
- Browser Setup - Browser configuration
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 thePrivacyBoost 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
giftFund
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
getPendingGifts().
giftClaimByCGift
cGift — preferred when the pending list may shift as
gifts settle.
giftClaimFromLink
giftRefundByRecord
getGiftRecords(). The argument is a positional u32, not an object. Only
valid after refundAfterBlock has elapsed.
giftRefund
getPendingGifts
getGiftRecords
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.
decodeGiftLink
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 onsdk; the
module also keeps two low-level namespace functions for custodial integrations.
See the Portal Deposits guide and the
concept page.
Namespace functions
generatePortalEoa
sdk.createPortal(...) flow does not expose a private key.
encodePortalWithdraw
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
E, gaslessly delegate and register it via the server relays, then
publish the discovery entry. Omitting index uses the next free derivation
index.
listPortalsPage
limit must be
between 1 and 100. Pass nextCursor back unchanged; an absent
nextCursor marks the final page.
listPortalDepositsPage
listPortalsPage.
getPortalStatus
sweepPortal
requestPortalDeposit(portal, tokenId) from the connected wallet and return
the transaction hash.
reclaimPortalDeposit
cancelPortalDeposit(depositId) from the connected wallet and return the
transaction hash.
withdrawPortal
E to to. Broadcast the returned raw transaction yourself.
portalDelegateAddress
/info, or undefined
when the server does not support portals.
publishPortalRegistry
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
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
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
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
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 submittedrequestDeposit 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.