> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloak.ag/llms.txt
> Use this file to discover all available pages before exploring further.

# Solana wallet adapter

> Integrate Cloak SDK with Solana wallet-adapter in web apps

> [!NOTE]
>
> If you use `createCloak`, it takes the connected wallet as it is, `createCloak({ wallet: useWallet() })`,
> along with Wallet Standard wallets, EVM wallets, Privy and more, and needs none of the wiring on this
> page. See [createCloak](https://docs.cloak.ag/sdk/create-cloak.md#the-wallets-it-takes). This page is for the free functions.

## Install

```bash theme={null}
npm install @cloak.dev/sdk@0.2.20 @solana/kit @solana/wallet-adapter-react @solana/web3.js@^1.99
```

The SDK is built on `@solana/kit`. `@solana/web3.js` is an optional peer dependency, and you need it
here: `signerFromWalletAdapter` hands the wallet a web3.js `VersionedTransaction` to sign. An app
that does not use the wallet-adapter bridge (a Wallet Standard app using `@solana/react`, say) can
skip it. See [Solana Kit integration](https://docs.cloak.ag/sdk/kit-integration.md).

Add wallet UI packages as needed:

```bash theme={null}
npm install @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets
```

## The wallet signer, and what each option is for

`signTransaction` is not an option any more. The wallet signs transactions through `signer`, a Kit
`TransactionSigner`, and `signMessage` signs the challenge that authenticates the user. Wrap the
connected adapter once with `signerFromWalletAdapter`:

```ts theme={null}
import { signerFromWalletAdapter } from "@cloak.dev/sdk";
import { useWallet } from "@solana/wallet-adapter-react";

const { publicKey, signTransaction, signMessage } = useWallet();
if (!publicKey || !signTransaction) throw new Error("Connect a wallet first.");

// `signer.address` is the wallet's Kit Address. `signer` signs the deposit transaction.
const signer = signerFromWalletAdapter({ publicKey, signTransaction, signMessage });
const walletPublicKey = signer.address;
```

What each option does:

| Option | Signs | Needed for |
| - | - | - |
| `signer` | the Solana transaction, and (if the wallet can) the auth challenge | deposits, which the wallet submits directly |
| `signMessage` | the request preimage and the viewing-key registration challenge | private sends, withdrawals and swaps, which are submitted for you |
| `walletPublicKey` | nothing: it names the user | the request's authenticated sender; must be the end user's own wallet |

A deposit needs `signer` plus a way to sign the viewing-key registration challenge, which is
`signMessage` or the `signer` itself. Every send, withdrawal and swap authenticates the user, so it
needs `signMessage` (or a message-capable or hardware `signer`) and `walletPublicKey`. When both
`signMessage` and `signer` are present, `signMessage` is the one used. Full contract, including the
approval window and prompt counts: [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md).

### Wallets without `signMessage`

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

### Bundlers and `@solana/web3.js`

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

```ts theme={null}
import { VersionedTransaction } from "@solana/web3.js";
import { signerFromWalletAdapter, type LegacyWalletAdapter } from "@cloak.dev/sdk";

export function walletSigner(adapter: LegacyWalletAdapter) {
  return signerFromWalletAdapter(adapter, { web3: { VersionedTransaction } });
}
```

## Where the user's keys live

Every spend flow (`transfer`, `partialWithdraw`, `fullWithdraw`, `swapUtxo`, `swapWithChange`,
`sweepToWalletKey`) requires two keys that belong to the user, not to the wallet adapter:

* `ownerUtxoKeypair`, the long-lived Cloak keypair that owns the notes.
* `nk` (passed as `chainNoteViewingKeyNk`), the view-only key that finds notes and decrypts chain
  notes. It can never spend.

Derive both from one 32-byte seed. Generate the seed once with `generateMasterSeed().seed` and store it
the way you would store a private key: a random key that is lost loses the notes.

```ts theme={null}
import {
  deriveSpendKey,
  deriveUtxoKeypairFromSpendKey,
  getNkFromUtxoPrivateKey,
} from "@cloak.dev/sdk";

// `seed`: 32 bytes from generateMasterSeed().seed, created once and kept in your app's secure storage.
export async function deriveUserKeys(seed: Uint8Array) {
  const { sk_spend } = deriveSpendKey(seed);
  const ownerUtxoKeypair = await deriveUtxoKeypairFromSpendKey(sk_spend);
  const nk = getNkFromUtxoPrivateKey(ownerUtxoKeypair.privateKey); // view-only
  return { ownerUtxoKeypair, nk };
}
```

Derive them again at the start of each session, hold them in memory, and pass both on every call,
deposits included. The wallet signs; the seed-derived keys own the money.

## UTXO integration with wallet signing

A browser deposit builds a recoverable output note and passes the wallet fields in `TransactOptions`:

```ts theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  NATIVE_SOL_MINT,
  createCloakRpc,
  createRecoverableDepositUtxo,
  createZeroUtxo,
  serializeUtxo,
  transact,
  type UtxoKeypair,
} from "@cloak.dev/sdk";
import type { TransactionSigner } from "@solana/kit";

declare const connection: ReturnType<typeof createCloakRpc>;
// Your own durable store: the SDK keeps no notes. It must have committed before it resolves.
declare function persistNotes(noteBytes: Uint8Array[]): Promise<void>;

export async function depositSol(
  signer: TransactionSigner, // from signerFromWalletAdapter(...)
  signMessage: ((message: Uint8Array) => Promise<Uint8Array>) | undefined,
  ownerUtxoKeypair: UtxoKeypair,
  nk: Uint8Array,
  amountLamports: bigint, // at least 0.01 SOL (MIN_DEPOSIT_LAMPORTS)
) {
  const { utxo, noteSalt } = await createRecoverableDepositUtxo({
    amount: amountLamports,
    viewingKeyNk: nk,
    ownerUtxoKeypair,
    mintAddress: NATIVE_SOL_MINT,
  });

  const result = await transact(
    {
      inputUtxos: [await createZeroUtxo(NATIVE_SOL_MINT)],
      outputUtxos: [utxo],
      externalAmount: amountLamports,
      depositor: signer.address,
    },
    {
      connection,
      programId: CLOAK_PROGRAM_ID,
      relayUrl: CLOAK_PRODUCTION_RELAY_URL,
      signer, // wallet signs the deposit transaction
      signMessage, // signs the registration challenge; omit on a hardware wallet
      depositorPublicKey: signer.address,
      walletPublicKey: signer.address, // same key; becomes the authenticated sender
      ownerUtxoKeypair,
      chainNoteViewingKeyNk: nk,
      chainNoteSalt: noteSalt,
    },
  );

  // `result.outputUtxos` is the money this deposit created, and the SDK stores none of it.
  // Write the bytes down before you report success. Zero-amount outputs are circuit
  // padding, so drop them.
  // See "Where your notes live between sessions" below.
  await persistNotes(
    result.outputUtxos.filter((out) => out.amount > 0n).map(serializeUtxo),
  );
  return result;
}
```

Check that the wallet can authenticate before you offer a send or withdraw action: either
`signMessage` is present, or you are on the `signer` (transaction-based) path above. Finding out
after a Groth16 proof has already been computed is a poor experience.

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

```typescript theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  NATIVE_SOL_MINT,
  address,
  createCloakRpc,
  createRecoverableDepositUtxo,
  createZeroUtxo,
  fullWithdraw,
  isRootNotFoundError,
  serializeUtxo,
  transact,
  type UtxoKeypair,
} from "@cloak.dev/sdk";
import type { TransactionSigner } from "@solana/kit";

// Your own durable store. The SDK ships nothing that plays this role.
declare function saveNoteBytes(bytes: Uint8Array): Promise<void>;

const connection = createCloakRpc(process.env.SOLANA_RPC_URL!);
const relayUrl = CLOAK_PRODUCTION_RELAY_URL;
const programId = CLOAK_PROGRAM_ID;

async function sendWithWalletAdapter({
  signer,
  signMessage,
  ownerUtxoKeypair,
  nk,
  recipientAddress,
  amountLamports,
}: {
  signer: TransactionSigner; // signerFromWalletAdapter(...); signer.address is the wallet's Kit Address
  signMessage?: (msg: Uint8Array) => Promise<Uint8Array>; // omit on a hardware wallet
  ownerUtxoKeypair: UtxoKeypair; // from the user's seed, see "Where the user's keys live"
  nk: Uint8Array;
  recipientAddress: string;
  amountLamports: bigint;
}) {
  const walletPublicKey = signer.address;
  const { utxo: output, noteSalt } = await createRecoverableDepositUtxo({
    amount: amountLamports,
    viewingKeyNk: nk,
    ownerUtxoKeypair,
    mintAddress: NATIVE_SOL_MINT,
  });

  const deposited = await transact(
    {
      inputUtxos: [await createZeroUtxo(NATIVE_SOL_MINT)],
      outputUtxos: [output],
      externalAmount: amountLamports,
      depositor: walletPublicKey,
    },
    {
      connection,
      programId,
      relayUrl,
      signer,
      signMessage,
      depositorPublicKey: walletPublicKey,
      walletPublicKey,
      ownerUtxoKeypair,
      chainNoteViewingKeyNk: nk,
      chainNoteSalt: noteSalt,
      onProgress: (status) => console.log("deposit", status),
      onProofProgress: (percent) => console.log("deposit proof", percent),
    },
  );

  // Persist before the withdrawal. The retry loop below can prompt the wallet three
  // times, and a tab closed at any of them leaves this note as the only claim on the
  // deposited funds. `saveNoteBytes` is your own storage, not an SDK export.
  await saveNoteBytes(serializeUtxo(deposited.outputUtxos[0]));

  const recipient = address(recipientAddress);
  let withdrawResult: Awaited<ReturnType<typeof fullWithdraw>> | undefined;

  for (let attempt = 1; attempt <= 3; attempt += 1) {
    try {
      withdrawResult = await fullWithdraw(deposited.outputUtxos, recipient, {
        connection,
        programId,
        relayUrl,
        signer,
        signMessage,
        walletPublicKey,
        ownerUtxoKeypair,
        chainNoteViewingKeyNk: nk,
        cachedMerkleTree: deposited.merkleTree,
        onProgress: (status) => console.log("withdraw", status),
        onProofProgress: (percent) => console.log("withdraw proof", percent),
      });
      break;
    } catch (error) {
      if (!isRootNotFoundError(error) || attempt === 3) throw error;
      await new Promise((resolve) => setTimeout(resolve, 1_500));
    }
  }

  if (!withdrawResult) throw new Error("withdraw did not produce a result");

  return {
    depositSignature: deposited.signature,
    withdrawSignature: withdrawResult.signature,
  };
}
```

Notes:

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

## Where your notes live between sessions

Every example above ends by feeding `deposited.outputUtxos` straight into the next call. A real
wallet cannot do that. The user closes the tab, comes back tomorrow, and something has to know what
they own.

The SDK does not persist anything for you. `transact`, `transfer`, `partialWithdraw`, `fullWithdraw`
and the swap helpers each return their new notes on `result.outputUtxos` and then forget them. That
storage boundary is explicit, and closing it is your job.

`fullWithdraw` leaves nothing shielded, so it hands back no change note when it spends one or two
notes. That is the full extent of its exemption; the next section explains why. Every other call in
that list produces a change note on every path. `swapUtxo` and `swapWithChange` additionally return
`refund` and `swapStatePda` on `UtxoSwapResult`, which is what reclaims the principal if the swap
times out before it settles; persist those two alongside the notes.

> [!WARNING]
>
> Write `result.outputUtxos` to durable storage before you report success to the user. A note is
> spendable only with its full secrets, `(amount, owner pubkey, blinding, mint)`. The spend flows
> build change with `createRecoverableChangeUtxo`, whose `blinding` is derived from your viewing key
> `nk` and a salt carried in the encrypted chain note, so a lost change note can be rebuilt by a scan
> (see [what happens if that storage is lost](#what-happens-if-that-storage-is-lost)). That scan is
> slow, and for a `transfer` it still needs you to supply the change amount, so the stored copy is the
> path your app should rely on. Notes built with plain `createUtxo`, including change from clients
> that predate recoverable change, have a random `blinding` that is published nowhere: if your only
> copy of one of those is lost, nobody can spend it.

### A withdrawal of three or more notes is not exempt

The circuit takes two inputs. `partialWithdraw`, and therefore `fullWithdraw`, which is a thin
wrapper that calls `partialWithdraw` for the whole input sum, absorbs a larger set by merging on
chain first: while more than two notes remain it spends the two smallest in a shield-to-shield
`transact` and creates one merged note in their place, repeating until two are left, and only then
builds the withdrawal itself. For `n` input notes that is `n - 2` settled merges ahead of the
withdrawal.

Each round is a real transaction. It nullifies two of your notes on chain and publishes the merged
commitment. The merged note is owned by `ownerUtxoKeypair` and built with
`createRecoverableChangeUtxo`, so its `blinding` is derived from your `nk` and the salt in that
round's chain note. You are never handed the note, because the merge is an implementation detail of
the withdrawal.

> [!WARNING]
>
> If a withdrawal of three or more notes throws part way through, the merges that already landed are
> not undone. The consumed inputs are spent, the merged note sits on chain, and the call produced no
> result, so there is nothing to persist. Exhausted stale-root retries, a rejected wallet prompt, a
> failed submission or a closed tab all reach that state. The merged value is not lost: the merged note
> is output 0 of its round and the chain note carries its amount, so `scanTransactions` with your `nk`
> returns it in `recoveredChangeNotes`. Until you run that scan, your app does not know the note
> exists, and retrying with the original inputs fails because they are already spent.

You avoid that gap more cheaply than you repair it. Keep withdrawal inputs at two notes or fewer, and
when they are not, run the merges yourself, so that each merged note is in your storage before the
next round starts.

```typescript theme={null}
import {
  createRecoverableChangeUtxo,
  serializeUtxo,
  transact,
  type TransactOptions,
  type Utxo,
  type UtxoKeypair,
} from "@cloak.dev/sdk";

// One deliberate merge round, in place of one round the withdrawal would have run
// for you. The difference is that the merged note exists in your storage first.
async function mergeTwo(
  a: Utxo,
  b: Utxo,
  ownerUtxoKeypair: UtxoKeypair,
  nk: Uint8Array,
  options: TransactOptions,
) {
  // A self-owned output must be recoverable: `transact` throws on one built with `createUtxo`.
  // The merged note is output 0, and the same salt has to reach the chain note.
  const { utxo: merged, noteSalt } = await createRecoverableChangeUtxo(
    a.amount + b.amount,
    ownerUtxoKeypair,
    nk,
    a.mintAddress,
    undefined, // let the SDK draw a fresh salt
    0,
  );

  // Write it down before submitting. Only `index` is still missing at this point,
  // and `index` is recoverable from chain state.
  await persistNotes([serializeUtxo(merged)]);

  const result = await transact(
    { inputUtxos: [a, b], outputUtxos: [merged], externalAmount: 0n },
    { ...options, ownerUtxoKeypair, chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt },
  );

  // On success, replace the provisional copy with the one carrying the leaf index.
  await persistNotes(
    result.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo),
  );
  return result;
}
```

> [!NOTE]
>
> `onProgress` is the only signal a caller gets that consolidation is happening at all. It fires
> `Consolidating notes (n remaining)...` once per round. A withdrawal that emits that string is inside
> the window above until it resolves, so treat it as a state worth surfacing rather than a spinner
> label.

### The two storage exports, and how they relate

| Export | Holds | Persists itself |
| - | - | - |
| `UtxoWallet` | the live `Utxo` set per mint, spent flags, balance, input selection | No. `serialize()` and the static `UtxoWallet.deserialize()` hand you a JSON string; where it goes is your choice |
| `LocalStorageAdapter`, `MemoryStorageAdapter` (both implement `StorageAdapter`) | `CloakNote` records, plus wallet key material through `saveKeys` / `loadKeys` | `LocalStorageAdapter` writes to browser `localStorage`, keys `cloak_notes` and `cloak_wallet_keys` by default; `MemoryStorageAdapter` keeps everything in process and loses it on reload |

`UtxoWallet` does not accept a `StorageAdapter`, and a `StorageAdapter` does not store `Utxo`
objects. They cover different halves of the problem: `UtxoWallet` is the spendable note set, the
adapters are a ready-made place to keep key material. The note set is the half that decides
solvency.

For a single note rather than a whole set, `serializeUtxo(utxo)` returns a `Uint8Array` and
`deserializeUtxo(bytes)` returns a `Promise<Utxo>`. Those are the primitives if you keep notes in
your own table or send one across a boundary; `UtxoWallet.serialize()` is the batch form.

### A note set that survives a reload

```typescript theme={null}
import {
  LocalStorageAdapter,
  UtxoWallet,
  type CloakKeyPair,
} from "@cloak.dev/sdk";

const NOTES_KEY = "myapp.cloak.notes";
const storage = new LocalStorageAdapter();

function loadWallet(): UtxoWallet {
  const saved = window.localStorage.getItem(NOTES_KEY);
  return saved ? UtxoWallet.deserialize(saved) : new UtxoWallet();
}

function saveWallet(wallet: UtxoWallet): void {
  window.localStorage.setItem(NOTES_KEY, wallet.serialize());
}

// Key material has a ready-made home on the adapter.
async function loadKeys(): Promise<CloakKeyPair | null> {
  return await storage.loadKeys();
}
```

`serialize()` writes the bigints out as strings, so a plain `JSON.stringify` over raw `Utxo` objects
is not a substitute; it throws on `bigint`. Use `serialize()` / `deserialize()` as the pair.

Then record the result of every flow, in the same tick that the flow returns:

```typescript theme={null}
import { transact } from "@cloak.dev/sdk";

const wallet = loadWallet();

const result = await transact(params, options);

for (const utxo of result.outputUtxos) {
  wallet.addUtxo(utxo, utxo.mintAddress);
}
saveWallet(wallet); // before any "done" is shown

// On a spend, the inputs stop being yours.
for (const spent of inputUtxos) {
  wallet.markSpent(spent, spent.mintAddress);
}
for (const utxo of result.outputUtxos) {
  wallet.addUtxo(utxo, utxo.mintAddress);
}
saveWallet(wallet);
```

> [!NOTE]
>
> `serialize()` carries amount, keypair, blinding, leaf `index` and the spent flag. It does not carry
> `commitment`, so notes coming back out of `deserialize()` have `commitment` undefined, and
> `verifyUtxos` reports every one of them as `skipped` rather than spent or unspent. Recompute before
> you reconcile against chain state:
>
> ```typescript theme={null}
> import { computeUtxoCommitment, NATIVE_SOL_MINT } from "@cloak.dev/sdk";
>
> for (const utxo of wallet.getUnspentUtxos(NATIVE_SOL_MINT)) {
>   if (utxo.commitment === undefined) {
>     utxo.commitment = await computeUtxoCommitment(utxo);
>   }
> }
> ```

### How `selectUtxos` consumes what storage returns

`selectUtxos(available, targetAmount)` is a pure function over an array you supply. `available` is
exactly what your store hands back: the unspent notes for one mint.

```typescript theme={null}
import { NATIVE_SOL_MINT, selectUtxos, transfer } from "@cloak.dev/sdk";

const available = wallet.getUnspentUtxos(NATIVE_SOL_MINT); // WalletUtxo[], extends Utxo
const selected = selectUtxos(available, 30_000_000n);

if (!selected) throw new Error("insufficient shielded balance");
if (selected.length > 2) throw new Error("consolidate before sending");

const sent = await transfer(selected, recipientUtxoPublicKey, 30_000_000n, walletOptions);

// The inputs are spent and your change is in `sent.outputUtxos`. Record both, and save,
// before you report the send as done.
for (const spent of selected) {
  wallet.markSpent(spent, spent.mintAddress);
}
for (const utxo of sent.outputUtxos) {
  wallet.addUtxo(utxo, utxo.mintAddress);
}
saveWallet(wallet);
```

Two things it does not do:

* It returns `null` when the balance is short, rather than throwing. A truthy check covers the
  error path.
* It does not know about the circuit's two-input limit. It can return three notes, and
  `transact` then throws `Maximum 2 input UTXOs allowed` before proving. `transfer` does not
  consolidate, so cap the selection yourself. `partialWithdraw` and `fullWithdraw` do consolidate,
  merging the two smallest notes repeatedly until two remain, and that convenience is the one
  described in
  [a withdrawal of three or more notes is not exempt](#a-withdrawal-of-three-or-more-notes-is-not-exempt):
  it settles merges whose notes you never receive, and a failure part way through leaves them
  findable only by a scan, so cap the selection before a withdrawal too and run the merges yourself.

`UtxoWallet.selectInputs(amount, mint, strategy)` does the same job against the wallet's own
bookkeeping and throws instead of returning `null`.

> [!WARNING]
>
> Do not build sends with `UtxoWallet.prepareSend` or `SimpleWallet`. `prepareSend` creates the
> recipient output from a freshly generated random keypair rather than from the recipient's key, so
> the recipient cannot spend what it produces, and `SimpleWallet.sync()` throws
> `Sync not yet implemented`. Use `transfer`, which derives the recipient output from the Cloak pubkey
> you pass it. `UtxoWallet` is sound for the parts used above: `addUtxo`, `markSpent`, `getBalance`,
> `getUnspentUtxos`, `getStats`, `selectInputs`, `serialize` and `deserialize`.

### What happens if that storage is lost

Notes built by the current SDK can mostly be rebuilt from your keys. Notes built with plain
`createUtxo` cannot. These are the parts that do and do not come back:

| What was lost | Recoverable from chain | Why |
| - | - | - |
| Change from your own withdrawal or swap, and notes merged by a withdrawal | Yes | `partialWithdraw`, its merge rounds and `swapWithChange` build change with `createRecoverableChangeUtxo`: the `blinding` is derived from your `nk` and the salt in the chain note, and change is output 0, whose amount the chain note carries. `scanTransactions` returns it in `recoveredChangeNotes`, spendable with your owner key |
| Change from your own `transfer` | Partly | The `blinding` is derived the same way, but change is output 1 and the chain note describes only output 0, so a scan cannot learn the change amount on its own. Once you supply the amount (the sender knows what was sent), the note can be rebuilt and spent |
| Change built with `createUtxo`, including change from clients that predate recoverable change | No | Its `blinding` is `randomFieldElement()` and is written nowhere on chain |
| A deposit built with `createUtxo` | No | Same missing `blinding`. It appears in history as an amount, which is not a spendable note |
| A deposit built with `createRecoverableDepositUtxo` | Yes | Secrets are a PRF of your `nk` and the salt the chain note already carries, so a cold scan can replay the derivation |
| A note someone sent you, when the sender passed `recipientViewingPublicKey` | Yes | The sender sealed `amount` and `blinding` into an on-chain envelope addressed to your viewing key |
| A swap input stranded by a timeout | Yes, if the swap was built with an `nk` | `discoverSwapRefunds` replays the same PRF shape over refund leaves. Older swaps, and any swap built without an `nk`, exist only in the `refund` field of the `UtxoSwapResult` you were handed |

`scanTransactions` is not note recovery. It decrypts your own chain notes with `nk` and produces
the history rows the site documents elsewhere: gross, fee, `netAmount` and a running balance, ready
for `toComplianceReport`. Two of its fields are the exception and are kept out of
`transactions` and `summary` because they are secrets rather than history:
`deliveredNotes` (inbound notes whose sender opted in), `recoveredDepositNotes` (your own
deposits, but only the ones built recoverably) and `recoveredChangeNotes` (your own withdrawal and
swap change, and withdrawal merges, built recoverably). Everything else it returns tells you a
deposit of 0.02 SOL happened. It does not give you something you can spend.

The reason sits in the chain note. Every transaction posts one, sealed under the writer's own
viewing key, and its plaintext is `{ timestamp, noteSalt, outAmount0, outPubkey0, isSendToSelfKey0 }`:
output 0's amount and owner pubkey, plus a salt, and no `blinding`. A chain note alone therefore
cannot rebuild a spendable note. The recoverable shapes work by deriving the `blinding` from `nk` and
that salt, so a scan can replay the derivation and check the result against a published commitment.
See
[the on-chain chain note is not a delivery channel](https://docs.cloak.ag/guides/private-transfers.md#the-on-chain-chain-note-is-not-a-delivery-channel).

`scanRecipientDeliveryNotes` recovers only notes sent to you by a sender who passed
`recipientViewingPublicKey`. It never surfaces your own change (that is `recoveredChangeNotes` on
`scanTransactions`), and it surfaces nothing at all when the sender omitted that option.

An empty scan is not proof that nothing is stranded. It means nothing in the scanned window was
derivable from this `nk`.

### Making deposits recoverable

The deposit examples above already do this. If you want a deposit that a `(rpc, programId, nk)` scan can rebuild later, build the output note
with `createRecoverableDepositUtxo` and hand the same salt to `transact`:

```typescript theme={null}
import { NATIVE_SOL_MINT, createRecoverableDepositUtxo, transact } from "@cloak.dev/sdk";

const { utxo, noteSalt } = await createRecoverableDepositUtxo({
  amount: 20_000_000n,
  viewingKeyNk: nk,
  ownerUtxoKeypair,
  mintAddress: NATIVE_SOL_MINT,
});

const deposit = await transact(
  { inputUtxos: [], outputUtxos: [utxo], externalAmount: 20_000_000n },
  { ...options, ownerUtxoKeypair, chainNoteViewingKeyNk: nk, chainNoteSalt: noteSalt },
);

// Recoverable is the fallback, not the plan. `deposit.outputUtxos` comes back with the leaf
// index already filled in, so persist it now and keep the scan as a repair tool.
for (const out of deposit.outputUtxos) {
  wallet.addUtxo(out, out.mintAddress);
}
saveWallet(wallet);
```

The salt has to reach the chain note, which is what `chainNoteSalt` does, and `transact` refuses a
`chainNoteSalt` that comes without an explicit `chainNoteViewingKeyNk`. Recovered notes then appear
on `scanTransactions(...).recoveredDepositNotes`, in spendable form, authenticated by recomputing a
commitment the deposit actually published.

Pick one `nk` per wallet and use the same value in both places, at deposit time as
`chainNoteViewingKeyNk` and at scan time as `viewingKeyNk`. `getNkFromUtxoPrivateKey(privateKey)`
derives it from the UTXO private key, as in [where the user's keys live](#where-the-users-keys-live).
Deriving the UTXO keypair from the seed (`deriveUtxoKeypairFromSpendKey`) makes the keys
reproducible, so they need never be the thing you lose. The note set still has to be written down.

> [!NOTE]
>
> Two devices sharing one note set will each believe a spent note is unspent, and the second spend
> fails with `DoubleSpend` (`0x1020`). `verifyUtxos(utxos, connection, programId)` partitions your
> local notes into `spent`, `unspent` and `skipped` in a single batched RPC call; run it on load and
> after any failure, and drop anything it reports as spent.

## UX requirements

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

## Related pages

* [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md)
* [Shielded transfers](https://docs.cloak.ag/guides/private-transfers.md)
* [Quickstart](https://docs.cloak.ag/get-started/quickstart.md)
* [UTXO Transactions](https://docs.cloak.ag/sdk/low-level-api.md)
* [Error Handling](https://docs.cloak.ag/reference/errors.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.