> ## 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.

# Error codes

> Every CloakCallError code, the low-level error classes, stale-root retries and on-chain error codes

This page is written against `@cloak.dev/sdk` 0.2.20. Catch the typed errors below instead of
matching message strings: the classes and codes are the stable surface, the wording is not.

## `createCloak` errors: `CloakCallError`

Every call on the object [`createCloak`](https://docs.cloak.ag/sdk/create-cloak) returns throws one error type,
`CloakCallError` (a `CloakError`), and it carries what a caller acts on:

* `code`: stable and dotted (`payout.refused`, `wallet.rejected`, `deposit.finish_failed`). Match on
  it with `isCloakCallError(e, code)`, which also matches every code under a prefix
  (`isCloakCallError(e, "payout")` is any `payout.*`).
* `retryable`: whether the same call can succeed if it is made again.
* `moneyAt` and `next`, when money is in flight: where it is now, and what happens to it. The
  message already includes both, written for a person.

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

try {
  await cloak.withdraw({ to, token: "USDC", amount: "10" });
} catch (e) {
  if (isCloakCallError(e, "balance.insufficient")) {
    // nothing moved: ask for a smaller amount
  } else if (isCloakCallError(e) && e.retryable) {
    // the same call can work again; e.next says what happens to the money meanwhile
  } else {
    throw e;
  }
}
```

A deposit or payout that stopped halfway is finished by the SDK itself (on the next start, or with
`cloak.resume()`), which is why many in-flight errors are `retryable` with a `next` that says so.

### Every `CloakCallError` code

Generated from the 0.2.20 source. "Retryable" is the error's own `retryable` flag; trust the flag on
the instance over this table.

| Code | Retryable | Thrown when |
| - | - | - |
| `account.missing` | no | No `wallet`, `wallets`, `cloakKey` or `account` was passed |
| `account.no_signer` | no | None of the wallets can sign the account message (a Ledger alone) |
| `account.invalid` | no | An account key is not 32 bytes or 64 hex characters, or a Cloak Key is not 24 words |
| `amount.invalid` | no | The amount is not a positive decimal string |
| `amount.too_precise` | no | More decimals than the token has |
| `token.missing` | no | No `token` was named |
| `ref.invalid` | no | A `ref` is not 1 to 128 printable characters |
| `ref.unsettled` | no | An earlier call with this `ref` started and did not record its end; it may have moved money |
| `quote.incomplete` | no | `quote` was given neither `from` nor `to` |
| `balance.insufficient` | no | The private balance cannot cover the call |
| `route.unsupported` | no | The route cannot carry that token |
| `route.ambiguous` | no | An EVM address or wallet without `chain: "base"` or `"polygon"` |
| `route.unknown` | no | `to` or `from` is not something the SDK can use |
| `route.mismatch` | no | The address belongs to another network than the one named |
| `route.private` | no | `withdraw` to a `cloak_` address; use `send` |
| `route.unavailable` | yes | The route is not serving right now |
| `shield.rejected` | no | The user declined the shield in the wallet |
| `shield.failed` | yes | The shield did not complete |
| `shield.insufficient_funds` | no | The origin wallet holds less than the amount |
| `shield.no_gas` | no | The origin wallet cannot pay the network fee |
| `shield.wrong_network` | no | The origin wallet is on another network |
| `shield.unavailable` | yes | Shields from that network cannot be taken right now |
| `shield.quote_failed` | yes | The route could not quote the shield |
| `shield.no_route` | no | This shield cannot be made |
| `shield.not_sent` | yes | The origin transfer was not sent |
| `shield.waiting` | yes | The transfer was sent and has not reached Cloak yet; it finishes on its own |
| `shield.origin_reverted` | no | The origin transfer reverted |
| `shield.closed` | no | The route closed the order; `moneyAt` says whether it refunded |
| `deposit.below_minimum`, `deposit.receiver_busy`, `deposit.origin_reverted`, `deposit.finish_failed` | per instance | Money arrived from another chain but is not shielded yet |
| `deposit.unfinished` | yes | A cross-chain deposit stopped part way |
| `send.failed` | yes | A private send did not complete |
| `send.needs_sol` | no | Sending BRS to Base needs private SOL for the LayerZero fee |
| `send.bridge_pending` | yes | BRS is at its one-time sender and not bridged yet |
| `withdraw.failed` | yes | A withdrawal did not complete |
| `payout.refused` | no | This recipient or amount cannot be paid (a token contract, below the minimum) |
| `payout.screening_refused` | no | Sanctions screening refused the recipient. Final |
| `payout.failed` | yes | A payout to another chain did not complete |
| `link.claimed` | no | The payment link was already claimed |
| `link.invalid`, `link.is_request` | no | Not a claimable link, or a payment request passed to `claimPaymentLink` |
| `link.ref_used` | no | This `ref` already made a different link |
| `link.unsupported_token` | no | The link holds a token the SDK does not handle |
| `link.failed`, `link.no_leaf`, `link.claim_failed` | yes | Funding or claiming a link did not complete |
| `request.invalid`, `request.unsupported_token` | no | Not a payment request the SDK can pay |
| `request.pay_failed` | yes | Paying the request did not complete |
| `notes.wrong_secret`, `notes.other_account`, `notes.wrong_network`, `notes.corrupt`, `notes.incomplete` | no | Saved notes could not be imported |
| `secret.invalid`, `secret.too_short` | no | A storage or backup secret is not 32+ bytes or a 12+ character passphrase |
| `storage.invalid`, `storage.reserved`, `storage.unreadable` | no | The storage passed is not usable, or was written with another secret |
| `storage.unwritable` | yes | The store did not keep a value |
| `wallet.missing`, `wallet.unrecognized` | no | No wallet, or not a wallet the SDK recognizes |
| `wallet.not_connected` | usually no | The wallet has no connected account (retryable when the connect call itself failed) |
| `wallet.rejected` | no | The user declined connecting, or declined the account message on an EVM wallet |
| `wallet.none_for_chain` | no | No connected wallet on the chain the call needs |
| `wallet.cannot_sign`, `wallet.cannot_send`, `wallet.cannot_read` | no | The wallet lacks a capability the call needs |
| `wallet.bad_response`, `wallet.bad_address`, `wallet.chain_unsupported` | no | The wallet returned something unusable |
| `sui.*` | mostly no | Sui wallet specifics: `insufficient`, `gas`, `bad_amount`, `too_many_coins`, `address_balance`, `read_failed` (retryable) |

Two errors that are not `CloakCallError` can also come out of `createCloak`:
`WalletSignatureChangedError` (the wallet now signs the account message differently than when the
account was set up on this device) and `StoredAccountRequiredError` (the wallet cannot sign
repeatably). Catch them by `name`.

## The free functions' errors

The free functions (`transact`, `transfer`, `partialWithdraw`, …) expose three layers:

1. `CloakError` (runtime SDK operations, with a `category` and a `retryable` flag)
2. Typed errors for the outcomes a caller must act on: `RootNotFoundError`,
   `UtxoAlreadySpentError`, `SanctionsQuoteError`, `RelayInternalError`,
   `SettlementVerificationError`, `TransactionConfirmationError`
3. `parseError` / `parseTransactionError` (user-facing normalization)

## `CloakError`

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

declare function run(): Promise<void>;

async function withBackoff(attempt: () => Promise<void>): Promise<void> {
  try {
    await attempt();
  } catch (error) {
    if (error instanceof CloakError) {
      // category: "network" | "indexer" | "prover" | "relay" | "validation" | "wallet"
      //         | "environment" | "service"
      console.log(error.category, error.retryable);
    }
    throw error;
  }
}

await withBackoff(run);
```

Most app flows should treat `retryable === true` as backoff-eligible.

## Typed errors

```ts theme={null}
import {
  RelayInternalError,
  SanctionsQuoteError,
  SettlementVerificationError,
  TransactionConfirmationError,
  UtxoAlreadySpentError,
  fullWithdraw,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const options: SpendOptions;

try {
  await fullWithdraw(inputUtxos, recipient, options);
} catch (error) {
  if (error instanceof UtxoAlreadySpentError) {
    // A note was spent elsewhere. error.spentUtxoCommitments lists them; reconcile with verifyUtxos.
  } else if (error instanceof SettlementVerificationError) {
    // The relay never gave a usable answer. error.outcome says what chain state supports:
    //   "landed"     the transaction DID land: never retry, rescan to recover notes
    //   "not-landed" nothing landed: retrying is safe (error.safeToRetry)
    //   "unknown"    look up error.signature on an independent RPC before doing anything
    //   "failed"     on chain and failed during execution: inputs are unspent
    console.log(error.outcome, error.signature, error.reason);
  } else if (error instanceof SanctionsQuoteError) {
    // Structural mismatch between the quote and the program (error.subKind:
    // "expired" | "wallet_mismatch" | "missing_ix", error.onChainCode is the program code).
    // These are not something the caller can fix: they point to version skew or config drift
    // between the quote and the program. Report them.
  } else if (error instanceof TransactionConfirmationError) {
    // A direct (self-signed) transaction did not confirm. error.reason: "failed" | "expired" | "timeout".
    console.log(error.signature, error.reason);
  } else if (error instanceof RelayInternalError) {
    // A relay 5xx that maps to nothing more specific. Keep error.relayMessage for support.
    console.log(error.httpStatus, error.relayMessage);
  } else {
    throw error;
  }
}
```

`confirmTransactSettlement` re-checks a signature from chain state when an outcome was reported as
unknown.

## Persist the notes before you report success

`transact`, `transfer`, `partialWithdraw`, `swapUtxo` and `swapWithChange` all return
`result.outputUtxos`, and the change note among them is the user's remaining shielded balance.
Outputs with `amount === 0n` are padding and can be skipped. `fullWithdraw` leaves nothing shielded.

The notes the SDK builds for you are derived from your `nk` and a salt published in the encrypted
chain note, so a lost change note can be found again by a scan (`recoverNotesFromIndex`,
`scanTransactions`). The exception is a `transfer`'s change: it is output 1, the chain note
describes only output 0, so a scan cannot learn its amount and the note is spendable again only once
you supply that amount. Writing it down is still the fast path and gives you the leaf index at once.
The notes that cannot be found again are the ones built with `createUtxo` (by you, or by a client
that predates recoverable change), whose `blinding` is random and written nowhere, and notes owned by
a random `generateUtxoKeypair()` key you did not keep. Those are unspendable by anyone if the only
copy is dropped.

This is an error-handling concern because every example below is a `try`/`catch`. The `catch` is the
failure path; the tail of the `try` is the success path, and that is where the write belongs.
`saveNotes`, `dropNotes` and `saveSwapRefund` in these snippets are your own storage, not SDK
exports; [Where your notes live between sessions](https://docs.cloak.ag/wallets/wallet-adapter.md#where-your-notes-live-between-sessions)
covers what to build them on.

## When `fullWithdraw` merges first

The circuit spends at most two notes per transaction, so both `fullWithdraw` and `partialWithdraw`
consolidate first when you pass three or more inputs. Each consolidation round is its own on-chain
transaction: it spends the two smallest notes and creates one merged note owned by your
`ownerUtxoKeypair`. `onProgress` fires `Consolidating notes (n remaining)...` once per round, and
that string is the signal a caller gets that consolidation is happening at all.

Rounds that land are permanent, and the failure is what makes this an error-handling problem. If a
later round or the final withdrawal throws (stale-root retries exhausted, a rejected wallet approval,
a submission failure, a closed tab), then the two notes that round consumed are spent, the merged
commitment is in the tree, and the call returned nothing, so there is no `result.outputUtxos` to
write down.

The merged note is not destroyed. Its blinding is derived from your `nk` and a salt the round
published in its chain note, and the merged note is output 0, whose amount that chain note carries,
so a rescan with `nk` finds it again (`recoveredChangeNotes`). Until you rescan, though, your app does not
know it exists, and retrying with the original `inputUtxos` fails: the first merge round preflights
their nullifiers and throws `UtxoAlreadySpentError`.

What you can do, in order of usefulness:

```ts Consolidate yourself first theme={null}
import {
  createRecoverableChangeUtxo,
  fullWithdraw,
  randomChangeNoteSalt,
  serializeUtxo,
  transact,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const options: SpendOptions; // includes ownerUtxoKeypair and chainNoteViewingKeyNk
declare const nk: Uint8Array; // the same nk as options.chainNoteViewingKeyNk
declare function saveNotes(notes: Uint8Array[]): Promise<void>;

// Each merge is now your transaction: it returns, and you persist, before the next one starts.
let notes = [...inputUtxos];
while (notes.length > 2) {
  notes.sort((a, b) => (a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0));
  const [small1, small2, ...rest] = notes;
  const salt = randomChangeNoteSalt();
  const { utxo: merged } = await createRecoverableChangeUtxo(
    small1.amount + small2.amount,
    options.ownerUtxoKeypair,
    nk,
    small1.mintAddress,
    salt,
    0,
  );
  const result = await transact(
    { inputUtxos: [small1, small2], outputUtxos: [merged], externalAmount: 0n },
    { ...options, chainNoteSalt: salt },
  );
  // The merged note exists on chain now. Write it before the next round can fail.
  await saveNotes(result.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo));
  notes = [result.outputUtxos[0], ...rest];
}

// Two notes left, so this call performs no merges.
await fullWithdraw(notes, recipient, options);
```

```ts Reconcile after a throw theme={null}
import { fullWithdraw, verifyUtxos, type SpendOptions, type Utxo } from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const options: SpendOptions;
declare function dropNotes(commitments: bigint[]): Promise<void>;

let consolidated = false;
try {
  await fullWithdraw(inputUtxos, recipient, {
    ...options,
    onProgress: (status) => {
      if (status.startsWith("Consolidating notes")) consolidated = true;
    },
  });
} catch (error) {
  if (consolidated) {
    // Some inputs are spent and one merged note is not in your store. Never retry with
    // `inputUtxos`: the first merge round preflights the nullifiers and throws
    // `UtxoAlreadySpentError` (0x1020).
    const { spent, unspent } = await verifyUtxos(inputUtxos, options.connection, options.programId);
    // Anything without a commitment lands in `skipped`, so `spent` entries always have one.
    await dropNotes(spent.map((utxo) => utxo.commitment!));
    // Rescan with recoverNotesFromIndex to pick up the merged note, then withdraw again from it
    // and from `unspent`. If the withdrawal itself landed and only its confirmation failed, the
    // recipient already has the funds, so check their balance first.
    console.log(unspent.length);
  }
  throw error;
}
```

Consolidating yourself is the only option that prevents the gap rather than recovering from it.
Prefer it in any flow where the user can hold more than two notes.

## `Unauthorized` and bare `401` on a send, withdraw or swap

Every request Cloak submits for you carries a signed sender, and every way that can go wrong arrives
as the same opaque rejection. `explainRelayAuthRejection` turns one into user-facing prose, and
returns `null` for anything that is not an authentication rejection, so it is safe to call
unconditionally:

```ts theme={null}
import {
  explainRelayAuthRejection,
  fullWithdraw,
  parseError,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const options: SpendOptions;
declare function showError(message: string): void;

try {
  await fullWithdraw(inputUtxos, recipient, options);
} catch (error) {
  const hint = explainRelayAuthRejection(String(error));
  // Non-null examples: a wallet approval that sat past the 300-second window, a machine
  // clock more than 30 seconds fast, a body that changed after it was signed, a wallet
  // with no viewing key registered yet.
  showError(hint ?? parseError(error).message);
}
```

Two of the causes are not a bug in your code at all: an approval dialog left waiting, and a wrong
clock on the user's machine. Both are recoverable by retrying, and nothing was submitted for the
request that was rejected. That is not the same as nothing having been submitted: with three or more
inputs the rejection can arrive on a round that follows landed consolidation transactions, so
reconcile with `verifyUtxos` before retrying rather than reusing `inputUtxos`. The full contract,
including how to supply a signer at all, is in
[Request authentication](https://docs.cloak.ag/sdk/request-authentication.md).

A call that has no usable signer never reaches the network. It throws up front, before any proof is
generated, with a message that begins `Cloak <flow> requires an authenticated sender` (for a
transfer, withdrawal or swap), `<flow> requires options.ownerUtxoKeypair` (a spend flow with no
owner key), or `Viewing key registration is mandatory` (no `nk`, or nothing to sign the registration
challenge). Those are setup mistakes, not runtime failures: fix the options rather than catching them.

## Stale Merkle root (`0x1001`)

Use helpers for RootNotFound detection:

```ts Keypair bytes theme={null}
import {
  fullWithdraw,
  isRootNotFoundError,
  RootNotFoundError,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const options: SpendOptions; // built with depositorKeypair, ownerUtxoKeypair and nk

try {
  await fullWithdraw(inputUtxos, recipient, options);
  // With one or two inputs this leaves nothing shielded, so there is no change note to
  // persist here. With three or more, consolidation runs first: see "When fullWithdraw merges
  // first". Every other flow has a change note either way.
} catch (error) {
  if (error instanceof RootNotFoundError || isRootNotFoundError(error)) {
    // Refresh proof inputs, then reconcile with verifyUtxos before retrying: a stale root on
    // the final withdrawal can follow consolidation rounds that already landed.
  }
}
```

```ts Wallet adapter theme={null}
import {
  isRootNotFoundError,
  partialWithdraw,
  RootNotFoundError,
  serializeUtxo,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const recipient: Address;
declare const walletOptions: SpendOptions; // built with walletPublicKey, signMessage, ownerUtxoKeypair and nk
declare function saveNotes(notes: Uint8Array[]): Promise<void>;

try {
  const withdrawn = await partialWithdraw(inputUtxos, recipient, 10_000_000n, walletOptions);
  // Success path: write the remaining balance down now.
  await saveNotes(
    withdrawn.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo),
  );
} catch (error) {
  if (error instanceof RootNotFoundError || isRootNotFoundError(error)) {
    // Rebuild with fresh commitments/root and retry
  }
}
```

SDK note and UTXO flows already include retry loops (`maxRootRetries`); this usually appears only
after retries are exhausted.

## On-chain error message mapping

`ShieldPoolErrors` maps known custom program codes:

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

console.log(ShieldPoolErrors[0x1001]); // Root not found in the roots ring
console.log(ShieldPoolErrors[0x1020]); // Double spend detected - this note has already been spent
console.log(ShieldPoolErrors[0x1076]); // Proof verification failed
```

## User-facing normalization

```ts Keypair bytes theme={null}
import {
  parseError,
  serializeUtxo,
  swapWithChange,
  type SpendOptions,
  type UserFriendlyError,
  type Utxo,
  type UtxoSwapResult,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const amountLamports: bigint;
declare const outputMint: Address;
declare const recipientAta: Address;
declare const recipientWallet: Address;
declare const minOutput: bigint;
declare const options: SpendOptions; // depositorKeypair, ownerUtxoKeypair, chainNoteViewingKeyNk
declare function saveNotes(notes: Uint8Array[]): Promise<void>;
declare function saveSwapRefund(
  swapStatePda: string,
  refund: UtxoSwapResult["refund"],
): Promise<void>;

try {
  const swapped = await swapWithChange(
    inputUtxos,
    amountLamports,
    outputMint,
    recipientAta,
    minOutput,
    options,
    recipientWallet,
  );
  // Success path, two writes. The change note is the remaining shielded balance.
  await saveNotes(
    swapped.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo),
  );
  // `swapped.refund` reclaims the principal if the swap times out before it executes.
  // With `chainNoteViewingKeyNk` supplied it can be rebuilt later via `discoverSwapRefunds`
  // (`refund.derivedFromNk` is true), so saving it is the fast path.
  await saveSwapRefund(swapped.swapStatePda, swapped.refund);
} catch (error) {
  const parsed: UserFriendlyError = parseError(error);
  // parsed.category: wallet | network | validation | service | transaction | unknown
  // parsed.recoverable: boolean
  console.log(parsed.title, parsed.message, parsed.suggestion);
}
```

```ts Wallet adapter theme={null}
import {
  parseError,
  serializeUtxo,
  swapWithChange,
  type SpendOptions,
  type UserFriendlyError,
  type Utxo,
  type UtxoSwapResult,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[];
declare const amountLamports: bigint;
declare const outputMint: Address;
declare const recipientAta: Address;
declare const recipientWallet: Address;
declare const minOutput: bigint;
declare const walletOptions: SpendOptions; // walletPublicKey, signMessage, ownerUtxoKeypair, chainNoteViewingKeyNk
declare function saveNotes(notes: Uint8Array[]): Promise<void>;
declare function saveSwapRefund(
  swapStatePda: string,
  refund: UtxoSwapResult["refund"],
): Promise<void>;

try {
  const swapped = await swapWithChange(
    inputUtxos,
    amountLamports,
    outputMint,
    recipientAta,
    minOutput,
    walletOptions,
    recipientWallet,
  );
  // Same two writes as the other tab: the change note, then the timeout refund secret.
  await saveNotes(
    swapped.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo),
  );
  await saveSwapRefund(swapped.swapStatePda, swapped.refund);
} catch (error) {
  const parsed: UserFriendlyError = parseError(error);
  // parsed.category / parsed.recoverable
  console.log(parsed.title, parsed.message);
}
```

## Practical retry strategy

* Retry network and service failures with exponential backoff.
* Avoid retrying deterministic validation failures.
* On stale-root errors, rebuild proof data before retrying.
* Never retry a `SettlementVerificationError` whose `outcome` is not `"not-landed"`.

## UTXO stale-root retry template

`transact`, `partialWithdraw` and `fullWithdraw` already retry a stale root internally, so an outer
loop is only for the case where those retries are exhausted:

```ts theme={null}
import {
  isRootNotFoundError,
  partialWithdraw,
  serializeUtxo,
  type MerkleTree,
  type SpendOptions,
  type Utxo,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const inputUtxos: Utxo[]; // one or two notes
declare const recipientWallet: Address;
declare const options: SpendOptions;
declare const initialMerkleTree: MerkleTree | undefined;
declare function saveNotes(notes: Uint8Array[]): Promise<void>;

let result: Awaited<ReturnType<typeof partialWithdraw>> | undefined;
let cachedMerkleTree = initialMerkleTree;

for (let attempt = 1; attempt <= 3; attempt += 1) {
  try {
    result = await partialWithdraw(inputUtxos, recipientWallet, 10_000_000n, {
      ...options,
      cachedMerkleTree,
    });
    break;
  } catch (error) {
    if (!isRootNotFoundError(error) || attempt === 3) throw error;
    await new Promise((resolve) => setTimeout(resolve, 1_500 * attempt));
    // refresh proof inputs before retrying (new root + updated tree)
    cachedMerkleTree = undefined;
  }
}

if (!result) throw new Error("withdraw did not complete");

// `break` only ends the retry. The change note is still unsaved at this point, so persist it
// before anything reports success.
await saveNotes(result.outputUtxos.filter((utxo) => utxo.amount > 0n).map(serializeUtxo));
```

This template reuses `inputUtxos` on every attempt, which is safe only while that array holds one or
two notes. With three or more, attempt 1 can land consolidation transactions before it throws, and
attempt 2 then spends notes that are already nullified: the first merge round preflights them and
throws `UtxoAlreadySpentError` instead of retrying. Consolidate down to two notes yourself before
entering a loop like this, as in
[When `fullWithdraw` merges first](#when-fullwithdraw-merges-first).

Swap `partialWithdraw` for `transact`, `transfer`, `swapUtxo` or `swapWithChange` and the loop is
unchanged, but the tail still has to run: each of those returns a change note too, and the two swap
helpers add a `refund` authorization. `fullWithdraw` is the only substitution that can skip the
tail, and only when it is given one or two notes, because that is when it leaves nothing shielded
and performs no merges of its own.

## Security logging rule

Never log full notes/UTXOs with secrets. Log only non-sensitive identifiers (commitment prefix, leaf index, request ID, and tx signature when needed for support).


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