Skip to main content
If you use createCloak, it takes the connected wallet as it is, createCloak({ wallet: useWallet() }), along with Wallet Standard wallets, EVM wallets, Privy and more, and needs none of the wiring on this page. See createCloak. This page is for the free functions.

Install

The SDK is built on @solana/kit. @solana/web3.js is an optional peer dependency, and you need it here: signerFromWalletAdapter hands the wallet a web3.js VersionedTransaction to sign. An app that does not use the wallet-adapter bridge (a Wallet Standard app using @solana/react, say) can skip it. See Solana Kit integration. Add wallet UI packages as needed:

The wallet signer, and what each option is for

signTransaction is not an option any more. The wallet signs transactions through signer, a Kit TransactionSigner, and signMessage signs the challenge that authenticates the user. Wrap the connected adapter once with signerFromWalletAdapter:
What each option does: A deposit needs signer plus a way to sign the viewing-key registration challenge, which is signMessage or the signer itself. Every send, withdrawal and swap authenticates the user, so it needs signMessage (or a message-capable or hardware signer) and walletPublicKey. When both signMessage and signer are present, signMessage is the one used. Full contract, including the approval window and prompt counts: Request authentication.

Wallets without signMessage

A hardware wallet (Ledger, Trezor) usually cannot sign arbitrary messages. Pass signer and leave signMessage out. The SDK then authenticates by asking the wallet to sign a deterministic 0-lamport self-transfer that carries the request digest (auth_mode: "transaction"). It is never sent to the network, but the wallet shows it as a 0 SOL transfer to yourself, so tell the user to expect it. signerFromWalletAdapter attaches message signing only when the adapter has signMessage, so the same wrapper covers both cases.

Bundlers and @solana/web3.js

By default signerFromWalletAdapter loads @solana/web3.js on demand, which works in Node but not through a bundler that cannot see a variable import specifier. In a bundled app pass the class in:

Where the user’s keys live

Every spend flow (transfer, partialWithdraw, fullWithdraw, swapUtxo, swapWithChange, sweepToWalletKey) requires two keys that belong to the user, not to the wallet adapter:
  • ownerUtxoKeypair, the long-lived Cloak keypair that owns the notes.
  • nk (passed as chainNoteViewingKeyNk), the view-only key that finds notes and decrypts chain notes. It can never spend.
Derive both from one 32-byte seed. Generate the seed once with generateMasterSeed().seed and store it the way you would store a private key: a random key that is lost loses the notes.
Derive them again at the start of each session, hold them in memory, and pass both on every call, deposits included. The wallet signs; the seed-derived keys own the money.

UTXO integration with wallet signing

A browser deposit builds a recoverable output note and passes the wallet fields in TransactOptions:
Check that the wallet can authenticate before you offer a send or withdraw action: either signMessage is present, or you are on the signer (transaction-based) path above. Finding out after a Groth16 proof has already been computed is a poor experience.

Full wallet-adapter SOL send flow (transact -> fullWithdraw)

Notes:
  • relayUrl comes from the exported CLOAK_PRODUCTION_RELAY_URL, not from an environment read. The SDK reads no environment variable for the submission endpoint, so exporting CLOAK_RELAY_URL does nothing on its own; if you want the value configurable, read your own build-time variable in your app and pass the result as relayUrl. Whatever you pass still has to be an origin on this build’s allowlist. On the default path, where enforceViewingKeyRegistration stays on, omitting relayUrl or passing "" throws Viewing key registration is mandatory: relayUrl is required. before anything reaches the network, deposits included. See which endpoint the SDK talks to.
  • Keep amount values as bigint end-to-end.
  • Use cachedMerkleTree from deposit for the immediate withdraw call.
  • Treat isRootNotFoundError as retryable with bounded backoff.
  • This example spends deposited.outputUtxos right after producing them, which keeps it short. A real wallet has to persist them instead: see where your notes live between sessions.
  • The withdrawal here spends two notes at most, so no consolidation round runs and the retry loop is safe to write this way. Handing fullWithdraw three or more notes is a different call with a different failure mode: see a withdrawal of three or more notes is not exempt.

Where your notes live between sessions

Every example above ends by feeding deposited.outputUtxos straight into the next call. A real wallet cannot do that. The user closes the tab, comes back tomorrow, and something has to know what they own. The SDK does not persist anything for you. transact, transfer, partialWithdraw, fullWithdraw and the swap helpers each return their new notes on result.outputUtxos and then forget them. That storage boundary is explicit, and closing it is your job. fullWithdraw leaves nothing shielded, so it hands back no change note when it spends one or two notes. That is the full extent of its exemption; the next section explains why. Every other call in that list produces a change note on every path. swapUtxo and swapWithChange additionally return refund and swapStatePda on UtxoSwapResult, which is what reclaims the principal if the swap times out before it settles; persist those two alongside the notes.
Write result.outputUtxos to durable storage before you report success to the user. A note is spendable only with its full secrets, (amount, owner pubkey, blinding, mint). The spend flows build change with createRecoverableChangeUtxo, whose blinding is derived from your viewing key nk and a salt carried in the encrypted chain note, so a lost change note can be rebuilt by a scan (see what happens if that storage is lost). That scan is slow, and for a transfer it still needs you to supply the change amount, so the stored copy is the path your app should rely on. Notes built with plain createUtxo, including change from clients that predate recoverable change, have a random blinding that is published nowhere: if your only copy of one of those is lost, nobody can spend it.

A withdrawal of three or more notes is not exempt

The circuit takes two inputs. partialWithdraw, and therefore fullWithdraw, which is a thin wrapper that calls partialWithdraw for the whole input sum, absorbs a larger set by merging on chain first: while more than two notes remain it spends the two smallest in a shield-to-shield transact and creates one merged note in their place, repeating until two are left, and only then builds the withdrawal itself. For n input notes that is n - 2 settled merges ahead of the withdrawal. Each round is a real transaction. It nullifies two of your notes on chain and publishes the merged commitment. The merged note is owned by ownerUtxoKeypair and built with createRecoverableChangeUtxo, so its blinding is derived from your nk and the salt in that round’s chain note. You are never handed the note, because the merge is an implementation detail of the withdrawal.
If a withdrawal of three or more notes throws part way through, the merges that already landed are not undone. The consumed inputs are spent, the merged note sits on chain, and the call produced no result, so there is nothing to persist. Exhausted stale-root retries, a rejected wallet prompt, a failed submission or a closed tab all reach that state. The merged value is not lost: the merged note is output 0 of its round and the chain note carries its amount, so scanTransactions with your nk returns it in recoveredChangeNotes. Until you run that scan, your app does not know the note exists, and retrying with the original inputs fails because they are already spent.
You avoid that gap more cheaply than you repair it. Keep withdrawal inputs at two notes or fewer, and when they are not, run the merges yourself, so that each merged note is in your storage before the next round starts.
onProgress is the only signal a caller gets that consolidation is happening at all. It fires Consolidating notes (n remaining)... once per round. A withdrawal that emits that string is inside the window above until it resolves, so treat it as a state worth surfacing rather than a spinner label.

The two storage exports, and how they relate

UtxoWallet does not accept a StorageAdapter, and a StorageAdapter does not store Utxo objects. They cover different halves of the problem: UtxoWallet is the spendable note set, the adapters are a ready-made place to keep key material. The note set is the half that decides solvency. For a single note rather than a whole set, serializeUtxo(utxo) returns a Uint8Array and deserializeUtxo(bytes) returns a Promise<Utxo>. Those are the primitives if you keep notes in your own table or send one across a boundary; UtxoWallet.serialize() is the batch form.

A note set that survives a reload

serialize() writes the bigints out as strings, so a plain JSON.stringify over raw Utxo objects is not a substitute; it throws on bigint. Use serialize() / deserialize() as the pair. Then record the result of every flow, in the same tick that the flow returns:
serialize() carries amount, keypair, blinding, leaf index and the spent flag. It does not carry commitment, so notes coming back out of deserialize() have commitment undefined, and verifyUtxos reports every one of them as skipped rather than spent or unspent. Recompute before you reconcile against chain state:

How selectUtxos consumes what storage returns

selectUtxos(available, targetAmount) is a pure function over an array you supply. available is exactly what your store hands back: the unspent notes for one mint.
Two things it does not do:
  • It returns null when the balance is short, rather than throwing. A truthy check covers the error path.
  • It does not know about the circuit’s two-input limit. It can return three notes, and transact then throws Maximum 2 input UTXOs allowed before proving. transfer does not consolidate, so cap the selection yourself. partialWithdraw and fullWithdraw do consolidate, merging the two smallest notes repeatedly until two remain, and that convenience is the one described in a withdrawal of three or more notes is not exempt: it settles merges whose notes you never receive, and a failure part way through leaves them findable only by a scan, so cap the selection before a withdrawal too and run the merges yourself.
UtxoWallet.selectInputs(amount, mint, strategy) does the same job against the wallet’s own bookkeeping and throws instead of returning null.
Do not build sends with UtxoWallet.prepareSend or SimpleWallet. prepareSend creates the recipient output from a freshly generated random keypair rather than from the recipient’s key, so the recipient cannot spend what it produces, and SimpleWallet.sync() throws Sync not yet implemented. Use transfer, which derives the recipient output from the Cloak pubkey you pass it. UtxoWallet is sound for the parts used above: addUtxo, markSpent, getBalance, getUnspentUtxos, getStats, selectInputs, serialize and deserialize.

What happens if that storage is lost

Notes built by the current SDK can mostly be rebuilt from your keys. Notes built with plain createUtxo cannot. These are the parts that do and do not come back: scanTransactions is not note recovery. It decrypts your own chain notes with nk and produces the history rows the site documents elsewhere: gross, fee, netAmount and a running balance, ready for toComplianceReport. Two of its fields are the exception and are kept out of transactions and summary because they are secrets rather than history: deliveredNotes (inbound notes whose sender opted in), recoveredDepositNotes (your own deposits, but only the ones built recoverably) and recoveredChangeNotes (your own withdrawal and swap change, and withdrawal merges, built recoverably). Everything else it returns tells you a deposit of 0.02 SOL happened. It does not give you something you can spend. The reason sits in the chain note. Every transaction posts one, sealed under the writer’s own viewing key, and its plaintext is { timestamp, noteSalt, outAmount0, outPubkey0, isSendToSelfKey0 }: output 0’s amount and owner pubkey, plus a salt, and no blinding. A chain note alone therefore cannot rebuild a spendable note. The recoverable shapes work by deriving the blinding from nk and that salt, so a scan can replay the derivation and check the result against a published commitment. See the on-chain chain note is not a delivery channel. scanRecipientDeliveryNotes recovers only notes sent to you by a sender who passed recipientViewingPublicKey. It never surfaces your own change (that is recoveredChangeNotes on scanTransactions), and it surfaces nothing at all when the sender omitted that option. An empty scan is not proof that nothing is stranded. It means nothing in the scanned window was derivable from this nk.

Making deposits recoverable

The deposit examples above already do this. If you want a deposit that a (rpc, programId, nk) scan can rebuild later, build the output note with createRecoverableDepositUtxo and hand the same salt to transact:
The salt has to reach the chain note, which is what chainNoteSalt does, and transact refuses a chainNoteSalt that comes without an explicit chainNoteViewingKeyNk. Recovered notes then appear on scanTransactions(...).recoveredDepositNotes, in spendable form, authenticated by recomputing a commitment the deposit actually published. Pick one nk per wallet and use the same value in both places, at deposit time as chainNoteViewingKeyNk and at scan time as viewingKeyNk. getNkFromUtxoPrivateKey(privateKey) derives it from the UTXO private key, as in where the user’s keys live. Deriving the UTXO keypair from the seed (deriveUtxoKeypairFromSpendKey) makes the keys reproducible, so they need never be the thing you lose. The note set still has to be written down.
Two devices sharing one note set will each believe a spent note is unspent, and the second spend fails with DoubleSpend (0x1020). verifyUtxos(utxos, connection, programId) partitions your local notes into spent, unspent and skipped in a single batched RPC call; run it on load and after any failure, and drop anything it reports as spent.

UX requirements

  • Persist result.outputUtxos before you report a flow as successful. Change the SDK builds can be rebuilt by a scan with nk, but a scan is slow, a transfer’s change also needs its amount, and notes built with createUtxo cannot be rebuilt at all. Treat storage as the source of truth and the scan as a repair tool.
  • Cap withdrawal inputs at two notes, and run the merges yourself above that. A withdrawal handed three or more notes consolidates on chain first, and a failure part way through leaves the merged notes outside your storage, with no result to persist, until a scan finds them.
  • Show progress during proof generation (onProgress, onProofProgress). On the first proof of a page, onProgress reports Downloading circuit files (n of m MB)... (a download of about 23 MB that aborts after 20 s without data and retries up to 3 attempts), then Generating zero-knowledge proof....
  • Expect proving to degrade rather than fail on a constrained browser: the prover uses at most 8 workers (2 in a 32-bit browser), retries with fewer workers and then single-threaded on an out-of-memory error (0.2.12), and abandons a threaded proof that hangs after 60 s to retry single-threaded (0.2.13).
  • Handle stale-root retries gracefully (isRootNotFoundError).
  • Keep circuit files accessible in browser deployments.
  • Ensure viewing-key registration succeeds before transact/swap actions.
  • For privacy history pages, expose explicit cache clear + rescan controls after swaps or failed scans.