Skip to main content
The UTXO API is the lower-level path createCloak is built on, for integrations that manage notes, proofs and submission themselves. This page is written against @cloak.dev/sdk 0.2.20, mainnet only. Test with small amounts on mainnet (the minimum SOL deposit is 0.01 SOL).

Core APIs

  • transact(params, options)
  • transfer(...)
  • partialWithdraw(...)
  • fullWithdraw(...)
  • swapUtxo(...)
  • swapWithChange(...)
All are exported from @cloak.dev/sdk.

End-to-end script

This script runs the Quickstart flow with the free functions, for SOL: it shields 0.01 SOL, sends it privately, and withdraws it to your wallet. Cloak derives every key from one 32-byte seed. The script generates it on the first run and stores it in cloak-seed.hex; treat that file like a private key. If you lose the seed you lose access to your shielded notes, which is why the script never uses a random throwaway key. From the seed come ownerUtxoKeypair, which owns your notes and is required on every spend, and nk, a view-only key that can find and read your notes but never spend them.
Withdrawing 0.01 SOL this way returns about 0.00497 SOL: the SOL pool’s withdrawal fee is 5_000_000 lamports plus 0.3% of the amount.

Transaction semantics

TransactParams also takes an optional recipient: Address, the public destination of a withdrawal. externalAmount rules:
  • > 0: public deposit into the pool
  • < 0: public withdrawal from the pool
  • 0: fully shielded transfer
Every transaction is 2-in / 2-out, and every note in one transaction belongs to the same pool (NATIVE_SOL_MINT is the SOL pool). Under the hood, the SDK builds a proof plus 264-byte public inputs and submits the resulting on-chain transaction.

Fees

  • SOL withdraw/swap:
    • gross = abs(externalAmount)
    • fee = 5_000_000 + floor(gross * 3 / 1000)
    • net = gross - fee
  • SPL (USDC/USDT) withdraw: fee = 450_000 + floor(gross * 3 / 1000) in token base units, i.e. 0.45 token fixed plus 0.3%, charged in the withdrawn token
  • BRS withdraw: fee = 2_300_000 + floor(gross * 3 / 1000), i.e. 2.3 BRS fixed plus 0.3%
  • Deposits and shielded transfers have no protocol fee, but every deposit must meet the on-chain minimum: 10_000_000 lamports (0.01 SOL) for the SOL pool, and 1_000_000 base units (1.00 token) for the 6-decimal USDC/USDT pools. Anything below the minimum is rejected by the program with DepositTooSmall. transact checks the SOL minimum before it proves (it throws Deposit amount too small), but it does not check the SPL one, so an under-minimum USDC or USDT deposit fails at submission. Compare against the exported MIN_DEPOSIT_SPL_BASE_UNITS yourself first.
The fee belongs to the on-chain program, read from each pool’s PoolConfig. The SDK helpers below only estimate it for the SOL pool:

Keys

Every spend flow (transfer, partialWithdraw, fullWithdraw, swapUtxo, swapWithChange) requires two pieces of key material, in the types (SpendOptions) and at runtime:
  • ownerUtxoKeypair: the wallet’s long-lived UTXO keypair. It owns every change, merge and refund note the flow creates.
  • the wallet’s viewing base nk, passed as chainNoteViewingKeyNk. It is view-only: it can find and read notes, never spend them.
Pass both on deposits too. Derive them from a seed you generate once and store like a private key:
Do not use generateUtxoKeypair() for anything that holds real funds. A random keypair that you lose takes its notes with it.

Every result carries notes you should persist

transact, transfer, partialWithdraw, swapUtxo and swapWithChange all resolve to a result whose outputUtxos hold your money: the note a deposit created, and the change note left over by a spend. fullWithdraw leaves nothing shielded, so its outputs are padding. The notes the SDK builds for you are recoverable. A deposit made with createRecoverableDepositUtxo and every change, merge and refund note a spend flow creates derive their blinding from nk and a salt that is published inside the encrypted chain note. A scan holding nk plus the owner’s public key finds them again (recoverNotesFromIndex, scanTransactions). One gap: a transfer puts its change at output 1, and the chain note describes only output 0, so a scan cannot learn that change amount by itself; the blinding is still derivable, so the note is spendable once you supply the amount. Persisting result.outputUtxos is still the fast path, because it spares you a scan and gives you the leaf index at once.
Recovery covers only notes whose blinding is derivable. A note built with createUtxo has a random blinding that is written nowhere on chain, so if you drop it, it is unspendable by anyone, permanently. That includes change from clients that predate recoverable change. The same goes for a note owned by a random generateUtxoKeypair() key you did not keep. transact refuses to build a change output that is not derivable from the wallet’s nk (it throws and points you to createRecoverableChangeUtxo), but a deposit note you build yourself is your responsibility: use createRecoverableDepositUtxo.
serializeUtxo and deserializeUtxo are the persistence primitives. Every sample on this page calls the same helper rather than repeating it:
Both filters matter. transact pads its outputs to a fixed count with zero-amount notes, and transfer builds the recipient’s output from the recipient’s public key alone, so that note comes back with privateKey set to 0n and is not yours to hold. Where those bytes should live, how to reload them, and why UtxoWallet.serialize() drops commitment so that verifyUtxos then reports those notes as skipped: where your notes live between sessions.

Withdrawing three or more notes consolidates first

fullWithdraw is a thin wrapper: it sums your inputs and calls partialWithdraw for the whole amount. partialWithdraw can spend only two notes at a time, because the circuit takes two inputs and two outputs. So when either call receives three or more notes, it first merges the two smallest on chain, repeatedly, until two are left, and only then withdraws. Each merge round is a real shield-to-shield transaction. It nullifies the two notes it consumed and creates one merged note owned by ownerUtxoKeypair, with a blinding derived from nk and a fresh salt that the round publishes in its chain note. The merged note therefore exists on chain even if the call never returns it.
If a later merge round or the final withdrawal throws (stale-root retries exhausted, a 5xx on submission, a closed tab, a rejected wallet approval), the merges that already landed are not undone. Their inputs are spent, and the call rejected without returning a result, so there is nothing in hand to persist. The merged note is not lost, because it is derivable from your nk, but it is only visible again after a rescan. Do not retry with the original inputUtxos: the first merge round preflights their nullifiers and throws UtxoAlreadySpentError. This is not specific to fullWithdraw: partialWithdraw runs the same loop.
With one or two input notes there is no loop and no exposure. fullWithdraw then leaves nothing shielded. onProgress is the signal a caller gets that consolidation is happening at all. It fires once per merge round with Consolidating notes (n remaining)..., so a call that emits it has already committed to multi-round on-chain work:
The practical defence is to keep your note count low enough that withdrawals never take this path, and to consolidate on your own schedule rather than letting a withdrawal do it implicitly. A planned merge is an ordinary transact with externalAmount: 0n. Build the merged note with createRecoverableChangeUtxo and pass its salt as chainNoteSalt, so it is derivable from your keys, and persist what comes back before the next one:
Repeat until two notes remain, then withdraw. Every intermediate note is one you hold on disk, so a failure costs you a retry instead of a rescan.

Choosing a signer

Every example below comes in two tabs. Which one you need is decided by where your code runs, not by which call you are making.
  • Wallet adapter (browser): you hold no secret key. signerFromWalletAdapter wraps the adapter as a Kit TransactionSigner, which you pass as signer. A deposit is signed by that signer and posted straight to the chain. Alongside it you pass the adapter’s signMessage and the wallet’s address as walletPublicKey. That pair signs the viewing-key registration message, which is enforced by default, and it produces the authenticated sender that every request submitted on your behalf carries.
  • Keypair bytes (Node, server, CLI): depositorKeypair, built with signerFromSecretKey, covers all of it and never prompts.
Deposits are why this catches people late. A deposit is signed by signer and carries no authenticated sender, so the deposit below can succeed while the very next call, the private send, is the first one that needs signMessage and walletPublicKey. Leave either of them out on a transfer, a withdrawal or a swap and the call throws before it generates a proof, with a message that begins Cloak <flow> requires an authenticated sender.
Request authentication is the full contract for that signed sender: the exact options, the 300-second approval window, how many wallet prompts each flow costs, and explainRelayAuthRejection for turning a rejection into something a user can act on.

Deposit example (transact)

relayUrl is the exported CLOAK_PRODUCTION_RELAY_URL. The SDK reads no environment variable for it and never defaults it, and the published build accepts only an origin on its allowlist, so any other value throws locally before a request leaves the process. CLOAK_RELAY_URL is a convention the SDK’s own examples and scripts read themselves and pass in as relayUrl. See which endpoint the SDK talks to.

Withdraw and transfer helpers

These three are submitted on your behalf, so each request carries an authenticated sender. In the browser that is what walletPublicKey and signMessage are for, and no transaction is signed here. The key you pass becomes the request’s sender, so it must be the end user’s own wallet, never a session or service key. Both tabs also carry the two mandatory spend options, ownerUtxoKeypair and chainNoteViewingKeyNk.
partialWithdraw/fullWithdraw use negative externalAmount semantics. Each of these asks the wallet to sign once per submitted request. Network retries re-send the same signed request; a stale Merkle root forces a new proof, which is a new request and a new prompt. See how many wallet prompts to expect.

Swap example

Swaps are Jupiter-routed and the input is SOL only (the pool is wSOL-locked). The output goes to a public associated token account you name.
swapWithChange sends a TransactSwap payload (proof + 264-byte public inputs + swap params). A swap returns two things worth keeping. outputUtxos carries the change note, exactly as every other flow does. refund is separate: it is the authorization that reclaims the swap principal if the swap times out before it executes, and swapStatePda is the swap it belongs to. Persisting refund is always the fast path. Because the flow takes chainNoteViewingKeyNk, the pair discoverSwapRefunds / matchSwapRefundLeaf can rebuild the same authorization from your nk and the swap’s first input nullifier, so a lost copy is recoverable (refund.derivedFromNk is true). Swaps are the one flow that can prompt more than once: a swap re-proves on every stale-root retry, and each new proof is a new request needing a fresh approval. maxWalletApprovals caps that at 5 by default, wallet-adapter path only. A depositorKeypair never prompts. Details in request authentication.

Viewing-key registration requirements

  • Default behavior enforces viewing-key registration before protocol txs.
  • TransactOptions.enforceViewingKeyRegistration defaults to true.
  • Registration signs a one-time challenge (with signMessage for a wallet, or depositorKeypair) and submits nk to Cloak for compliance scanning. Nothing viewing-key related is written on chain.
  • Registration needs the wallet’s nk (chainNoteViewingKeyNk) and a way to sign. Without nk, or without signMessage, signer or depositorKeypair, the call throws a message that begins Viewing key registration is mandatory.
If the viewing key is missing, history and decrypt flows cannot resolve your transaction data.

Risk-oracle deposits

When deposits require Range/Switchboard validation, include:
  • riskOracleQueue
  • riskQuoteUrl (or getRiskQuoteInstruction)
The SDK can fetch risk quotes for you; you can also provide your own quote backend or a direct instruction callback. If the deposit account list is large, use v0 transactions with addressLookupTableAccounts. For SPL deposits, relaySupplementalAlt: true asks Cloak to extend its own lookup table so the deposit needs one wallet signature instead of two.

Operational notes

  • Every call hands its new notes back on result.outputUtxos and persists none of them. Write them out with serializeUtxo before you report success. Notes the SDK derives from your keys can be recovered by a scan if you lose them; notes built with createUtxo cannot. See every result carries notes you should persist.
  • partialWithdraw and fullWithdraw merge on chain before withdrawing whenever they are given three or more input notes, and a failure mid-merge leaves a merged note that no result hands back (recoverable by a scan). onProgress is the signal. See withdrawing three or more notes consolidates first.
  • Amounts use bigint in the UTXO API.
  • Proof retries are built in for stale roots (0x1001). Do not wrap transact, partialWithdraw or fullWithdraw in your own retry loop.
  • Pass result.merkleTree as cachedMerkleTree to the next call to skip re-fetching commitments.
  • useUniqueNullifiers defaults to true on mainnet RPC: every padding UTXO gets a random salt, so padding nullifiers never collide between runs or between concurrent depositors. Leave it unset. Setting it to false restores deterministic padding salts, which collide and fail with DoubleSpend (0x1020) once more than one deposit shares them.

Troubleshooting

  • RootNotFound / 0x1001: regenerate proof with fresh root (SDK retry usually handles this).
  • 0x1020 (double spend): the input UTXO was already spent, usually from another session or device. transact and swapUtxo pre-flight the input nullifiers and throw UtxoAlreadySpentError before any proof is generated. Catch it and call verifyUtxos() to reconcile your local notes with chain state.
  • <flow> requires options.ownerUtxoKeypair: every spend flow needs the wallet’s long-lived UTXO keypair. See Keys.
  • Viewing key registration is mandatory: the call has no nk, or no way to sign the registration challenge. Pass chainNoteViewingKeyNk and a signer.
  • Cloak <flow> requires an authenticated sender: a transfer, withdrawal or swap had no usable signer, or only half of one. In the browser pass signMessage and walletPublicKey; on a server pass depositorKeypair. Full diagnosis in Request authentication.

Next