# SDK LLM Reference This file is for AI coding agents integrating the full `@cloak.dev/sdk` surface in external applications. It is intentionally dense, code-first, and grounded in real exports. Every signature and recipe below maps to a function or class that actually exists in `@cloak.dev/sdk`. Use this file as your primary SDK briefing and only fall back to the friendlier `.mdx` guides for conceptual context: - `/sdk/quickstart` - `/sdk/request-authentication` - `/sdk/core-concepts` - `/sdk/utxo-transactions` - `/sdk/wallet-integration` - `/sdk/api-reference` - `/sdk/error-handling` - `/sdk/kit-integration` --- ## 1. Package - Name: `@cloak.dev/sdk` - Version: `0.2.5`. The exported `VERSION` constant now matches the published package version (it lagged before 0.2.5); it is still informational only — confirm the installed version with `npm ls @cloak.dev/sdk`. - **0.2.5 moved the SDK onto `@solana/kit`.** `connection` is a `CloakRpc` from `createCloakRpc(rpcUrl)`; `programId`, mints and recipients are Kit `Address` strings; `depositorKeypair` is a Kit `KeyPairSigner`; `signer` is a Kit transaction signer. `@solana/web3.js` is an optional peer dependency, needed only by `signerFromWalletAdapter` (the browser wallet bridge). `@solana/spl-token` was replaced by `@solana-program/token`. Removed in 0.2.5: `keypairToAdapter` and the `WalletAdapter` type. - Runtime: Node `>=18` and modern browsers. ESM and CJS both shipped (`dist/index.js`, `dist/index.cjs`). - Types: `dist/index.d.ts` - Program ID (default, mainnet): `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW` - Circuits: the 0.2.0 bundle base is pinned into this SDK build (`DEFAULT_TRANSACTION_CIRCUITS_URL`), so standard integrations configure nothing. Override with `setCircuitsPath()` or `CLOAK_CIRCUITS_PATH`. - Submission endpoint: NOT defaulted, by design, so a local or test run can never silently reach production. Pass `relayUrl` in `TransactOptions` on every flow. The SDK reads no environment variable for it; `CLOAK_RELAY_URL` is a convention used by the SDK's own examples and scripts, which read it themselves and pass the value as `relayUrl`. Omitting `relayUrl`, or passing `relayUrl: ""`, makes `transact` / `transfer` / `partialWithdraw` / `fullWithdraw` / `swapUtxo` / `swapWithChange` AND deposits (`externalAmount > 0n`) all throw the same error, before any network call: `Viewing key registration is mandatory: relayUrl is required.` There is no silent fallback to self-submission on the default path, for any flow. The endpoint-pinning bullet below also describes `""` as the caller-signed direct-submission signal; both statements are true and this is the condition that reconciles them: `""` carries that meaning ONLY when `enforceViewingKeyRegistration: false` is passed in the same `TransactOptions`. The viewing-key gate defaults ON and runs first, so on default options `""` never reaches the code that would read it as a signal. Turning the gate off to reach direct submission is unsafe for sends, withdrawals and swaps; see invariant 7. (`swapUtxo` also contains a `relayUrl is required for swapUtxo` throw, but it sits far past the check above and is unreachable unless registration enforcement is turned off; see invariant 7.) - Endpoint pinning: `relayUrl` no longer SELECTS the endpoint. The allowed origins are fixed when this SDK is built (`RELAY_ORIGIN_ALLOWLIST`). Only two values pass the pin: an origin on that allowlist (say `CLOAK_PRODUCTION_RELAY_URL` rather than typing a host), or `""` for caller-signed direct submission. Anything else throws, naming the value and the allowlist. Passing the pin is not the same as reaching submission: `""` only ever behaves as the direct-submission signal when `enforceViewingKeyRegistration: false` is set in the same `TransactOptions`, because the viewing-key gate runs earlier and, on default options, throws `Viewing key registration is mandatory: relayUrl is required.` for every flow including deposits. So an allowlisted origin is the only value a standard integration passes; see invariant 7 before considering the other one. It is not an environment variable because an env var resolves in the consumer process, which is exactly what the pin constrains. - RPC is NOT pinned. The caller builds the `Connection`; the SDK never inspects, replaces or proxies it, and ANY non-loopback RPC is fine. A production build refuses only a LOOPBACK RPC (`localhost` / `127.0.0.1`), through `BUILD_ALLOWS_LOCAL_ENDPOINTS`, which is derived from the same allowlist. Never state or imply that an integrator must use a Cloak-operated RPC; that is false. - Authenticated sender: every relay-submitted flow (private send, withdraw, swap) signs its request body with the END USER'S OWN wallet. Deposits do not, being wallet-signed straight to chain. See invariant 13, §5.8 and `/sdk/request-authentication`. - Hashing: BN254 Poseidon (via `@lightprotocol/hasher.rs`) + BLAKE3. - Proof system: Groth16 via `snarkjs`. - Native companion types come from `@solana/kit`: `Address`, `KeyPairSigner`, `TransactionSigner`. Build the RPC with `createCloakRpc(rpcUrl)`. `@solana/web3.js` is an optional peer dependency, needed only by `signerFromWalletAdapter`. Install: ```bash npm install @cloak.dev/sdk@0.2.5 @solana/kit # Browser apps using a wallet adapter also need: npm install @solana/wallet-adapter-react @solana/web3.js ``` --- ## 2. Runtime contract (invariants an agent MUST preserve) 1. UTXO external amount semantics: - `externalAmount > 0n` -> **deposit** (SDK submits the transaction directly, signed by the user). - `externalAmount < 0n` -> **withdraw / swap** (user does not sign on-chain; SDK handles submission). - `externalAmount === 0n` -> **shield-to-shield transfer** (SDK handles submission). 2. Every UTXO transaction has exactly 2 inputs and 2 outputs. The SDK pads for you using `createZeroUtxo()`. 3. UTXO balance identity the circuit enforces: `inputSum + externalAmount === outputSum`. 4. Amounts in UTXO flows are ALWAYS `bigint`. Never cast to `number` inside transaction logic. 5. Public inputs for the transact/withdraw-swap proofs are 264-byte payloads; do not hand-pack them. 6. On-chain fee model (read by the program from each pool's `pool_config` PDA and collected by the program into the treasury; `transact` reads the live config before building a fee-bearing proof): - SOL: `5_000_000` lamports fixed (`0.005 SOL`) + `0.3 %` variable. SDK helpers: `calculateFee(number)`, `calculateFeeBigint(bigint)`, `isWithdrawAmountSufficient(bigint)`, `getDistributableAmount(number)`. - SPL (USDC/USDT, 6 decimals): `450_000` base units fixed (`0.45` token) + `0.3 %` variable, charged in the withdrawn token. The SDK does not compute SPL fees; there is no SPL fee helper. - Fees only apply on withdrawal/swap paths. Deposits and shield-to-shield transfers pay zero protocol fee. - Minimum deposit: `10_000_000` lamports for SOL, `1_000_000` base units for USDC/USDT. 7. Viewing-key registration is required before scanner/compliance flows can decrypt chain notes. `enforceViewingKeyRegistration: false` in `TransactOptions` is the only thing that turns that check off, and it defaults to enabled. It is also the flag that gates `relayUrl: ""`: with the check on (the default) an empty or omitted `relayUrl` throws before any network call, and only with the check off does `""` act as the caller-signed direct-submission signal described in §1. Do NOT combine it with an omitted or empty `relayUrl`: with the check off and a signer present (`depositorKeypair`, or `signTransaction` + `depositorPublicKey`), `transact` / `transfer` / `partialWithdraw` / `fullWithdraw` submit directly, signed and paid by the user's own key, which links the transaction to that key and loses the privacy the flow exists for. With the check off, no relay and no signer, the call does not fail cleanly either: it reports the problem through `onProgress` and then throws a misleading `commitment indices missing: [-1, -1]` error. Deposits are the one flow where direct submission is correct: they always submit under the depositor's key by design, and require `depositorKeypair` or `signTransaction` + `depositorPublicKey`. 8. Merkle root freshness: treat `RootNotFound` / stale-root errors as retryable. SDK transaction paths already retry these by default; use `preflightCheck` / `waitForRoot` only for advanced/operator flows. 9. Never log secrets: spend keys, viewing keys (`nk`), UTXO private keys, blindings, signed messages, note payloads. 10. Standard integrations should use SDK defaults for program and circuits. Only override for custom/operator deployments. There is no submission-endpoint default: `relayUrl` is required on every flow, and for a standard integration the value is always an allowlisted origin. The other value the pin accepts, `""`, is inert unless invariant 7's check is turned off, and turning it off is not a recipe for a send, withdrawal or swap. 11. In low-level UTXO calls, keep `programId` fixed to `CLOAK_PROGRAM_ID` in one place and do not expose it as user configuration. 12. Minimal scripts should use `KEYPAIR_PATH` + `` input; do not use raw secret env vars or float amount parsing. 13. Relay-submitted flows require an authenticated sender, checked BEFORE any proof work: - Browser: pass `signMessage` AND `walletPublicKey` (or `depositorPublicKey`) in `TransactOptions`. A wallet adapter cannot supply `depositorKeypair`; never generate browser code that asks for one. - Node/server: pass `depositorKeypair`. - Neither, or only half of the wallet pair: `transact` / `transfer` / `partialWithdraw` / `fullWithdraw` / `swapUtxo` / `swapWithChange` throw `Cloak requires an authenticated sender ...` before proof generation. Deposits (`externalAmount > 0n`) are exempt. - The authenticated `sender` IS the key screened for sanctions and the key a viewing key is registered against. It MUST be the end user's real wallet, never an ephemeral, session or service-held key. Passing a `depositorKeypair` and a different `walletPublicKey` throws. - A private send or withdrawal signs EXACTLY ONCE regardless of network retries. Only `swapUtxo` / `swapWithChange` re-prompt, capped by `maxWalletApprovals` (default 5, floored at 1). - Signed requests are valid for `REQUEST_AUTH_MAX_AGE_SECONDS` (300); the SDK holds back 15 seconds for transit, so the usable approval budget is 285 seconds. A machine clock more than `REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS` (30) ahead cannot authenticate at all. Map rejections through `explainRelayAuthRejection`. --- ## 3. Core defaults, constants, and types ```ts import { CLOAK_PROGRAM_ID, // Address, the deployed mainnet program NATIVE_SOL_MINT, // PublicKey, So111...112 DEFAULT_TRANSACTION_CIRCUITS_URL, // ".../cloak-circuits/circuits/0.2.0" (ceremony bundle) TRANSACTION_CIRCUITS_VERSION, // "0.2.0" resolveCircuitsBase, // explicit arg → CLOAK_CIRCUITS_PATH / CLOAK_CIRCUITS env → pinned default MERKLE_TREE_HEIGHT, // 32 FIXED_FEE_LAMPORTS, // 5_000_000 MIN_DEPOSIT_LAMPORTS, // 10_000_000 VARIABLE_FEE_NUMERATOR, // 3 VARIABLE_FEE_DENOMINATOR, // 1000 VARIABLE_FEE_RATE, // 0.003 LAMPORTS_PER_SOL, // 1_000_000_000 SIGN_IN_MESSAGE, // wallet-based viewing-key derivation message VERSION, // SDK version string } from "@cloak.dev/sdk"; ``` Core note/transaction types (from `core/types`): ```ts // Exported union. Mainnet is the only target this package supports; the other members are // historical and nothing in the published surface is configured for them. type Network = "localnet" | "devnet" | "mainnet" | "testnet"; // The `WalletAdapter` type was REMOVED in 0.2.5. The equivalent is `LegacyWalletAdapter`, wrapped // with `signerFromWalletAdapter(adapter, { web3: { VersionedTransaction } })` to get a Kit signer. interface WalletAdapter { publicKey: PublicKey | null; signTransaction?(tx: T): Promise; signAllTransactions?(txs: T[]): Promise; sendTransaction?(tx: Transaction, connection: Connection, options?: SendOptions): Promise; } class CloakError extends Error { category: "network" | "indexer" | "prover" | "relay" | "validation" | "wallet" | "environment" | "service"; retryable: boolean; originalError?: Error; } ``` --- ## 4. Initialization patterns ### 4a. Node.js with a Keypair (server / script) ```ts import { CLOAK_PROGRAM_ID, CLOAK_PRODUCTION_RELAY_URL, setDebugMode } from "@cloak.dev/sdk"; import { createCloakRpc, signerFromSecretKey } from "@cloak.dev/sdk"; import { readFileSync } from "fs"; const signer = await signerFromSecretKey( Uint8Array.from(JSON.parse(readFileSync(process.env.KEYPAIR_PATH!, "utf8"))), ); const connection = createCloakRpc(process.env.SOLANA_RPC_URL!); setDebugMode(true); // There is no client object. The signer travels per call, in TransactOptions. const options = { connection, programId: CLOAK_PROGRAM_ID, relayUrl: CLOAK_PRODUCTION_RELAY_URL, depositorKeypair: signer, walletPublicKey: signer.publicKey, }; ``` ### 4b. Browser with `@solana/wallet-adapter` ```ts import { CLOAK_PROGRAM_ID, CLOAK_PRODUCTION_RELAY_URL, LocalStorageAdapter, getPublicKey, validateWalletConnected, } from "@cloak.dev/sdk"; import { useWallet } from "@solana/wallet-adapter-react"; const wallet = useWallet(); validateWalletConnected(wallet); // Persist notes and key material through an explicit storage boundary. const storage = new LocalStorageAdapter(); const options = { connection, programId: CLOAK_PROGRAM_ID, relayUrl: CLOAK_PRODUCTION_RELAY_URL, signTransaction: wallet.signTransaction!, // signs the DEPOSIT transaction signMessage: wallet.signMessage!, // authenticates send/withdraw/swap requests + viewing-key registration depositorPublicKey: getPublicKey(wallet), walletPublicKey: getPublicKey(wallet), }; ``` ### 4c. UTXO transaction API (primary runtime entry point) ```ts import { transact, partialWithdraw, fullWithdraw, swapWithChange, CLOAK_PROGRAM_ID, } from "@cloak.dev/sdk"; import { createCloakRpc } from "@cloak.dev/sdk"; const connection = createCloakRpc(process.env.SOLANA_RPC_URL!); const programId = CLOAK_PROGRAM_ID; ``` ### 4d. Kit-flavored reads alongside SDK ```ts import { createSolanaRpc, address } from "@solana/kit"; import { createCloakRpc } from "@cloak.dev/sdk"; const kitRpc = createSolanaRpc(process.env.SOLANA_RPC_URL!); const connection = createCloakRpc(process.env.SOLANA_RPC_URL!); // Reads via Kit: const balance = await kitRpc.getBalance(address(signer.publicKey.toBase58())).send(); // Writes via SDK (still uses web3.js Connection): ``` For an end-to-end Kit-flavored integration shape, combine the read/write split in this section with the transaction recipes in section 6. --- ## 5. Full capability map Group exports by responsibility. Every symbol below is a real named export of `@cloak.dev/sdk`. ### 5.1 Package constants and entry points There is no client class. The transaction entry points are free functions, listed in §5.3. - `CLOAK_PROGRAM_ID`: `PublicKey`, mainnet program - `NATIVE_SOL_MINT`: `PublicKey`, SOL pool mint identity - `VERSION`: string, currently `"0.2.5"` -- matches the published package version (it lagged before 0.2.5); informational only, confirm the installed version with `npm ls @cloak.dev/sdk` - `setDebugMode(enabled: boolean)`: global SDK logging switch - `LocalStorageAdapter` / `MemoryStorageAdapter`: `StorageAdapter` implementations (see §5.13) ### 5.2 UTXO primitives (primary data model) ```ts interface UtxoKeypair { privateKey: bigint; // ~252-bit field element publicKey: bigint; // Poseidon(privateKey, 0) } interface Utxo { amount: bigint; keypair: UtxoKeypair; blinding: bigint; mintAddress: Address; // NATIVE_SOL_MINT for SOL index?: number; // leaf index after insertion commitment?: bigint; // Poseidon(amount, pubkey, blinding, mintField) nullifier?: bigint; // computed at spend time siblingCommitment?: bigint; // other output from the same tx } // Exports: const NATIVE_SOL_MINT: Address; function randomFieldElement(): bigint; function generateUtxoKeypair(): Promise; function deriveUtxoKeypairFromSpendKey(skSpend: Uint8Array): Promise; function derivePublicKey(privateKey: bigint): Promise; function createUtxo(amount: bigint, keypair: UtxoKeypair, mint?: Address): Promise; function createZeroUtxo(mint?: Address, salt?: bigint): Promise; function pubkeyToFieldElement(pubkey: Address): bigint; function computeUtxoCommitment(utxo: Utxo): Promise; function computeSignature(privateKey: bigint, commitment: bigint, pathIndex: bigint): Promise; function computeUtxoNullifier(utxo: Utxo): Promise; function serializeUtxo(utxo: Utxo): Uint8Array; // 128 bytes, little-endian function deserializeUtxo(bytes: Uint8Array): Promise; function bigintToHex(value: bigint): string; function utxoHexToBigint(hex: string): bigint; function utxoBigintToBytes32(value: bigint): Uint8Array; function sumUtxoAmounts(utxos: Utxo[]): bigint; function selectUtxos(available: Utxo[], targetAmount: bigint): Utxo[] | null; function utxoEquals(a: Utxo, b: Utxo): Promise; // Reconcile restored notes against chain before spending them. A note only lands in `unspent` or // `spent` when it carries `commitment`, `mintAddress` AND a keypair; anything missing one of those // lands in `skipped`, which means UNVERIFIED, not absent. interface VerifyUtxosResult { spent: Utxo[]; unspent: Utxo[]; skipped: Utxo[]; } function verifyUtxos( utxos: Utxo[], connection: CloakRpc, programId: Address, commitment?: "processed" | "confirmed" | "finalized", ): Promise; function preflightNullifiers( // throws UtxoAlreadySpentError on a spent input utxos: Utxo[], connection: CloakRpc, programId: Address, commitment?: "processed" | "confirmed" | "finalized", ): Promise; ``` `serializeUtxo` is the persistence primitive and it is the ONLY one: 128 bytes carrying amount, private key, blinding, mint and index. Every flow hands back a note the SDK then forgets, with one conditional exception below (a full withdrawal of one or two input notes), and `createUtxo` draws that note's `blinding` from `randomFieldElement()` and writes it nowhere on chain, so a note that is not serialized to durable storage before you report success is permanently unspendable by anyone. `StorageAdapter` (§5.13) is a DIFFERENT boundary: its methods are typed on `CloakNote`, and it does not accept these bytes. **The full-withdrawal exemption is CONDITIONAL: it holds for one or two input notes only.** `fullWithdraw` sums the inputs and calls `partialWithdraw`, and `partialWithdraw` runs `while (utxos.length > 2)` first: it sorts the notes, merges the two smallest on chain into a fresh note from `createUtxo`, and repeats until two remain. Each round nullifies its two inputs on chain and the merged note's blinding exists only in that call's local variable. If a later round or the final withdrawal throws (stale-root retries exhausted, a relay 5xx, a closed tab, a rejected wallet approval), the spent inputs are gone, the merged commitment is on chain, and the call returns no result to persist, so the balance is unrecoverable by anyone. There is no API that hands you the intermediate note. Mitigations, in order: withdraw from at most two notes (consolidate deliberately with your own `transact` calls, persisting each merged output, before calling `fullWithdraw`), and watch `onProgress` for `Consolidating notes (n remaining)...`, which is the ONLY signal the caller gets that consolidation is running. `partialWithdraw` shares the same loop and the same exposure. ### 5.3 UTXO transaction API (primary runtime path) ```ts function transact(params: TransactParams, options: TransactOptions): Promise; function transfer(inputUtxos: Utxo[], recipientPubkey: bigint, amount: bigint, options: TransactOptions): Promise; function partialWithdraw(inputUtxos: Utxo[], recipient: Address, withdrawAmount: bigint, options: TransactOptions): Promise; function fullWithdraw(inputUtxos: Utxo[], recipient: Address, options: TransactOptions): Promise; function swapUtxo(params: UtxoSwapParams, options: TransactOptions): Promise; function swapWithChange( inputUtxos: Utxo[], swapAmount: bigint, outputMint: Address, recipientAta: Address, minOutputAmount: bigint, options: TransactOptions, recipientWallet?: Address, ): Promise; // The swap result. It extends TransactResult, so it also carries `signature`, `outputUtxos`, // `commitmentIndices`, `merkleTree` and the rest of that shape. interface UtxoSwapResult extends TransactResult { swapStatePda: string; // SwapState PDA, base58 nullifier: string; // hex nullifier the PDA is derived from requestId?: string; // request id for polling swap execution status refund: { // the timeout-refund secret. MONEY. Persist it (see below). privateKey: string; // hex 32-byte field elements, all three publicKey: string; blinding: string; derivedFromNk: boolean; // true => also rediscoverable from `nk` (discoverSwapRefunds, §5.5) }; } function computeExtDataHash(recipient: Address | null, relayerFee: bigint, relayer: Address | null, maxFee?: bigint): Promise; // Chain note v4. The tail binds noteSemantics = Poseidon(outAmount0, outPubkey0, isSendToSelfKey0) // to match the ceremony circuit, so this is an EIGHT-argument hash, not four. `transact` computes // it for you; there is no reason to call this in an integration. function computeChainNoteHash( publicAmount: bigint, extDataHash: bigint, noteTimestamp: bigint, noteCommitment: bigint, noteSalt: bigint, outAmount0: bigint, outPubkey0: bigint, noteIsSendToSelfKey0: bigint, ): Promise; function setCircuitsPath(next: string): void; function getCircuitsPath(): string | null; function resolveCircuitsBase(explicit?: string): string; // explicit → CLOAK_CIRCUITS_PATH / CLOAK_CIRCUITS → pinned 0.2.0 default function fetchRiskQuoteInstruction( riskQuoteUrl: string, wallet: Address, options: { // REQUIRED, and `poolMint` inside it is required too poolMint: Address; recipient?: Address; amount?: bigint; token?: Address; commitment?: string | Uint8Array; context?: "deposit" | "send" | "withdraw"; nullifier0?: string; nullifier1?: string; }, ): Promise; const DEFAULT_TRANSACTION_CIRCUITS_URL: string | null; // ".../cloak-circuits/circuits/0.2.0" in 0.2.0 const TRANSACTION_CIRCUITS_VERSION: "0.2.0"; ``` **`UtxoSwapResult.refund` is the user's principal, not telemetry.** A swap locks the SOL in a SwapState PDA and only settles on a second transaction. If it times out before that, the close path returns the principal to the pool as an amount-bound note ``` R_fb = Poseidon(amountAfterFee, refund.publicKey, refund.blinding, WSOL) ``` where `amountAfterFee` is the amount the program actually locked, read authoritatively from the on-chain `SwapState.sol_amount` (the gross swap amount minus the on-chain program fee). Claiming it back requires `refund.privateKey`. Persist the whole `refund` object alongside the change note, in the same tick `swapUtxo` / `swapWithChange` returns. `derivedFromNk` says whether losing it is survivable. When it is `true`, the same secret can be rebuilt later from the wallet's `nk` plus the swap's public first input nullifier, which is what `discoverSwapRefunds` (§5.5) walks the chain for. When it is `false`, the returned object is the only copy that will ever exist. The `nk` in question is `TransactOptions.chainNoteViewingKeyNk` when you passed one; when you did not, the SDK falls back to `getNkFromUtxoPrivateKey(inputUtxos[0].keypair.privateKey)`, so the recovery scan then needs that same first input's private key. Pass an explicit `chainNoteViewingKeyNk` on every swap so the recovery key is one you already hold. Persisting `refund` stays the fast path either way. Key `TransactOptions` fields (most used): ```ts interface TransactOptions { connection: CloakRpc; programId: Address; relayUrl?: string; // NO default, see §1; required on every flow. // Pass an allowlisted origin. "" is the caller-signed // direct-submission signal ONLY with // enforceViewingKeyRegistration: false; on default // options "" throws like omitting it (§1, invariant 7). // Signing. The RUNTIME picks the shape; it is not a free choice (invariant 13, §8 rule 15): // NODE / SERVER: depositorKeypair + walletPublicKey. // BROWSER: signMessage + walletPublicKey on every relay-submitted flow (private send, // withdraw, swap), plus signTransaction + depositorPublicKey on a deposit. // A wallet adapter holds no secret key and can never produce a Keypair, so depositorKeypair in // browser code is code that cannot run. Never generate it there, and never ask a browser user // for a keypair.json path. depositorKeypair?: Keypair; // NODE / SERVER ONLY. Unreachable from a wallet adapter. signTransaction?: WalletAdapter["signTransaction"]; // browser: signs the DEPOSIT transaction signMessage?: (msg: Uint8Array) => Promise; // browser: authenticates relay-submitted // flows AND the viewing-key challenge, so it is required // in the browser on every flow, deposits included. walletPublicKey?: Address; // the END USER'S real wallet, never an ephemeral or // service key. Passing depositorKeypair together with a // DIFFERENT walletPublicKey throws. depositorPublicKey?: Address; // UX / observability: onProgress?: (status: string) => void; onProofProgress?: (percent: number) => void; // Retry + reliability: maxRootRetries?: number; retryDelayMs?: number; // Compliance / chain notes: chainNoteViewingKeyNk?: string | Uint8Array; getChainNoteViewingKeyNk?: () => Promise; chainNoteSalt?: bigint; // pin the note's 96-bit salt; pass the `noteSalt` from // createRecoverableDepositUtxo so a cold scan can rebuild // the deposit note (§5.5). Requires an explicit nk. recipientViewingPublicKey?: Uint8Array | string; // shield-to-shield ONLY: the RECIPIENT'S X25519 // public viewing key, i.e. // deriveViewingKeyFromNk(recipientNk).publicKey. Without // it the send still succeeds but the recipient CANNOT // discover the note from chain (§5.5, §6.4). disableChainNotes?: boolean; // drop the on-chain ciphertext blob only; the proof still // binds chainNoteHash. Costs auto-scan discovery. metadataBundle?: EncryptedMetadataBundle; encryptedNotes?: string[]; enforceViewingKeyRegistration?: boolean; // Performance: cachedMerkleTree?: MerkleTree; useChainForMerkle?: boolean; useChainRootForProof?: boolean; useUniqueNullifiers?: boolean; // ALTs: altAddresses?: string[]; addressLookupTableAccounts?: AddressLookupTableAccount[]; // Swap-specific: maxWalletApprovals?: number; // swaps ONLY: cap on wallet re-prompts (default 5, // floored at 1). Sends and withdrawals prompt once and // never consult this. swapDexes?: string[]; swapExcludeDexes?: string[]; swapRouteRetryAttempts?: number; swapMaxRetries?: number; swapSlippageBps?: number; swapStatusMaxAttempts?: number; swapStatusDelayMs?: number; // Risk oracle: riskOracleQueue?: Address; riskQuoteUrl?: string; getRiskQuoteInstruction?: (wallet: Address) => Promise; // one arg rangeApiKey?: string; } ``` ### 5.4 Chain-note encryption `transact` builds and embeds the chain note itself when you pass `chainNoteViewingKeyNk`. These exports exist for callers reading notes back. There is no `encodeCompactChainNote` / `decodeCompactChainNote` in the public surface: encryption and encoding are the same call. ```ts type ChainNoteTxType = "deposit" | "withdraw" | "transfer" | "swap" | "unknown"; interface CompactChainNote { timestamp: bigint; commitment: string; noteSalt?: bigint; // v3+ outAmount0?: bigint; // v4 only: the three terms of noteSemantics outPubkey0?: bigint; isSendToSelfKey0?: bigint; } // Encrypt. Takes the note's parts, NOT a CompactChainNote, and the caller's `nk`, NOT a public // key. Returns raw envelope BYTES, not base64. function encryptCompactChainNote( timestamp: bigint, nk: Uint8Array, commitmentHex: string, noteSalt: bigint, semantics?: { outAmount0: bigint; outPubkey0: bigint; isSendToSelfKey0: bigint }, ): Promise; // Decrypt. The key is derived per output commitment, so you MUST supply the candidate commitments // the transaction published; the call tries each until AES-GCM authenticates. Accepts v3 and // legacy v2 notes. It is async. function decryptCompactChainNote( noteBytes: Uint8Array, nk: Uint8Array, candidateCommitments: string[], ): Promise; // Transport only: these move ENVELOPE BYTES in and out of base64. Neither one parses a note. function chainNoteToBase64(noteBytes: Uint8Array): string; function chainNoteFromBase64(base64: string): Uint8Array; ``` For ordinary history and note recovery, do not drive these by hand: `scanTransactions` (§5.5) finds the envelopes, supplies the candidate commitments and decrypts them for you. ### 5.5 Scanner / compliance ```ts interface ScanOptions { connection: CloakRpc; programId: Address; viewingKeyNk: Uint8Array; limit?: number; afterTimestamp?: number; beforeTimestamp?: number; untilSignature?: string; onProgress?: (processed: number, total: number) => void; batchSize?: number; onStatus?: (status: string) => void; debug?: boolean; walletPublicKey?: string; includeRecipientDeliveries?: boolean; // sweep the CLKD1 delivery registry (default: true) ownerUtxoPublicKey?: bigint; // this wallet's UTXO pubkey; without it deliveries arrive UNVERIFIED deliveryMints?: Address[]; // candidate pool mints for that verification (default: native SOL) } interface ScannedTransaction { txType: ChainNoteTxType; amount: bigint; fee: bigint; netAmount: bigint; timestamp: bigint; // ms recipient: string; // base58 commitment: string; // hex signature: string; runningBalance: bigint; mint: string; decimals: number; symbol: string; outputMint?: string; // swaps outputSymbol?: string; } interface ScanSummary { totalDeposits: bigint; totalWithdrawals: bigint; totalFees: bigint; netChange: bigint; transactionCount: number; finalBalance: bigint; } interface ScanResult { transactions: ScannedTransaction[]; summary: ScanSummary; lastSignature?: string; rpcCallsMade: number; // Note RECOVERY. Additive by design: these carry SPENDABLE secrets, so they are deliberately // kept out of `transactions` / `summary` and the compliance report shape is unchanged. deliveredNotes: DeliveredNote[]; recoveredDepositNotes: RecoveredDepositNoteRecord[]; } // A note delivered TO the scanning wallet by SOMEONE ELSE'S shield-to-shield send. interface DeliveredNote { commitment: string; // lowercase hex, as the carrier declares it amount: bigint; // decrypted from the envelope blinding: bigint; // decrypted from the envelope carrierSignature: string; // the discovery record, NOT the source transaction blockTime?: number; // seconds, when the RPC supplied one mint?: string; // resolved by recomputing; present only with `ownerUtxoPublicKey` commitmentVerified: boolean; // true ONLY when the commitment was recomputed and matched } // This wallet's OWN deposit, rebuilt in spendable form from `nk` alone. interface RecoveredDepositNoteRecord { // extends RecoveredDepositNote extends DepositNoteSecrets keypair: UtxoKeypair; blinding: bigint; amount: bigint; mintAddress: Address; commitment: bigint; // the published commitment, reproduced from the derived secrets noteSalt: bigint; // the salt the chain note carried, which anchored the derivation signature: string; // the deposit transaction timestamp: bigint; // ms, from the chain note } // ComplianceReport is the JSON-safe version of ScanResult. function scanTransactions(opts: ScanOptions): Promise; function toComplianceReport(result: ScanResult): ComplianceReport; function formatComplianceCsv(report: ComplianceReport): string; // Deposit-note recovery helpers (the builder side of `recoveredDepositNotes`). function createRecoverableDepositUtxo( amount: bigint, viewingKeyNk: Uint8Array, mintAddress?: Address, noteSalt?: bigint, ): Promise<{ utxo: Utxo; noteSalt: bigint }>; function deriveDepositNoteSecrets(viewingKeyNk: Uint8Array, noteSalt: bigint): Promise; function randomDepositNoteSalt(): bigint; // Delivery-registry sweep on its own, when you do not want a full history scan. It resolves to a // WRAPPER, not a bare array: read `.notes`. Its options name the mint list `mints`, not // `deliveryMints` (that spelling belongs to `ScanOptions`). function scanRecipientDeliveryNotes( opts: ScanRecipientDeliveryOptions, // { connection, programId, viewingKeyNk, // ownerUtxoPublicKey?, mints?, onStatus?, debug? } ): Promise<{ notes: DeliveredNote[]; rpcCalls: number }>; ``` **History is NOT recovery, and the two fields above are the exception.** Getting this wrong is how a wallet loses funds, so do not generalise from either half of it: - `transactions` is a HISTORY row. It records that a note existed and for how much. It carries no keypair and no blinding, so nothing in it can be spent. A UI can render it; a wallet cannot restore a balance from it. - `deliveredNotes` IS spendable: notes other people sent to this wallet, opened from the CLKD1 delivery registry with the scanning wallet's `nk`. The carrier memo's commitment field is unauthenticated, so treat a note as real only when `commitmentVerified === true`, which requires passing `ownerUtxoPublicKey` (and `deliveryMints` for a non-SOL pool) in `ScanOptions`. Without it, every delivered note comes back `commitmentVerified: false`. - `recoveredDepositNotes` IS spendable: this wallet's own deposits, rebuilt from `nk` alone. ONLY deposits built with `createRecoverableDepositUtxo(...)` AND submitted with that same salt as `TransactOptions.chainNoteSalt` land here. A deposit whose blinding came from raw randomness has nothing to rebuild and appears as a history row only. - NOTHING recovers a CHANGE note. `createUtxo` draws its blinding from `randomFieldElement()` and writes it nowhere, and the chain note carries no blinding, so the change output of a send, a partial withdraw or a swap is unrecoverable the moment it is dropped. Persist every output UTXO with `serializeUtxo` (§5.2) as soon as the call returns. Scanning will not bring it back. - A swap's `UtxoSwapResult.refund` (§5.3) is a separate secret again, and it is the only way to claim the principal back if the swap times out. It is the one item on this list with a key-only fallback: `discoverSwapRefunds`, below, when the swap was built with an `nk`. Persist it anyway. **Swap timeout-refund discovery.** The recovery path for a `UtxoSwapResult.refund` (§5.3) that was never persisted: it rebuilds the stranded refund leaf from key material alone, with no relay, no local note store and no prior knowledge of the swap. ```ts interface SwapRefundAuthorization { privateKey: bigint; publicKey: bigint; blinding: bigint; } interface RecoveredSwapRefund { keypair: UtxoKeypair; blinding: bigint; amount: bigint; commitment: bigint; // R_fb, identical to the leaf the close path appended } interface DiscoveredSwapRefund extends RecoveredSwapRefund { signature: string; // the close transaction that appended the leaf leafIndex: bigint; inputNullifier: Uint8Array; // first input nullifier of the swap this refund belongs to swapSignature?: string; // the opening swap tx, when it fell inside the scanned window } function discoverSwapRefunds( connection: CloakRpc, programId: Address, viewingKeyNk: Uint8Array, // the SAME nk the swap was built with (§5.3) options?: { limit?: number; // program signatures to walk; omit or 0 for all history untilSignature?: string; // resume cursor from a previous run (exclusive) batchSize?: number; // getTransaction concurrency, default 50 onStatus?: (status: string) => void; poolMint?: Address; // swap input is wSOL-locked; the SOL default is correct }, ): Promise; // The pieces it is built from, for a caller walking its own transactions instead. function deriveSwapRefundAuthorization( viewingKeyNk: Uint8Array, inputNullifier: Uint8Array | bigint, ): Promise; function computeSwapRefundCommitment( amountAfterFee: bigint, refundPublicKey: bigint, refundBlinding: bigint, ): Promise; function matchSwapRefundLeaf(params: { viewingKeyNk: Uint8Array; inputNullifier: Uint8Array | bigint; // read from the swap's public inputs amountAfterFee: bigint; // the principal the close path returned commitment: bigint | Uint8Array; // R_fb as appended on chain }): Promise; // null for every leaf that is not this wallet's ``` An empty result is NOT proof that a wallet has no stranded refund. `discoverSwapRefunds` finds only refunds whose authorization was DERIVED from an `nk`. A swap whose refund keypair and blinding came from raw randomness has no derivation to replay, and no key-only scan will ever find it; for those, the in-memory `UtxoSwapResult.refund` was the only copy. Never report "no stranded refunds" on the strength of an empty return. ### 5.6 Viewing keys + compliance keys ```ts interface ViewingKeyPair { privateKey: Uint8Array; publicKey: Uint8Array; } interface ExpandedSpendKey { ask: Uint8Array; nsk: Uint8Array; ovk: Uint8Array; } function expandSpendKey(skSpend: Uint8Array): ExpandedSpendKey; function deriveViewingKeyFromNk(nk: Uint8Array): ViewingKeyPair; function deriveViewingKeyFromSpendKey(skSpend: Uint8Array): ViewingKeyPair; function deriveViewingKeyFromUtxoPrivateKey(utxoPrivateKey: bigint): ViewingKeyPair; function getNkFromUtxoPrivateKey(utxoPrivateKey: bigint): Uint8Array; function deriveDiversifier(nk: Uint8Array, commitmentHex: string, outputIndex: number): Uint8Array; // 11 bytes function deriveDiversifiedViewingKey(nk: Uint8Array, diversifier: Uint8Array): ViewingKeyPair; function generateViewingKeyPair(): ViewingKeyPair; function registerViewingKey( relayUrl: string, userPubkey: Address, nk: Uint8Array, signMessage: (msg: Uint8Array) => Promise, ): Promise; const SIGN_IN_MESSAGE: string; ``` ### 5.7 Metadata encryption ```ts function encryptTransactionMetadata( metadata: TransactionMetadata, userViewKeyPublic: Uint8Array, complianceKeyPublic: Uint8Array, context?: { userPubkey?: Address | string }, ): Promise; function encryptTransactionMetadataBundle( metadata: TransactionMetadata, viewingKeyPrivate: Uint8Array, userPubkey: Address, ): Promise<{ encrypted_user: string; encrypted_compliance: string; user_pubkey: string; commitment: string; timestamp: number; tx_type?: string; // widened to `string` here, NOT `ComplianceTxType`: // `const t: ComplianceTxType = bundle.tx_type` does not compile. // Narrow it yourself before treating it as the union. }>; function decryptTransactionMetadata(encrypted: string, viewKeySecret: Uint8Array): Promise; function decryptComplianceMetadataWithMasterKey( encrypted: string, masterCompliancePrivateKey: Uint8Array, masterCompliancePublicKey: Uint8Array, userPublicKey: Address, ): Promise; ``` ### 5.8 Relay + merkle + on-chain proof helpers ```ts // Every params shape below is declared INLINE on the class. There is no exported // `SubmitWithdrawParams` / `SubmitSwapParams` type name to import. class RelayService { constructor(baseUrl: string); submitWithdraw( params: { proof: string; publicInputs: { root: string; nf: string; outputs_hash: string; amount: number }; outputs: Array<{ recipient: string; amount: number }>; feeBps: number; metadataBundle?: EncryptedMetadataBundle; }, onStatusUpdate?: (status: string) => void, onRequestId?: (requestId: string) => void, ): Promise; submitSwap( params: { proof: string; publicInputs: { root: string; nf: string; outputs_hash: string; amount: number }; outputs: Array<{ recipient: string; amount: number }>; feeBps: number; swap: { output_mint: string; slippage_bps: number; min_output_amount: number }; metadataBundle?: EncryptedMetadataBundle; }, onStatusUpdate?: (status: string) => void, onRequestId?: (requestId: string) => void, ): Promise; resumeWithdraw(requestId: string, onStatusUpdate?: (status: string) => void): Promise<{ status: "completed" | "failed" | "pending"; signature?: string; error?: string; }>; getStatus(requestId: string): Promise; registerViewingKey(userPubkey: string, viewingKey: string, signMessage: (msg: Uint8Array) => Promise): Promise; getCompliancePublicKey(): Promise; } function fetchCommitments(relayUrl: string, options?: { mint?: Address; timeoutMs?: number; maxRetries?: number; sync?: boolean; repair?: boolean; requireTarget?: boolean; requireCanonical?: boolean; fromIndex?: number; limit?: number; waitForIndex?: number; }): Promise; function buildMerkleTreeFromRelay(relayUrl: string, options?: { mint?: Address; sync?: boolean; repair?: boolean; requireTarget?: boolean; requireCanonical?: boolean; timeoutMs?: number; maxRetries?: number; waitForIndex?: number; }): Promise; function buildMerkleTreeFromChain( connection: CloakRpc, programId: Address, merkleTree: Address, onProgress?: (m: string) => void, mint?: Address, // required in practice: without it a CloseSwapState refund leaf // cannot be attributed to a tree and reconstruction fails closed ): Promise; function validateRoot(relayUrl: string, rootHex: string): Promise<{ valid: boolean; currentRoot?: string; message: string; isRecent: boolean; }>; function waitForRoot(relayUrl: string, rootHex: string, timeoutMs?: number, pollIntervalMs?: number): Promise<{ success: boolean; currentRoot?: string; waitedMs: number; }>; function preflightCheck(relayUrl: string, rootHex: string): Promise<{ shouldProceed: boolean; action: "proceed" | "refresh_proofs" | "rebuild_tree" | "wait"; message: string; estimatedWaitMs?: number; }>; function readMerkleTreeState( connection: CloakRpc, merkleTreePDA: Address, forceConfirmed?: boolean, relayUrl?: string, skipRelayRoot?: boolean, mint?: Address, ): Promise<{ nextIndex: number; root: string; subtrees: string[] }>; function computeProofFromChain(connection: CloakRpc, merkleTreePDA: Address, leafIndex: number, forceConfirmed?: boolean): Promise; function computeProofForLatestDeposit(connection: CloakRpc, merkleTreePDA: Address): Promise; ``` **Request authentication (all exported).** Standard integrations never call these: pass `signMessage` + `walletPublicKey` (browser) or `depositorKeypair` (server) in `TransactOptions` and the SDK signs for you. These exist for callers driving submission themselves. ```ts // Endpoint pinning const CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag"; // a NAME, never a default const RELAY_ORIGIN_ALLOWLIST: readonly string[]; // origins THIS build may reach const BUILD_ALLOWS_LOCAL_ENDPOINTS: boolean; // derived; true only for a local build // Freshness window const REQUEST_AUTH_MAX_AGE_SECONDS = 300; // usable budget is 285 (15s held back for transit) const REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS = 30; // a clock this far FAST cannot authenticate // The exact fields each body signs, sorted; order is part of the agreement const TRANSACT_AUTH_FIELDS: readonly ["encrypted_notes","max_fee","mint","proof_bytes","public_inputs","recipient","recipient_delivery_notes","risk_quote","sender"]; const TRANSACT_SWAP_AUTH_FIELDS: readonly ["close_timed_out","dexes","encrypted_notes","exclude_dexes","max_fee","min_output_amount","output_mint","proof_bytes","public_inputs","recipient","recipient_ata","refund_blinding","refund_pubkey","retry_request_id","risk_quote","route_retry_attempts","sender","slippage_bps","swap_max_retries"]; interface RelayAuthPreimage { sender: string; auth_issued_at: string; auth_nonce: string; message: Uint8Array; } interface RelayAuthSigner { walletPublicKey: Address; signMessage: (m: Uint8Array) => Promise; } function buildRelayAuthPreimage( endpoint: string, // the exact path POSTed to, e.g. "/transact" programId: Address, body: Record, sender: Address, // the END USER'S wallet; becomes `sender` nowSeconds?: number, fields?: readonly string[], // TRANSACT_AUTH_FIELDS (default) | TRANSACT_SWAP_AUTH_FIELDS ): RelayAuthPreimage; function canonicalJson(value: unknown): string; // keys sorted bytewise, no whitespace function explainRelayAuthRejection(responseText: string): string | null; function submitTransactToRelay( // takes depositorKeypair | relayAuthSigner args: SubmitTransactToRelayArgs, ): Promise; type RelaySubmissionResult = | { kind: "submitted"; signature: string; commitmentIndices?: [number, number]; viewingKeyRegistered?: boolean; settlement: SettlementVerdict } | { kind: "stale-root"; error: Error } // root rejected; rebuild the tree and re-prove | { kind: "failed"; error: Error }; interface SettlementVerdict { status: "landed" | "failed" | "not-landed" | "unknown"; signature: string | null; reason: string; // safe to put in an error message nullifiersSpent: boolean; // true when every checkable nullifier PDA was on chain signatureStatus: "finalized" | "confirmed" | "processed" | "absent" | "error" | "unchecked"; } ``` Branch on `kind`; the three outcomes above are returned, not thrown. A `"submitted"` result is not by itself proof: read `settlement.status`, and never report `"unknown"` as success or silently retry it. Surface `settlement.signature` instead. `preimage.message` is a plain ed25519 detached-signature preimage, newline separated: ``` CLOAK_RELAY_REQUEST_AUTH_V1 ``` Put `sender`, `auth_issued_at`, `auth_nonce` from the preimage plus the base64 signature as `auth_signature` on the POSTed body. Re-POSTing a request MUST reuse the same preimage and the same body bytes; rebuilding it produces a new request, not a retry. HARD TRAP: `slippage_bps` MUST always be present in a signed swap body. Every other field in both lists signs as an explicit `null` when absent, but `slippage_bps` is a bare `u16` with a default of `500` on the receiving side, so omitting it signs `null` against a signed `500`. The digests diverge and the rejection never mentions slippage. `buildRelayAuthPreimage` refuses the call rather than sign a digest that cannot match. ### 5.9 Proof / circuit utilities This SDK pins exactly ONE circuit: the ceremony-frozen `transaction` circuit. The pre-ceremony `withdraw_regular` / `withdraw_swap` circuits were removed in 0.2.0 together with every function that loaded them, so proof generation is not a public entry point at all. There is no `generateWithdrawRegularProof`, `generateWithdrawSwapProof`, `areCircuitsAvailable` or `getDefaultCircuitsPath`, and no `WithdrawRegularInputs` / `WithdrawSwapInputs` / `ProofResult` type. `transact` and the flows built on it load, verify and prove for you; the exports below exist for start-up diagnostics and for callers driving artifact loading themselves. ```ts // Load artifacts and get back the very bytes whose digest was checked. Fails closed on any // mismatch, unreachable artifact, or environment that cannot produce bytes. `circuitsPath` is a // base directory or URL, honoured verbatim; pass `null` to report the "no base configured" state. function loadVerifiedCircuitArtifacts(circuitsPath: string | null): Promise<{ wasm: Uint8Array; zkey: Uint8Array; digests: { wasm: string; zkey: string }; // SHA-256 of the buffers in this same object }>; // the return shape is declared inline; it is NOT an exported type name // The fail-closed gate: throws when the artifacts are not the pinned ones. function assertTransactionCircuitIntegrity( circuitsPath: string | null, prefetched?: { wasm: Uint8Array; zkey: Uint8Array }, // already-downloaded bytes, to skip a refetch ): Promise; // Reporting only. These do NOT gate proving: a check that re-reads the source cannot speak for the // bytes a later, independent read returns. Prove from loadVerifiedCircuitArtifacts, always. function verifyCircuitIntegrity( circuitsPath: string | null, prefetched?: { wasm: Uint8Array; zkey: Uint8Array }, ): Promise; function verifyAllCircuits( circuitsPath: string | null, transactionCircuitsPath?: string | null, // same base; takes precedence when given ): Promise; // one entry, for `transaction` interface CircuitVerificationResult { valid: boolean; error?: string; computed?: { wasm: string; zkey: string }; expected?: { wasm: string; zkey: string }; } const DEFAULT_CIRCUITS_URL: string; // alias of DEFAULT_TRANSACTION_CIRCUITS_URL: same ceremony transaction bundle, same 0.2.0 URL, never null const EXPECTED_CIRCUIT_HASHES: Readonly<{ // frozen VIEW; exactly two keys, no withdraw_* entries transaction_wasm: string; // 02ec02e954ae3932827ad9de51afa597ca95569aa97fec8410879c937a58aa2b transaction_zkey: string; // 9da7db8cb1370fc497d36a0365f1f107ab0b0c13ca66fa9f0287e5f96ee68d25 }>; ``` There is no environment variable that disables the integrity check. A build that genuinely needs different artifacts needs different DIGESTS, which is a source edit and a rebuild, exactly like the endpoint pin. The `transaction` circuit (used by `transact`, `transfer`, `partialWithdraw`, `fullWithdraw`, `swapUtxo`, `swapWithChange`) is frozen by the `cloak-transaction-0.2.0` trusted-setup ceremony. The SDK checks every artifact it loads against these digests and refuses to prove against anything else; the program rejects proofs from the older `0.1.0` bundle. ### 5.10 Wallet helpers ```ts function validateWalletConnected(wallet: WalletAdapter | Keypair): void; function getPublicKey(wallet: WalletAdapter | Keypair): Address; function sendTransaction( tx: Transaction, wallet: WalletAdapter | Keypair, connection: CloakRpc, options?: SendOptions, ): Promise; function signTransaction(tx: T, wallet: WalletAdapter | Keypair): Promise; // keypairToAdapter was REMOVED in 0.2.5 -- pass a Kit `KeyPairSigner` (signerFromSecretKey) directly. ``` `UtxoWallet` and `SimpleWallet` are also exported and are NOT send paths. `UtxoWallet.prepareSend` and `SimpleWallet.send` build the recipient output from a freshly generated random keypair, so the recipient cannot spend what they produce, and `SimpleWallet.sync()` throws `Sync not yet implemented`. `UtxoWallet.serialize()` additionally drops each note's `commitment`, so notes restored from it come back from `verifyUtxos` (§5.2) as `skipped`. Use `transfer` for a shielded send and `fullWithdraw` / `partialWithdraw` to exit the pool. ### 5.11 Fees Fees are enforced on-chain by the program from each pool's `PoolConfig`; `transact` reads the live config before building a fee-bearing proof, so you do not compute the fee yourself. The helpers below use the deployed SOL-pool defaults (`5_000_000` lamports fixed + `3 / 1000`): ```ts const FIXED_FEE_LAMPORTS: number; // 5_000_000 const MIN_DEPOSIT_LAMPORTS: number; // 10_000_000 const VARIABLE_FEE_NUMERATOR: number; // 3 const VARIABLE_FEE_DENOMINATOR: number;// 1000 const VARIABLE_FEE_RATE: number; // 0.003 // SOL pool. These four functions are the entire fee surface the SDK exports. function calculateFee(amountLamports: number): number; // fixed + variable function calculateFeeBigint(amountLamports: bigint): bigint; // same, bigint function isWithdrawAmountSufficient(amountLamports: bigint): boolean; function getDistributableAmount(amountLamports: number): number; // Formatting function formatAmount(lamports: number, decimals?: number): string; function parseAmount(sol: string): number; ``` There is NO SPL fee helper. USDC and USDT pools charge `450_000` base units fixed (0.45 token at 6 decimals) plus the same `3 / 1000` variable fee in the withdrawn token, and the program reads the effective values from the `pool_config` PDA; minimum SPL deposit is `1_000_000` base units (1.00). Compute an SPL fee yourself, or read it back from the transaction result. Do not invent a `calculateSpl*` or Q64 helper: none exists. See `/protocol/fee-model`. ### 5.12 Errors ```ts class RootNotFoundError extends Error {} function isRootNotFoundError(error: unknown): boolean; const ShieldPoolErrors: Record; // maps 0x1000+ program error codes to human strings function parseError(error: unknown): UserFriendlyError; function parseTransactionError(error: any): string; function formatErrorForLogging(error: unknown): string; function parseRelayErrorResponse(text: string): { isRootNotFound: boolean; currentRoot?: string }; ``` ### 5.13 Network + logging + storage + PDAs ```ts function detectNetworkFromRpcUrl(rpcUrl?: string): Network; function getRpcUrlForNetwork(network: Network): string; function isValidRpcUrl(url: string): boolean; function getExplorerUrl(signature: string, network?: Network): string; function getAddressExplorerUrl(address: string, network?: Network): string; function createLogger(module: string): Logger; function setDebugMode(enabled: boolean): void; function formatSol(lamports: number | bigint): string; const sdkLogger: Logger; // StorageAdapter stores `CloakNote` records and a `CloakKeyPair`. It does NOT store `Utxo` // objects, and it does not accept the bytes `serializeUtxo` returns; those are your own store's // problem (§9.3). interface StorageAdapter { saveNote(note: CloakNote): Promise | void; loadAllNotes(): Promise | CloakNote[]; updateNote(commitment: string, updates: Partial): Promise | void; deleteNote(commitment: string): Promise | void; clearAllNotes(): Promise | void; saveKeys(keys: CloakKeyPair): Promise | void; loadKeys(): Promise | CloakKeyPair | null; deleteKeys(): Promise | void; } class MemoryStorageAdapter implements StorageAdapter {} // in-process; lost on reload class LocalStorageAdapter implements StorageAdapter { constructor(notesKey?: string, keysKey?: string); // defaults: "cloak_notes", "cloak_wallet_keys" } function getShieldPoolPDAs(programId?: Address, mint?: Address): { pool: Address; merkleTree: Address; vaultAuthority: Address; treasury: Address; }; function getNullifierPDA(poolPubkey: Address, nullifier: Uint8Array | Buffer, programId?: Address): [PublicKey, number]; function getSwapStatePDA(poolPubkey: Address, nullifier: Uint8Array | Buffer, programId?: Address): [PublicKey, number]; ``` ### 5.14 Pending operations persistence (browser-only) ```ts function savePendingDeposit(p: PendingDeposit): void; function loadPendingDeposits(): PendingDeposit[]; function updatePendingDeposit(commitment: string, updates: Partial): void; function removePendingDeposit(commitment: string): void; function clearPendingDeposits(): void; function savePendingWithdrawal(w: PendingWithdrawal): void; function loadPendingWithdrawals(): PendingWithdrawal[]; function updatePendingWithdrawal(requestId: string, updates: Partial): void; function removePendingWithdrawal(requestId: string): void; function clearPendingWithdrawals(): void; function hasPendingOperations(): boolean; function getPendingOperationsSummary(): { deposits: PendingDeposit[]; withdrawals: PendingWithdrawal[]; totalPending: number; }; function cleanupStalePendingOperations(maxAgeMs?: number): { removedDeposits: number; removedWithdrawals: number; }; ``` --- ## 6. Copy-paste recipes (Node/server form by default, browser form on every flow) **Read this before copying any recipe in section 6.** Every recipe below is written in the NODE / SERVER form, and `depositorKeypair: sender` is the field that makes it one. It is NOT the browser form. A wallet adapter holds no secret key and can never produce a `Keypair`, so a recipe pasted verbatim into browser code is code that cannot run. Each recipe therefore carries its own browser block: never infer a recipe's signing shape from a neighbouring one. The swap is always the same one field: - Relay-submitted flows (private send, withdraw, swap): Node `depositorKeypair: sender` -> browser `signMessage: wallet.signMessage!` plus `walletPublicKey: getPublicKey(wallet)`. - Deposit (`externalAmount > 0n`, signed by the user straight to chain): Node `depositorKeypair: sender` -> browser `signTransaction: wallet.signTransaction!` plus `signMessage: wallet.signMessage!` plus `depositorPublicKey: getPublicKey(wallet)`. `signMessage` is required in the browser on EVERY flow, deposits included, because the mandatory viewing-key registration signs a challenge before anything else happens (invariant 7). Guard on `wallet.signMessage` being present before offering the action, and never mix a `depositorKeypair` with a different `walletPublicKey`: they are two names for the same end user, and splitting them throws. `relayUrl` has no default and is REQUIRED on every recipe here, deposits included. Omit it and the call throws `Viewing key registration is mandatory: relayUrl is required.` before any network call. Pass the allowlisted origin by name (§1); never type a host. All recipes assume you created: ```ts import { CLOAK_PROGRAM_ID, CLOAK_PRODUCTION_RELAY_URL, getPublicKey } from "@cloak.dev/sdk"; import { createCloakRpc } from "@cloak.dev/sdk"; const connection = createCloakRpc(process.env.SOLANA_RPC_URL!); const programId = CLOAK_PROGRAM_ID; const relayUrl = CLOAK_PRODUCTION_RELAY_URL; // Node / server: `sender` is a Keypair. // Browser: `wallet` is the object from useWallet(); see §4b. // YOUR durable note store. Every recipe below writes through it; the SDK ships nothing that plays // this role for `Utxo` bytes (`StorageAdapter` is a different boundary, §5.13). Back it with // something that survives a process restart, and write BEFORE reporting success. declare function saveNoteBytes(bytes: Uint8Array): Promise; declare function saveSwapRefund(refund: { privateKey: string; publicKey: string; blinding: string; derivedFromNk: boolean; }): Promise; ``` ### 6.1 Deposit into a fresh UTXO (SOL) ```ts import { NATIVE_SOL_MINT, createUtxo, createZeroUtxo, generateUtxoKeypair, getNkFromUtxoPrivateKey, serializeUtxo, transact, } from "@cloak.dev/sdk"; const amount = 1_000_000_000n; // 1 SOL const utxoKeypair = await generateUtxoKeypair(); const depositUtxo = await createUtxo(amount, utxoKeypair, NATIVE_SOL_MINT); const padding = await createZeroUtxo(); const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey); const depositResult = await transact( { inputUtxos: [padding], outputUtxos: [depositUtxo], externalAmount: amount, // > 0 => deposit depositor: sender.publicKey, }, { connection, programId, relayUrl, // required even here; the viewing-key gate runs first depositorKeypair: sender, // NODE ONLY chainNoteViewingKeyNk: nk, onProgress: (s) => console.log("deposit:", s), onProofProgress: (p) => console.log("proof", p), }, ); console.log("tx", depositResult.signature); console.log("leaf_index", depositResult.outputUtxos[0].index); // This note was built with createUtxo, so its blinding is raw randomness and no scan rebuilds it. // The returned UTXO already carries its leaf index; persist it as it stands. await saveNoteBytes(serializeUtxo(depositResult.outputUtxos[0])); ``` **Browser form of this same deposit.** A deposit is signed by the user's wallet and submitted straight to chain, so it is the one flow that needs `signTransaction` as well as `signMessage`: ```ts import { getPublicKey, serializeUtxo, transact } from "@cloak.dev/sdk"; const depositResult = await transact( { inputUtxos: [padding], outputUtxos: [depositUtxo], externalAmount: amount, depositor: getPublicKey(wallet), }, { connection, programId, relayUrl, signTransaction: wallet.signTransaction!, // signs the deposit transaction signMessage: wallet.signMessage!, // signs the viewing-key challenge depositorPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, }, ); await saveNoteBytes(serializeUtxo(depositResult.outputUtxos[0])); // same rule here. ``` To make this deposit recoverable from `nk` alone later, build the output with `createRecoverableDepositUtxo` and pass the salt it returns as `chainNoteSalt` (§5.5). Both forms above draw a random salt, which leaves the note discoverable only from your own storage. ### 6.2 Full withdraw (spend the entire shielded balance) ```ts import { fullWithdraw } from "@cloak.dev/sdk"; const withdrawResult = await fullWithdraw( [depositResult.outputUtxos[0]], recipient.publicKey, { connection, programId, relayUrl, depositorKeypair: sender, // NODE ONLY; also signs the viewing-key challenge walletPublicKey: sender.publicKey, chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, onProgress: (s) => console.log("withdraw:", s), }, ); console.log("withdraw sig", withdrawResult.signature); ``` **Browser form of this same withdrawal.** A withdrawal is relay-submitted: no `Keypair`, no `signTransaction`, and the wallet prompts EXACTLY ONCE no matter how many times the network is retried. ```ts import { fullWithdraw, getPublicKey } from "@cloak.dev/sdk"; const withdrawResult = await fullWithdraw( [depositResult.outputUtxos[0]], recipientPublicKey, { connection, programId, relayUrl, signMessage: wallet.signMessage!, // authenticates the request; prompts once walletPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, }, ); ``` The signed request is good for 285 usable seconds (§5.8). If the user leaves the approval dialog open longer than that, map the rejection through `explainRelayAuthRejection` and ask again. **Both forms above pass ONE input note, which is the only shape with nothing to persist.** Passing three or more inputs makes `fullWithdraw` consolidate them on chain first, two at a time, and a throw partway through strands the merged balance with no result to save (§5.2). Consolidate deliberately with your own `transact` calls, persisting each merged output, or accept the risk knowingly and watch `onProgress` for `Consolidating notes (n remaining)...`. ### 6.3 Partial withdraw (keep a shielded change UTXO) ```ts import { partialWithdraw, serializeUtxo } from "@cloak.dev/sdk"; const withdrawAmount = 500_000_000n; // 0.5 SOL const result = await partialWithdraw( [depositResult.outputUtxos[0]], recipient.publicKey, withdrawAmount, { connection, programId, relayUrl, depositorKeypair: sender, // NODE ONLY walletPublicKey: sender.publicKey, chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, }, ); // result.outputUtxos[0] is the new shielded change UTXO (remainder), and this write is the only // thing that keeps it spendable. Do it before you report success. await saveNoteBytes(serializeUtxo(result.outputUtxos[0])); ``` **Browser form of this same partial withdrawal.** Relay-submitted, so the keypair is replaced, not supplemented: ```ts import { getPublicKey, partialWithdraw, serializeUtxo } from "@cloak.dev/sdk"; const result = await partialWithdraw( [depositResult.outputUtxos[0]], recipientPublicKey, withdrawAmount, { connection, programId, relayUrl, signMessage: wallet.signMessage!, walletPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, }, ); await saveNoteBytes(serializeUtxo(result.outputUtxos[0])); // the change note. Same rule here. ``` **Persist `result.outputUtxos[0]` before you do anything else, in either form.** A change note is the one thing NOTHING recovers: its blinding comes from `randomFieldElement()` and is written nowhere on chain, so scanning will never bring it back (§5.5). Store it with `serializeUtxo` (§5.2) the moment the call returns. ### 6.4 Shield-to-shield transfer / private send (publicAmount = 0) Relay-submitted, so this recipe has a browser form and the block below is NOT it. In the browser this flow uses `signMessage` + `walletPublicKey`; there is no `depositorKeypair` in browser code. ```ts import { NATIVE_SOL_MINT, createUtxo, serializeUtxo, transact } from "@cloak.dev/sdk"; const transferAmount = 1_000_000_000n; const changeAmount = senderShieldedUtxo.amount - transferAmount; const recipientOutput = await createUtxo(transferAmount, recipientUtxoKeypair, NATIVE_SOL_MINT); const changeOutput = await createUtxo(changeAmount, senderUtxoKeypair, NATIVE_SOL_MINT); const result = await transact( { inputUtxos: [senderShieldedUtxo], outputUtxos: [recipientOutput, changeOutput], externalAmount: 0n, // shield-to-shield }, { connection, programId, relayUrl, depositorKeypair: sender, // NODE ONLY walletPublicKey: sender.publicKey, chainNoteViewingKeyNk: senderNk, recipientViewingPublicKey, // see "make the note discoverable" below cachedMerkleTree: senderCachedTree, }, ); // outputUtxos[1] is YOUR change (outputs were [recipientOutput, changeOutput]). Nothing on chain // carries its blinding, so this write is the only thing that keeps it spendable. await saveNoteBytes(serializeUtxo(result.outputUtxos[1])); ``` **Browser form of this same private send.** Same call, same params, one field swapped. The wallet prompts EXACTLY ONCE; a send never re-prompts on retry. ```ts import { getPublicKey, serializeUtxo, transact } from "@cloak.dev/sdk"; const result = await transact( { inputUtxos: [senderShieldedUtxo], outputUtxos: [recipientOutput, changeOutput], externalAmount: 0n, }, { connection, programId, relayUrl, signMessage: wallet.signMessage!, // authenticates /transact; prompts once walletPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: senderNk, recipientViewingPublicKey, cachedMerkleTree: senderCachedTree, }, ); await saveNoteBytes(serializeUtxo(result.outputUtxos[1])); // your change note. Same rule here. ``` `transfer(inputUtxos, recipientPubkey, amount, options)` (§5.3) wraps the same flow when you have the recipient's UTXO public key as a `bigint` and want the SDK to build both outputs. Its `options` argument is the identical `TransactOptions`, so the same Node-vs-browser swap applies. **Make the note discoverable, or the recipient cannot spend it.** Pass `recipientViewingPublicKey: deriveViewingKeyFromNk(recipientNk).publicKey` (hex or bytes) in `TransactOptions`. The SDK then seals `{amount, blinding}` of output 0 to that key and ships it as `recipient_delivery_notes`, which is what the recipient's `scanTransactions` later returns in `ScanResult.deliveredNotes` (§5.5). Leave it out and the send still succeeds, but the recipient has no way to find the note from chain and it must be handed over out of band. And persist `changeOutput` yourself, in either form. Nothing recovers a change note (§5.5). ### 6.5 Fast send (deposit + full withdraw in one user action) This is the ONE shape in section 6 that needs no note storage, and only because it is written the way it is: exactly one deposit note goes in, `fullWithdraw` spends it in the same process, and a one-input full withdrawal leaves no change. Every other recipe here writes a note before it reports success. Do NOT generalise the recipe to a wallet's whole note set: pass three or more inputs and `fullWithdraw` consolidates them on chain first, and a throw partway through strands the merged balance with nothing to persist (§5.2). This shape stays storage-free only at one or two inputs. ```ts import { NATIVE_SOL_MINT, createUtxo, createZeroUtxo, fullWithdraw, generateUtxoKeypair, getNkFromUtxoPrivateKey, serializeUtxo, transact, } from "@cloak.dev/sdk"; const amount = 1_000_000_000n; const kp = await generateUtxoKeypair(); const utxo = await createUtxo(amount, kp, NATIVE_SOL_MINT); const nk = getNkFromUtxoPrivateKey(kp.privateKey); const dep = await transact( { inputUtxos: [await createZeroUtxo()], outputUtxos: [utxo], externalAmount: amount, depositor: sender.publicKey }, { connection, programId, relayUrl, depositorKeypair: sender, chainNoteViewingKeyNk: nk }, // NODE ONLY ); // Persist before the withdraw. transact returns only after the deposit is confirmed // on chain, so a throwing fullWithdraw exits with SOL shielded and the blinding gone. // Same rule as the browser form below; the process being short-lived is not a defence. await saveNoteBytes(serializeUtxo(dep.outputUtxos[0])); const wd = await fullWithdraw([dep.outputUtxos[0]], recipient.publicKey, { connection, programId, relayUrl, depositorKeypair: sender, // NODE ONLY walletPublicKey: sender.publicKey, chainNoteViewingKeyNk: nk, cachedMerkleTree: dep.merkleTree, }); ``` **Browser form.** Two different swaps in one flow, because the two legs submit differently: the deposit is signed to chain, the withdraw goes through the relay. That is two wallet prompts for the deposit (`signTransaction` for the transaction, `signMessage` for the viewing-key challenge, the latter only on first use per wallet) and exactly one more for the withdraw. ```ts import { createZeroUtxo, fullWithdraw, getPublicKey, serializeUtxo, transact, } from "@cloak.dev/sdk"; const dep = await transact( { inputUtxos: [await createZeroUtxo()], outputUtxos: [utxo], externalAmount: amount, depositor: getPublicKey(wallet) }, { connection, programId, relayUrl, signTransaction: wallet.signTransaction!, signMessage: wallet.signMessage!, depositorPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, }, ); // Persist BEFORE the second leg. In a browser the process is a tab, and the withdraw // below opens a wallet dialog: if the tab closes there, this note is the only claim on // the funds already in the pool. saveNoteBytes is your storage, not an SDK export. await saveNoteBytes(serializeUtxo(dep.outputUtxos[0])); const wd = await fullWithdraw([dep.outputUtxos[0]], recipientPublicKey, { connection, programId, relayUrl, signMessage: wallet.signMessage!, walletPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, cachedMerkleTree: dep.merkleTree, }); ``` ### 6.6 Swap SOL -> SPL (with shielded change) ```ts import { NATIVE_SOL_MINT, serializeUtxo, swapWithChange } from "@cloak.dev/sdk"; import { address } from "@cloak.dev/sdk"; import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from "@solana-program/token"; import { createJupiterApiClient } from "@jup-ag/api"; const swapAmount = 250_000_000n; // 0.25 SOL const outputMint = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"); // USDC const [recipientAta] = await findAssociatedTokenPda({ mint: outputMint, owner: sender.address, tokenProgram: TOKEN_PROGRAM_ADDRESS, }); // Quote (Jupiter) -> pick minOut: const jup = createJupiterApiClient(); const quote = await jup.quoteGet({ inputMint: NATIVE_SOL_MINT.toBase58(), // swap input is wSOL-locked outputMint: outputMint.toBase58(), amount: Number(swapAmount), slippageBps: 1500, }); const minOut = BigInt(quote.otherAmountThreshold); const swapResult = await swapWithChange( depositResult.outputUtxos, // inputs (must sum to >= swapAmount) swapAmount, outputMint, recipientAta, minOut, { connection, programId, relayUrl, depositorKeypair: sender, // NODE ONLY walletPublicKey: sender.publicKey, chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, swapSlippageBps: 1500, swapStatusMaxAttempts: 60, swapStatusDelayMs: 2000, }, sender.publicKey, // so the SDK can create ATA if missing ); console.log("swap sig", swapResult.signature); console.log("swapStatePda", swapResult.swapStatePda); // TWO pieces of the user's own money exist only in that returned object. Write both now. await saveNoteBytes(serializeUtxo(swapResult.outputUtxos[0])); // shielded change note await saveSwapRefund(swapResult.refund); // timeout-refund secret ``` **Browser form of this same swap.** Relay-submitted, so the same one-field swap, with one extra thing to plan for in the UI: a swap is the ONLY flow that can re-prompt the wallet, because a route can be re-quoted and re-signed. `maxWalletApprovals` caps how many times (default 5, floored at 1). Sends and withdrawals never do this. ```ts import { getPublicKey, serializeUtxo, swapWithChange } from "@cloak.dev/sdk"; const swapResult = await swapWithChange( depositResult.outputUtxos, swapAmount, outputMint, recipientAta, minOut, { connection, programId, relayUrl, signMessage: wallet.signMessage!, walletPublicKey: getPublicKey(wallet), chainNoteViewingKeyNk: nk, cachedMerkleTree: depositResult.merkleTree, swapSlippageBps: 1500, maxWalletApprovals: 5, // swaps only; tell the user they may be asked more than once }, getPublicKey(wallet), // so the SDK can create the ATA if missing ); await saveNoteBytes(serializeUtxo(swapResult.outputUtxos[0])); // change note await saveSwapRefund(swapResult.refund); // timeout-refund secret ``` **Persist `swapResult.outputUtxos[0]` AND `swapResult.refund` before you do anything else, in either form.** A swap hands back two pieces of the user's own money that exist only in that returned object. `outputUtxos[0]` is the shielded change note whenever the inputs did not sum to exactly `swapAmount`, which is the case in both recipes above, and a change note is the one thing NOTHING recovers: its blinding comes from `randomFieldElement()` and is written nowhere on chain, so scanning will never bring it back (§5.5). The `refund` object is the secret that claims the principal back if the swap times out before it executes (§5.3). Store the change note with `serializeUtxo` (§5.2) and the `refund` object beside it, the moment the call returns. Both recipes above pass `chainNoteViewingKeyNk: nk`, so the refund secret is derived from that `nk` and `discoverSwapRefunds` (§5.5) can rebuild it later from key material alone. That is a backstop, not a substitute for persisting it. ### 6.7 Compliance history scan + CSV export ```ts import { scanTransactions, toComplianceReport, formatComplianceCsv, getNkFromUtxoPrivateKey, } from "@cloak.dev/sdk"; import { writeFile } from "node:fs/promises"; const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey); const scan = await scanTransactions({ connection, programId, viewingKeyNk: nk, batchSize: 50, walletPublicKey: sender.publicKey.toBase58(), onStatus: (s) => console.log("scan:", s), onProgress: (done, total) => console.log(`scan progress ${done}/${total}`), }); console.log("summary", scan.summary); const report = toComplianceReport(scan); const csv = formatComplianceCsv(report); await writeFile("cloak-history.csv", csv, "utf8"); ``` Incremental re-scan (only fetch new transactions since the last run): ```ts import { scanTransactions } from "@cloak.dev/sdk"; const delta = await scanTransactions({ connection, programId, viewingKeyNk: nk, untilSignature: scan.lastSignature, // resume cursor }); ``` ### 6.8 Viewing-key registration (advanced) For standard app integrations, keep the SDK-managed registration flow and avoid manual wiring. Only use direct registration helpers for custom/operator pipelines. ### 6.9 Fee math ```ts import { calculateFeeBigint, isWithdrawAmountSufficient } from "@cloak.dev/sdk"; // SOL, 1.0 SOL gross → fee = 5_000_000 + 3_000_000 = 8_000_000 lamports, net 992_000_000 const solGross = 1_000_000_000n; const solFee = calculateFeeBigint(solGross); // 5_000_000 fixed + 0.3 % variable const solNet = solGross - solFee; if (!isWithdrawAmountSufficient(solGross)) throw new Error("below the SOL fee floor"); // USDC / USDT, 100.000000 USDC gross. No SDK helper exists for SPL: the fixed component is a // program constant of 450_000 base units (0.45 token at 6 decimals), charged on-chain from the // pool's PoolConfig alongside the same 0.3 % variable fee. // fee = 450_000 + 100_000_000 * 3 / 1000 = 750_000 base units (0.75 USDC), net 99_250_000 const usdcGross = 100_000_000n; const usdcFee = 450_000n + (usdcGross * 3n) / 1000n; const usdcNet = usdcGross - usdcFee; ``` The program computes and deducts the fee; these numbers are for display. Never describe them as relay or SDK fees. ### 6.10 Metadata encryption (dual envelope) ```ts import { encryptTransactionMetadata, decryptTransactionMetadata, deriveViewingKeyFromUtxoPrivateKey, } from "@cloak.dev/sdk"; const vk = deriveViewingKeyFromUtxoPrivateKey(utxoKeypair.privateKey); const compliancePublic = await fetchCompliancePublic(); // your own source of truth const bundle = await encryptTransactionMetadata( { txType: "withdraw", commitment, amount: 1000000000, recipient: recipient.publicKey.toBase58(), timestamp: Date.now() }, vk.publicKey, compliancePublic, { userPubkey: sender.publicKey }, ); // Later, decrypt for the user: const decrypted = await decryptTransactionMetadata(bundle.encrypted_user, vk.privateKey); ``` ### 6.11 Tree helpers + stale-root preflight (advanced) Use these helpers for operator-grade diagnostics and custom infrastructure. They are not required for standard app integrations. ### 6.12 On-chain Merkle proof fallback ```ts import { computeProofFromChain, getShieldPoolPDAs, NATIVE_SOL_MINT } from "@cloak.dev/sdk"; const pdas = getShieldPoolPDAs(programId, NATIVE_SOL_MINT); const proof = await computeProofFromChain(connection, pdas.merkleTree, leafIndex, true); // proof: { pathElements, pathIndices, root } ``` Pass the resulting tree into `TransactOptions.cachedMerkleTree` or set `useChainForMerkle: true` to force on-chain reconstruction inside the transact path. ### 6.13 Error handling + retry for stale roots ```ts import { fullWithdraw, isRootNotFoundError, parseError } from "@cloak.dev/sdk"; for (let attempt = 0; attempt < 3; attempt++) { try { await fullWithdraw(inputUtxos, recipient, options); break; } catch (err) { if (isRootNotFoundError(err)) { const wait = 500 * 2 ** attempt; await new Promise(r => setTimeout(r, wait)); continue; } const friendly = parseError(err); console.error("withdraw failed:", friendly); throw err; } } ``` This loop is safe to re-enter only while `inputUtxos` holds one or two notes. With three or more, the first attempt may already have consolidated some of them on chain, so the same array is no longer the wallet's live state and a retry spends notes that are gone (§5.2). Guardrail 9 applies: the SDK transaction paths already retry stale roots, so do not add this loop by default. --- ## 7. Recipe index for common flows Use section 6 directly as your public, copy-paste integration source. Every recipe there is written in the Node/server form and carries its own browser form beside it; read the browser block, do not adapt the Node one by hand. - Deposit a fresh shielded UTXO: section 6.1. - Withdraw flows: sections 6.2 (full) and 6.3 (partial/change), including why a full withdrawal is storage-free at one or two input notes and not at three or more. - Private shield-to-shield transfer (private send): section 6.4, including how to make the note discoverable by the recipient. - Fast-send user flow: section 6.5. - SOL -> SPL swap with shielded change: section 6.6, including the two secrets a swap hands back that must be persisted (the change note and `UtxoSwapResult.refund`). - Recovering a swap refund whose secret was never persisted: `discoverSwapRefunds`, section 5.5. - Compliance scan and CSV export: section 6.7. - Viewing-key registration: section 6.8. - Fee modeling (SOL + SPL): section 6.9. - Metadata encryption: section 6.10. - Merkle reliability helpers and fallback proof path: sections 6.11 and 6.12. - Retry/error strategy for stale roots: section 6.13. --- ## 8. AI generation guardrails (hard rules) 1. Never print/log secrets: spend keys (`skSpend`), viewing keys (`nk`, private bytes), UTXO `privateKey`, `blinding`, note payloads, raw `sign_message` outputs, `cloakKeys`, or relayer auth tokens. 2. Never hand-pack Groth16 public inputs. Let `transact` / `swapUtxo` build the proof and the 264-byte public inputs for you. 3. Never bypass `viewingKeyNk` when calling `scanTransactions`: it cannot return anything without it. 4. Never change `externalAmount` semantics; treat deposit/withdraw/transfer as three distinct modes derived from that field. 5. Never call `transact` with raw `number` amounts. Always `BigInt(...)` at API boundaries. 6. Use SDK defaults for program and circuits in standard integrations. `relayUrl` has no default and must be passed on every flow, as an allowlisted origin. Never generate `relayUrl: ""` together with `enforceViewingKeyRegistration: false` for a send, withdrawal or swap: that pairing is what makes `""` mean direct submission, and it submits under the user's own key, publicly linking the transaction. 7. Prefer `scanTransactions` + `toComplianceReport` for user history UX. Do not re-invent compliance endpoints. 8. For mutating paths in the browser, prefer the wallet adapter (`signTransaction` / `signMessage`). Reserve `depositorKeypair` for Node scripts. 9. Do not add manual stale-root retry loops by default in app scripts; SDK transaction paths already handle these retries. 10. Cache `TransactResult.merkleTree` across operations in the same user session to avoid redundant tree rebuilds. 11. For one-file scripts, accept ` ` in CLI and read signer from `KEYPAIR_PATH`. 12. Do not generate `SENDER_PRIVATE_KEY` or `AMOUNT_SOL` + `parseFloat(...)` patterns. 13. Do not generate `RECIPIENT_ADDRESS` / `SEND_LAMPORTS` env contracts for one-file CLI scripts. 14. For standalone script entrypoints, terminate explicitly with `process.exit(0)` on success and `process.exit(1)` on failure. 15. In BROWSER code, never generate `depositorKeypair`, `signerFromSecretKey`, or a `keypair.json` path for a send/withdraw/swap. A wallet adapter cannot supply one. Take `signMessage` and `publicKey` from `useWallet()` instead, pass `walletPublicKey: addressFromPublicKey(publicKey)` (the adapter yields a web3.js `PublicKey`; Cloak options take a Kit `Address`), and guard on `signMessage` being present before offering the action. 16. Never substitute an ephemeral, session or service-held key for the authenticated `sender`. It is the key screened for sanctions; substituting it moves screening off the actual user. 17. Do not hand-roll the request-auth scheme when `submitTransactToRelay` will do. If you do hand-roll it, use `buildRelayAuthPreimage` + `canonicalJson` and read `TRANSACT_AUTH_FIELDS` / `TRANSACT_SWAP_AUTH_FIELDS` from the package rather than retyping them. 18. Never claim an integrator must use a Cloak-operated RPC. Only the submission endpoint is pinned; the `Connection` is entirely the caller's, and any non-loopback RPC works. --- ## 9. Minimal LLM "contract" When generating Cloak integration code, produce a file-by-file plan that: 1. Declares an explicit `TransactOptions` factory (single source of truth for `connection` and signing; keep `programId` fixed to `CLOAK_PROGRAM_ID`). 2. Exposes `deposit`, `transfer`, `partialWithdraw`, `fullWithdraw`, `swap`, and `scanHistory` primitives using the functions in §5.3, §5.2, §5.5. 3. Persists notes and key material through TWO boundaries, which are not interchangeable: - **Notes.** Write `result.outputUtxos` yourself, as `serializeUtxo(...)` bytes (§5.2), in the same tick the flow returns. Do NOT route them through a `StorageAdapter`: its methods are typed on `CloakNote` (`saveNote`, `loadAllNotes`, `updateNote`, `deleteNote`), a different record shape, and the public surface has no converter between the two. Passing `serializeUtxo` bytes to `saveNote` does not type-check and does not persist a spendable note. - **Key material.** `StorageAdapter.saveKeys` / `loadKeys` (a `CloakKeyPair`) is the ready-made home, via `LocalStorageAdapter` or `MemoryStorageAdapter` (§5.13). For swaps, `UtxoSwapResult.refund` (§5.3) is a third item and must be persisted too. The full storage answer, including how the two boundaries divide, is `/sdk/wallet-integration#where-your-notes-live-between-sessions`. 4. Surfaces `onProgress` + `onProofProgress` into the UI layer. 5. Maps relay/on-chain errors through `parseError` + `isRootNotFoundError` into a small typed error union. 6. Includes a CSV export path using `formatComplianceCsv(toComplianceReport(scan))`. 7. Never exports or logs raw secrets. 8. Uses only the exact exported names listed in §5. If a name is not listed here, it is not part of the public SDK contract; treat it as unstable. --- ## 10. Version pinning note - The `transaction` circuit digests (`EXPECTED_CIRCUIT_HASHES.transaction_*`) are the ceremony pins; `DEFAULT_TRANSACTION_CIRCUITS_URL` is derived from `TRANSACTION_CIRCUITS_VERSION` (`0.2.0`) so URL and digests cannot drift. Never hand-write a circuits URL; use `resolveCircuitsBase()`. - `DEFAULT_CIRCUITS_URL` is an alias of `DEFAULT_TRANSACTION_CIRCUITS_URL`, kept so older imports keep resolving: same value, same ceremony bundle, never `null` in this build. Either name is safe to read. The pre-ceremony `withdraw_regular` / `withdraw_swap` circuits, and the `CloakSDK` class that loaded them, were removed in 0.2.0; `setCircuitsPath` overrides the base for the ceremony `transaction` bundle only, and the deployed program rejects proofs from any other bundle. - The SDK currently targets program `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`. Set `programId` explicitly in non-default deployments.