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(...)
@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 incloak-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.
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 pool0: fully shielded transfer
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_000lamports (0.01 SOL) for the SOL pool, and1_000_000base units (1.00 token) for the 6-decimal USDC/USDT pools. Anything below the minimum is rejected by the program withDepositTooSmall.transactchecks the SOL minimum before it proves (it throwsDeposit 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 exportedMIN_DEPOSIT_SPL_BASE_UNITSyourself first.
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 aschainNoteViewingKeyNk. It is view-only: it can find and read notes, never spend them.
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.
serializeUtxo and deserializeUtxo are the persistence primitives. Every sample on this page
calls the same helper rather than repeating it:
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.
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:
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:
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.
signerFromWalletAdapterwraps the adapter as a KitTransactionSigner, which you pass assigner. A deposit is signed by that signer and posted straight to the chain. Alongside it you pass the adapter’ssignMessageand the wallet’s address aswalletPublicKey. 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 withsignerFromSecretKey, covers all of it and never prompts.
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 whatwalletPublicKey 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.enforceViewingKeyRegistrationdefaults totrue.- Registration signs a one-time challenge (with
signMessagefor a wallet, ordepositorKeypair) and submitsnkto Cloak for compliance scanning. Nothing viewing-key related is written on chain. - Registration needs the wallet’s
nk(chainNoteViewingKeyNk) and a way to sign. Withoutnk, or withoutsignMessage,signerordepositorKeypair, the call throws a message that beginsViewing key registration is mandatory.
Risk-oracle deposits
When deposits require Range/Switchboard validation, include:riskOracleQueueriskQuoteUrl(orgetRiskQuoteInstruction)
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.outputUtxosand persists none of them. Write them out withserializeUtxobefore you report success. Notes the SDK derives from your keys can be recovered by a scan if you lose them; notes built withcreateUtxocannot. See every result carries notes you should persist. partialWithdrawandfullWithdrawmerge 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).onProgressis the signal. See withdrawing three or more notes consolidates first.- Amounts use
bigintin the UTXO API. - Proof retries are built in for stale roots (
0x1001). Do not wraptransact,partialWithdraworfullWithdrawin your own retry loop. - Pass
result.merkleTreeascachedMerkleTreeto the next call to skip re-fetching commitments. useUniqueNullifiersdefaults totrueon 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 tofalserestores deterministic padding salts, which collide and fail withDoubleSpend(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.transactandswapUtxopre-flight the input nullifiers and throwUtxoAlreadySpentErrorbefore any proof is generated. Catch it and callverifyUtxos()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 nonk, or no way to sign the registration challenge. PasschainNoteViewingKeyNkand 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 passsignMessageandwalletPublicKey; on a server passdepositorKeypair. Full diagnosis in Request authentication.
Next
- Storing the notes these calls return: Wallet integration
- Signing requests: Request authentication
- Protocol behavior: Shield Pool Program
- Runtime lifecycle: Transaction Flows
- Full SDK exports: API Reference