API Reference
Complete API reference for the Privacy Boost TypeScript SDK.Generated Documentation
Full API documentation can be generated using TypeDoc:- 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.
Example:
sdk.auth
Authentication resource.auth.authenticate(adapter, options?)
Connect a wallet, derive privacy keys, and authenticate with the server in a single call.
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:
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:
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.
auth.clearSession()
Clear JWT only, keep keys for quick re-auth.
auth.isConnected()
Check if wallet is connected.
auth.isAuthenticated()
Check if user is authenticated.
auth.getPrivacyAddress()
Get user’s privacy address.
auth.getMpk()
Get user’s master public key.
auth.revealRecoveryPhrase(options?)
Show the user their recovery phrase again, drawn by the key vault itself.
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.
strings to localize the screen; each field falls back to English.
sdk.vault
Vault resource for privacy operations.vault.shield(params)
Deposit tokens to private balance.
vault.unshield(params)
Withdraw tokens to public address.
vault.send(params)
Send private transfer.
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.
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 with the mined receipt to
recover the on-chain request id. recipient shields to another privacy address;
omit it to shield to yourself.
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.
depositRequestId is the DepositRequested event’s indexed topic1, a
uint256. It’s the same value vault.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.
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.
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:
'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.
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_calls 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.
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.
vault.cancelDeposit(depositRequestId)
Cancel a stuck deposit and refund its full escrow to the depositor. Returns the
tx hash.
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.
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.
vault.getAllBalances()
Get all token balances.
vault.refreshBalance(tokenAddress)
Refresh a single token balance from the server.
vault.refreshBalances()
Refresh all tracked balances from the server.
vault.getToken(address)
Get token metadata for a single token.
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.
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.
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 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; withEARN_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.
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.
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.
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.
/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.
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.
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.
parseAmount(amount, decimals)
Parse a human-readable amount to a bigint. Exported as a standalone utility from the SDK package.
formatAmount(amount, decimals)
Format a bigint amount as a human-readable string. Exported as a standalone utility from the SDK package.
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.
finalizeShield(params)
Recover the on-chain shield request id from the mined receipt of a relayed
deposit (see vault.prepareShield). 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.
sdk.transactions
Transactions resource.transactions.fetchHistory(params?)
Get transaction history.
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()
Get lifetime Startale mission progress. Requires the full auth tier, which the
vault reaches after auth.authenticate() completes.
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”.
Progress is scoped to the chain the server is deployed for. In a
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.portal.create(opts?)
Derive a portal address E, delegate it, register the owner binding, and publish
the discovery entry — in one call.
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.
portal.depositsPage(address, options?)
Fetch one bounded deposit page. Cursor and limit semantics match
portal.listPage.
portal.status(address)
portal.sweep(address, tokenId)
Self-service sweep backstop; a keeper normally handles this. Returns the tx
hash.
portal.reclaim(depositId)
Reclaim an un-credited deposit after the cancel delay; funds return to E.
Returns the tx hash.
portal.withdraw(params)
Build a signed raw EIP-1559 tx that withdraws funds resting at E (escape
hatch). Broadcast it yourself.
portal.delegateAddress()
The portal delegate address from /info, or undefined if unsupported.
Portal,
PortalInfo, PortalInfoPage, PortalStatus, PortalDeposit,
PortalDepositPage, PortalDepositState, PortalPageOptions,
CreatePortalOptions, and WithdrawPortalParams types.
Gift Methods (sdk.wasm)
Claimable transfers are available on the underlying WASM SDK viasdk.wasm. Each fund/claim/refund returns a
TransferResult (extended with optional giftRecord and claimLink).
giftFundSecretBearer(params) also exists. It is a bearer instrument, selected
only by that explicit method. See the concept
page. Full parameter shapes and the
GiftRecord / PendingGift / GiftLinkPreview types are in the gift
guide.
Utility Functions
isValidPrivacyAddress(address)
Check if address is valid privacy address.
validatePrivacyAddress(address)
Validate a privacy address.
encodePrivacyAddress(mpk, viewingPublicKey)
Encode MPK and viewing public key to privacy address.
decodePrivacyAddress(address)
Decode privacy address to components.
extractMpkFromPrivacyAddress(address)
Extract MPK from privacy address.
isEvmAddress(address)
Check if valid EVM address.
isNativeEth(address)
Check if address represents native ETH.
Types
KeySource
Key derivation source, passed to authenticate().
Hex
PrivacyAddress
0x prefix the string is 194 characters.
WalletAdapter
OnProgress
FeeRates
Fee schedule applied to vault operations.
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.
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.