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

# API reference

> Current public API for @cloak.dev/sdk

This page tracks the current public exports of `@cloak.dev/sdk` 0.2.20. Every name and signature
below is checked against the package's `index.d.ts`.

## `createCloak`

One call per action. [createCloak](https://docs.cloak.ag/sdk/create-cloak.md) documents every call, request and receipt.

```ts theme={null}
import {
  createCloak,
  isCloakCallError,
  type CloakQuote,
  type CloakReceipt,
  type CreateCloakOptions,
} from "@cloak.dev/sdk";

const options: CreateCloakOptions = { wallet, rpc: "https://<your-mainnet-rpc>" };
const cloak = await createCloak(options);
const quote: CloakQuote = await cloak.quote({ to: "cloak_…", token: "USDC", amount: "1" });
const receipt: CloakReceipt = await cloak.send({ to: "cloak_…", token: "USDC", amount: "1" });
```

Next to it: `CloakCallError` and `isCloakCallError(e, code?)`; storage (`memoryStorage`,
`encryptedStorage`, `restoreNotes`); wallets (`recognizeWallet`, `discoverEvmWallets`); networks
(`NETWORKS`, `networkById`, `depositNetworks`, `payoutNetworks`, `payoutToken`, `payoutMinimum`,
`classifyRecipient`, `isTronAddress`, `decodeTronAddress`); and payouts (`checkPayoutRecipient`,
`previewPayout`, `payOutFromPrivateBalance`, `watchPayout`, `isPayoutScreeningRefusal`). See
[Other networks](https://docs.cloak.ag/guides/cross-chain.md).

## UTXO API

The UTXO free functions are the lower-level entrypoint, the one `createCloak` is built on. There is
no client class to construct.

```ts theme={null}
import {
  fullWithdraw,
  partialWithdraw,
  swapUtxo,
  swapWithChange,
  sweepToWalletKey,
  transact,
  transfer,
  type SpendOptions,
  type SweepResult,
  type TransactOptions,
  type TransactParams,
  type TransactResult,
  type Utxo,
  type UtxoSwapParams,
  type UtxoSwapResult,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const params: TransactParams;
declare const swapParams: UtxoSwapParams;
declare const options: TransactOptions; // deposits and raw transact calls
declare const spendOptions: SpendOptions; // TransactOptions & { ownerUtxoKeypair: UtxoKeypair }
declare const inputs: Utxo[];
declare const recipient: Address;
declare const recipientCloakPubkey: bigint;
declare const outputMint: Address;
declare const recipientAta: Address;

const a: Promise<TransactResult> = transact(params, options);
const b: Promise<TransactResult> = transfer(inputs, recipientCloakPubkey, 1_000_000n, spendOptions);
const c: Promise<TransactResult> = partialWithdraw(inputs, recipient, 1_000_000n, spendOptions);
const d: Promise<TransactResult> = fullWithdraw(inputs, recipient, spendOptions);
const e: Promise<UtxoSwapResult> = swapUtxo(swapParams, spendOptions);
const f: Promise<UtxoSwapResult> = swapWithChange(
  inputs,
  1_000_000n, // swapAmount
  outputMint,
  recipientAta,
  1n, // minOutputAmount
  spendOptions,
  recipient, // optional recipientWallet
);
const g: Promise<SweepResult> = sweepToWalletKey(inputs, spendOptions);
```

`transact` is the single engine entrypoint and the sign of `externalAmount` classifies the
flow: positive shields (deposit), negative withdraws, zero is a shielded transfer.
`transfer`, `partialWithdraw` and `fullWithdraw` are shaped wrappers over it.
`sweepToWalletKey` moves up to two notes owned by other keys under the wallet's long-lived key with
one self-spend.

`transact` and `transactBatch` take a `TransactOptions` object. Every spend flow (`transfer`,
`partialWithdraw`, `fullWithdraw`, `swapUtxo`, `swapWithChange`, `sweepToWalletKey`) takes
`SpendOptions`, which is `TransactOptions` with `ownerUtxoKeypair` made mandatory. The wallet's `nk`
(`chainNoteViewingKeyNk`) is also required at runtime on every spend, and should be passed on
deposits too. `connection`, `programId` and `relayUrl` are required on all flows. Supply either
`depositorKeypair` (a Kit `KeyPairSigner`, programmatic) or `signer` (the wallet as a Kit
`TransactionSigner`, from `signerFromWalletAdapter`). `signMessage` plus `walletPublicKey` is the
relay-only alternative for sends, withdrawals and swaps. There is no `signTransaction` option.
`relayUrl` has no default and is not read from the environment, so pass `CLOAK_PRODUCTION_RELAY_URL`
explicitly on every call. Every flow except a deposit needs an authenticated sender and throws before
proof generation without one: see [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md).

The canonical way to get `ownerUtxoKeypair` and `nk` is from a seed generated once and stored like
a private key. A random key that is lost loses the notes, so do not use `generateUtxoKeypair()` for
anything that holds real funds.

```ts theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  createCloakRpc,
  deriveSpendKey,
  deriveUtxoKeypairFromSpendKey,
  generateMasterSeed,
  getNkFromUtxoPrivateKey,
  signerFromSecretKey,
  type SpendOptions,
} from "@cloak.dev/sdk";

const seed = generateMasterSeed().seed; // 32 bytes: generate once, store like a private key
const { sk_spend } = deriveSpendKey(seed);
const ownerUtxoKeypair = await deriveUtxoKeypairFromSpendKey(sk_spend);
const nk = getNkFromUtxoPrivateKey(ownerUtxoKeypair.privateKey); // view-only: finds notes, never spends them

declare const secretKey: Uint8Array;

const spendOptions: SpendOptions = {
  connection: createCloakRpc("https://your-keyed-mainnet-rpc.example"),
  programId: CLOAK_PROGRAM_ID,
  relayUrl: CLOAK_PRODUCTION_RELAY_URL,
  depositorKeypair: await signerFromSecretKey(secretKey),
  ownerUtxoKeypair,
  chainNoteViewingKeyNk: nk,
};
```

UTXO primitives:

```ts theme={null}
import {
  computeUtxoCommitment,
  computeUtxoNullifier,
  createUtxo,
  createZeroUtxo,
  deserializeUtxo,
  generateUtxoKeypair,
  NATIVE_SOL_MINT,
  selectUtxos,
  serializeUtxo,
  verifyUtxos,
  type Utxo,
  type VerifyUtxosResult,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const connection: Parameters<typeof verifyUtxos>[1];
declare const programId: Address;
declare const available: Utxo[];

const keypair = await generateUtxoKeypair(); // tests only; derive it from a seed for real funds
// Illustrates the type only. A note that holds funds should come from createRecoverableDepositUtxo
// or createRecoverableChangeUtxo; transact throws on a self-owned output built with createUtxo.
const note: Utxo = await createUtxo(1_000_000_000n, keypair, NATIVE_SOL_MINT);
const zero: Utxo = await createZeroUtxo();
const commitment: bigint = await computeUtxoCommitment(note);
const nullifier: bigint = await computeUtxoNullifier(note);
const picked: Utxo[] | null = selectUtxos(available, 500_000_000n);
const state: VerifyUtxosResult = await verifyUtxos([note], connection, programId, "confirmed");
const bytes: Uint8Array = serializeUtxo(note);
const restored: Utxo = await deserializeUtxo(bytes);
console.log(zero, commitment, nullifier, picked, state, restored);
```

`selectUtxos` needs two checks at every call site, not one. It returns `null` instead of throwing
when the available notes do not cover the target, so a truthy check covers the insufficient-balance
case. It also knows nothing about the circuit's two-input cap: it can return three notes for
a large target, and `transact` then throws `Maximum 2 input UTXOs allowed` before proving. Check the
length as well as the null. `partialWithdraw` and `fullWithdraw` consolidate down to two inputs for
you; `transfer` does not, so cap the selection yourself.

That consolidation has a cost worth budgeting for. `partialWithdraw` merges the two
smallest notes at a time, so `n` inputs cost `n - 2` shielded transactions before the withdrawal
itself, each one separately proved, signed and submitted. `fullWithdraw` delegates to it and behaves
the same. In a browser that is `n - 2` extra wallet approvals, and `options.onProgress` is the only
thing that reports them: it fires `Consolidating notes (n remaining)...` on each round. Each merge
also creates an intermediate note that the SDK never hands back. Its blinding is derived from `nk`,
so a run that dies between a merge and the final withdrawal can be recovered by a scan, but only
through the recovery path described below, not by the call itself. Prefer
two inputs where you can, and treat a many-input withdrawal as a long resumable operation rather
than a single call.

`serializeUtxo` / `deserializeUtxo` are a fixed 128-byte encoding of one note: amount, private key,
blinding, mint and leaf index. That is the full spending secret in a byte array, so treat the output
as key material and encrypt it at rest. `deserializeUtxo` is async because it re-derives the public
key and recomputes `commitment`. One edge to know: a note at leaf index `0` comes back with `index`
undefined, because the encoding cannot tell index `0` from unset.

Note storage and key material. The SDK persists nothing on its own; these are the pieces you build a
store out of, and the full pattern is
[Where your notes live between sessions](https://docs.cloak.ag/wallets/wallet-adapter.md#where-your-notes-live-between-sessions).

```ts theme={null}
import {
  exportWalletKeys,
  expandSpendKey,
  getNkFromUtxoPrivateKey,
  importWalletKeys,
  LocalStorageAdapter,
  MemoryStorageAdapter,
  UtxoWallet,
  type CloakKeyPair,
  type ExpandedSpendKey,
  type StorageAdapter,
} from "@cloak.dev/sdk";

declare const keys: CloakKeyPair;
declare const skSpend: Uint8Array;
declare const utxoPrivateKey: bigint;

const wallet = new UtxoWallet();
const restored: UtxoWallet = UtxoWallet.deserialize(wallet.serialize());
const browserStore: StorageAdapter = new LocalStorageAdapter();
const testStore: StorageAdapter = new MemoryStorageAdapter();
const json: string = exportWalletKeys(keys);
const back: CloakKeyPair = importWalletKeys(json);
const expanded: ExpandedSpendKey = expandSpendKey(skSpend);
const nk: Uint8Array = getNkFromUtxoPrivateKey(utxoPrivateKey);
console.log(restored, browserStore, testStore, back, expanded, nk);
```

* [`UtxoWallet`](https://docs.cloak.ag/wallets/wallet-adapter#where-your-notes-live-between-sessions) is the live note set:
  `Utxo` objects per mint, spent flags, balance, stats and input selection. It does not persist
  itself. `serialize()` and the static `UtxoWallet.deserialize(json)` give you a JSON string that
  handles the `bigint` fields; where that string goes is your choice. It drops `commitment`, so
  recompute with `computeUtxoCommitment` after restoring, or `verifyUtxos` reports every restored
  note as `skipped` rather than spent or unspent.
* [`LocalStorageAdapter`](https://docs.cloak.ag/wallets/wallet-adapter#where-your-notes-live-between-sessions) implements
  `StorageAdapter` over browser `localStorage`, holding `CloakNote` records and wallet keys under the
  keys `cloak_notes` and `cloak_wallet_keys` by default.
* [`MemoryStorageAdapter`](https://docs.cloak.ag/wallets/wallet-adapter#where-your-notes-live-between-sessions) is the same
  interface held in process. It persists nothing and loses everything on reload: use it for tests, or
  when storage lives entirely on your side.
* `importWalletKeys` / `exportWalletKeys` move a `CloakKeyPair` in and out of a JSON string.
* `expandSpendKey` derives `(ask, nsk, ovk)` from a spend key; `getNkFromUtxoPrivateKey` returns the
  32-byte `nk` for a note's private key. `nk` is the incoming viewing base: it is what decrypts chain
  notes and what the recovery helpers below scan with.

The two halves do not connect. `UtxoWallet` does not take a `StorageAdapter`, and a `StorageAdapter`
does not store `Utxo` objects. The note set is the half that decides solvency.

> [!WARNING]
>
> Do not build sends with `UtxoWallet.prepareSend` or with `SimpleWallet`, even though both are
> exported. `prepareSend` derives the recipient output from a freshly generated random keypair rather
> than from the recipient's key, so the note it produces is unspendable by the recipient and by you.
> `SimpleWallet.sync()` throws `Sync not yet implemented`. Use `transfer`, which builds the recipient
> output from the Cloak pubkey you pass it. The rest of `UtxoWallet` is sound: `addUtxo`, `markSpent`,
> `getBalance`, `getUnspentUtxos`, `getStats`, `selectInputs`, `serialize` and `deserialize`.

Note helpers, all free functions:

```ts theme={null}
import {
  encodeNoteSimple,
  exportNote,
  generateNoteFromWallet,
  parseNote,
  serializeNote,
  validateNote,
  type CloakKeyPair,
  type CloakNote,
} from "@cloak.dev/sdk";

declare const keys: CloakKeyPair;

const note: CloakNote = await generateNoteFromWallet(1_000_000_000, keys, "mainnet");
const text: string = serializeNote(note, true);
const parsed: CloakNote = parseNote(text);
const simple: string = encodeNoteSimple(parsed);
const exported: string = exportNote(parsed, true);
validateNote(parsed); // throws when the note is malformed
console.log(simple, exported);
```

Full flow guide: [UTXO Transactions](https://docs.cloak.ag/sdk/low-level-api.md)

## Result types

Every UTXO flow resolves to a `TransactResult`:

```ts theme={null}
import type { LookupTable, MerkleTree, Utxo } from "@cloak.dev/sdk";

interface TransactResult {
  signature: string;
  inputNullifiers: bigint[];
  outputCommitments: bigint[];
  newRoot: string;
  commitmentIndices: [number, number];
  siblingCommitments: [bigint, bigint];
  preTransactionLeftSibling?: bigint;
  outputUtxos: Utxo[];
  viewingKeyRegistered?: boolean;
  merkleTree?: MerkleTree;
  addressLookupTableAccounts?: LookupTable[];
}
```

`swapUtxo` and `swapWithChange` both resolve to a `UtxoSwapResult`, which extends it:

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

interface UtxoSwapResult extends TransactResult {
  swapStatePda: string;
  nullifier: string;
  requestId?: string;
  refund: {
    publicKey: string;
    blinding: string;
    derivedFromNk: boolean;
  };
}
```

`refund` describes the note the program creates if the swap times out and the input is returned. Its
`publicKey` is the wallet's own `ownerUtxoKeypair` public key, so the private key is not
repeated here, and its blinding is derived from the wallet's `nk` (`derivedFromNk` is always `true`).
That is what lets `discoverSwapRefunds` find the leaf again from key material if you lose this object.

## Recovery helpers

Two exports let a wallet rebuild notes from key material alone, with no local note store.

```ts theme={null}
import {
  CLOAK_PROGRAM_ID,
  createCloakRpc,
  createRecoverableDepositUtxo,
  discoverSwapRefunds,
  NATIVE_SOL_MINT,
  type DiscoveredSwapRefund,
  type UtxoKeypair,
} from "@cloak.dev/sdk";

declare const ownerUtxoKeypair: UtxoKeypair;
declare const nk: Uint8Array;

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

const refunds: DiscoveredSwapRefund[] = await discoverSwapRefunds(
  createCloakRpc("https://your-keyed-mainnet-rpc.example"),
  CLOAK_PROGRAM_ID,
  nk,
  { ownerUtxoKeypair },
);
console.log(utxo, noteSalt, refunds);
```

`createRecoverableDepositUtxo` builds a deposit output owned by `ownerUtxoKeypair`, with a blinding
derived from `(nk, noteSalt)` instead of raw randomness, which is what makes a later cold scan able to
rebuild it. It resolves to `{ utxo, noteSalt }`, and the same salt must reach `transact` as
`options.chainNoteSalt` alongside `options.chainNoteViewingKeyNk` and `options.ownerUtxoKeypair`. A
salt that never reaches the chain note leaves the deposit exactly as undiscoverable as before.

`discoverSwapRefunds` walks program history for swap timeout-refund leaves that belong to the holder
of `viewingKeyNk`. Its options object is required and must carry `ownerUtxoKeypair`: pass the real
keypair for spendable results, or `{ privateKey: 0n, publicKey }` for a view-only scan. It also accepts
`limit`, `untilSignature` and `batchSize`. It finds refunds whose blinding was derived from `nk`, so an
empty result is not proof that a wallet has no stranded refund.

> [!WARNING]
>
> A note built with plain `createUtxo` has a random `blinding` that is written nowhere, so if you lose
> it the note is unspendable by anyone, permanently. The spend flows now derive their change from
> `nk` (`createRecoverableChangeUtxo`), so a scan can rebuild it, but persist `result.outputUtxos`
> before you report success anyway:
> [where your notes live between sessions](https://docs.cloak.ag/wallets/wallet-adapter.md#where-your-notes-live-between-sessions).
> Wallet restore from key material alone is `scanTransactions` (history walk) or `recoverNotesFromIndex`
> (one bulk feed, one RPC request); both are exported.

## Proof and Merkle utilities

```ts theme={null}
import {
  buildMerkleTreeFromRelay,
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  computeProofFromChain,
  createCloakRpc,
  getShieldPoolPDAs,
  readMerkleTreeState,
} from "@cloak.dev/sdk";

const connection = createCloakRpc("https://your-keyed-mainnet-rpc.example");
const { merkleTree: merkleTreePDA } = await getShieldPoolPDAs(CLOAK_PROGRAM_ID); // SOL pool

const state = await readMerkleTreeState(connection, merkleTreePDA);
const proof = await computeProofFromChain(connection, merkleTreePDA, 0);
const tree = await buildMerkleTreeFromRelay(CLOAK_PRODUCTION_RELAY_URL);
console.log(state, proof, tree);
```

Notes:

* UTXO transact/swap flows submit 256-byte proofs and 264-byte public inputs.

## Fee constants

Fees are enforced on-chain from each pool's `PoolConfig`; `transact` reads the live config before
building a fee-bearing proof. These constants mirror the deployed SOL-pool defaults for display
math. SPL pools (USDC/USDT) charge `450_000` base units fixed (0.45) + 0.3%, and the BRS pool `2_300_000` (2.3 BRS) + 0.3%; see
[Fee Model](https://docs.cloak.ag/concepts/fees.md).

```ts theme={null}
import {
  calculateFee,
  calculateFeeBigint,
  FIXED_FEE_LAMPORTS, // 5_000_000
  formatAmount,
  getDistributableAmount,
  isWithdrawAmountSufficient,
  LAMPORTS_PER_SOL, // 1_000_000_000
  MIN_DEPOSIT_LAMPORTS, // 10_000_000
  parseAmount,
  VARIABLE_FEE_DENOMINATOR, // 1000
  VARIABLE_FEE_NUMERATOR, // 3
  VARIABLE_FEE_RATE, // 0.003
} from "@cloak.dev/sdk";

const fee: number = calculateFee(1_000_000_000);
const feeBig: bigint = calculateFeeBigint(1_000_000_000n);
const enough: boolean = isWithdrawAmountSufficient(1_000_000_000n);
const net: number = getDistributableAmount(1_000_000_000);
const label: string = formatAmount(1_000_000_000, 4);
const lamports: number = parseAmount("1.5");
console.log(
  fee, feeBig, enough, net, label, lamports,
  FIXED_FEE_LAMPORTS, VARIABLE_FEE_NUMERATOR, VARIABLE_FEE_DENOMINATOR,
  VARIABLE_FEE_RATE, MIN_DEPOSIT_LAMPORTS, LAMPORTS_PER_SOL,
);
```

These values cover the native SOL pool. SPL pools (USDC and USDT) charge a fixed 0.45 token,
450,000 raw units at 6 decimals, plus the same 0.3 percent variable fee. The BRS pool charges a fixed
2.3 BRS (2,300,000 raw units) plus 0.3 percent. The program reads the
effective values from the `pool_config` PDA; the SDK does not compute SPL fees.

## Advanced `TransactOptions`

Five options a standard integration never sets, listed because nothing else documents them.

```ts theme={null}
import type {
  ExternalFeePayerAdapter,
  RelayBatchAuthItemHandle,
  TransactOptions,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

// These five fields are declared on TransactOptions; this interface restates them.
interface AdvancedTransactOptions {
  expectedMint?: Address; // the mint the CALLER believes it is spending
  relaySupplementalAlt?: boolean; // one-signature SPL deposits (default false)
  transactionVersion?: 0 | 1; // message version for SDK-built transactions (default 0)
  externalFeePayer?: ExternalFeePayerAdapter; // a payer that covers network fees
  relayAuthBatch?: RelayBatchAuthItemHandle; // set by transactBatch, not by hand
}

// Compile-time proof that the restatement matches the package.
const check: AdvancedTransactOptions = {} satisfies Pick<
  TransactOptions,
  keyof AdvancedTransactOptions
>;
console.log(check);
```

**`expectedMint`**: every flow takes the pool from the notes it is handed, so the SDK cannot
otherwise tell a deliberate USDC withdrawal from a SOL withdrawal that was handed a USDC note by
mistake. Both are well-formed and both settle. Set `expectedMint` and the SDK refuses the
transaction when the input notes disagree. It is optional for backward compatibility, but pass it on every
flow you can.

**`relaySupplementalAlt`**: when `true` and `relayUrl` is set, an SPL deposit that needs a
supplemental address lookup table asks for a shared table to be extended instead of creating a
depositor-signed throwaway one, so the user signs once instead of twice. Any failure
falls back to the depositor-signed ephemeral-ALT path automatically. Off by default, which preserves
the old behaviour exactly.

**`transactionVersion`**: `0` (default) builds a v0 message with ComputeBudget instructions. `1`
builds a Transaction V1 message (SIMD-0385): 4,096-byte packet, every account static with no lookup
tables, compute budget in the message header. It needs the cluster's v1 gate active and a signer
that signs v1 messages. A local key pair does; a browser wallet may not yet.

**`externalFeePayer`**: lets a deposit come from a wallet holding no SOL: the adapter's payer covers
the network fee and on-chain rent and is reimbursed in an SPL token inside the same transaction.

**`relayAuthBatch`**: the handle `transactBatch` passes to each item so the row is authenticated by
the batch's single signature. It takes precedence over `depositorKeypair` and `relayAuthSigner`.
Set it yourself only if you drive the coordinator directly.

## Partner code (`affiliateCode`)

Approved [Cloak partners](https://docs.cloak.ag/affiliates/overview.md) earn commission on the fee-bearing transactions their app makes by passing their code. See [Earn with the SDK](https://docs.cloak.ag/affiliates/sdk-integration.md) for the full rules.

```ts theme={null}
import { normalizeAffiliateCode, type TransactOptions } from "@cloak.dev/sdk";

// Both fields are declared on TransactOptions; this restates them.
interface PartnerCodeOptions {
  affiliateCode?: string; // trimmed and lower-cased; must match ^[a-z0-9_]{3,24}$
  onWarning?: (message: string) => void; // told when an invalid code is left out
}
const partner: PartnerCodeOptions = {} satisfies Pick<TransactOptions, keyof PartnerCodeOptions>;
console.log(partner, normalizeAffiliateCode(" Alice_01 ")); // "alice_01"
```

**`affiliateCode`** is attached only to fee-bearing requests: a withdrawal or send to a public
address (`fullWithdraw`, `partialWithdraw`, `transact` with a negative `externalAmount` and a
recipient) and a swap (`swapUtxo`, `swapWithChange`). Deposits, shielded transfers and the internal
merge steps of `partialWithdraw` never carry it, whatever is passed. It is signed inside the request,
never written on-chain, and an invalid code is left out without failing the transaction. In
`transactBatch` the batch's code applies to every fee-bearing item and an item's own
`options.affiliateCode` overrides it.

**`normalizeAffiliateCode(raw)`** applies the same rule and returns the normalised code or `null`,
for validating a code before it reaches a transaction.

## Request authentication and endpoint pinning

Private sends, withdrawals and swaps carry a signed sender. Standard integrations only pass `signer`
(browser) or `depositorKeypair` (server) in `TransactOptions` and never touch these; they exist for
callers driving submission themselves.

```ts theme={null}
import {
  buildRelayAuthPreimage,
  BUILD_ALLOWS_LOCAL_ENDPOINTS, // derived: true only for a local build
  canonicalJson,
  CLOAK_PRODUCTION_RELAY_URL, // the production endpoint, never a default
  CLOAK_PROGRAM_ID,
  explainRelayAuthRejection,
  messageSignerFromCallback,
  RELAY_ORIGIN_ALLOWLIST, // origins this build may reach; pinned at build time
  REQUEST_AUTH_MAX_AGE_SECONDS, // 300 (285 usable after the SDK's transit margin)
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS, // 30
  submitTransactToRelay,
  TRANSACT_AUTH_FIELDS, // 9 fields, sorted; order is part of the agreement
  TRANSACT_SWAP_AUTH_FIELDS, // 19 fields, sorted; `slippage_bps` must always be present
  type RelayAuthPreimage,
  type RelayAuthSigner,
  type SubmitTransactToRelayArgs,
} from "@cloak.dev/sdk";
import type { Address } from "@solana/kit";

declare const sender: Address;
declare const walletSignMessage: (message: Uint8Array) => Promise<Uint8Array>;
declare const requestBody: Record<string, unknown>;
declare const settlement: SubmitTransactToRelayArgs["settlement"];

// A message signer built from a wallet adapter's signMessage.
const relayAuthSigner: RelayAuthSigner = messageSignerFromCallback(sender, walletSignMessage);

const endpoint = `${CLOAK_PRODUCTION_RELAY_URL}/transact`;
const preimage: RelayAuthPreimage = buildRelayAuthPreimage(
  endpoint,
  CLOAK_PROGRAM_ID,
  requestBody,
  sender,
  undefined, // nowSeconds
  TRANSACT_AUTH_FIELDS,
);
// preimage is { sender, auth_issued_at, auth_nonce, message }

const args: SubmitTransactToRelayArgs = {
  relayUrl: CLOAK_PRODUCTION_RELAY_URL,
  requestBody,
  programId: CLOAK_PROGRAM_ID,
  relayAuthSigner,
  settlement, // the on-chain check used to confirm a reported success
  canRetryStaleRoot: true, // true while you still have a re-prove budget
};
const result = await submitTransactToRelay(args);

console.log(
  canonicalJson(requestBody),
  explainRelayAuthRejection("rejected response text"),
  TRANSACT_SWAP_AUTH_FIELDS,
  REQUEST_AUTH_MAX_AGE_SECONDS,
  REQUEST_AUTH_MAX_FUTURE_SKEW_SECONDS,
  RELAY_ORIGIN_ALLOWLIST,
  BUILD_ALLOWS_LOCAL_ENDPOINTS,
  preimage,
  result,
);
```

`maxWalletApprovals` on `TransactOptions` caps wallet dialogs for one swap (default `5`). Sends and
withdrawals sign once per submitted request; a stale Merkle root forces a new proof and a new
prompt. Full contract: [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md).

## Error utilities

```ts theme={null}
import {
  CloakError,
  isRootNotFoundError,
  parseError,
  parseTransactionError,
  RootNotFoundError,
  ShieldPoolErrors, // Record<number, string>: program error code to message
} from "@cloak.dev/sdk";

try {
  throw new CloakError("example", "network", true);
} catch (error) {
  if (error instanceof CloakError) console.log(error.category, error.retryable);
  if (error instanceof RootNotFoundError || isRootNotFoundError(error)) console.log("stale root");
  console.log(parseError(error).message, parseTransactionError(error), ShieldPoolErrors[0]);
}
```

Detailed usage: [Error Handling](https://docs.cloak.ag/reference/errors.md)

## Versioned exports

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

console.log(VERSION); // "0.2.20": matches the published package version
console.log(CLOAK_PROGRAM_ID); // mainnet program constant
```

`VERSION` tracked the package version incorrectly before 0.2.5 and is now in step with it. It is
still informational. To confirm which version you are on, check the published package with
`npm view @cloak.dev/sdk version` or `npm ls @cloak.dev/sdk`.

## Batch signing

`transactBatch` runs N private spends behind one wallet approval. Each item is proved
concurrently so every proof exists before the wallet is asked, then all items are submitted under a
single batch signature.

```ts theme={null}
import {
  RELAY_BATCH_AUTH_MAX_ITEMS, // 64: hard cap per call
  transactBatch,
  type TransactOptions,
  type TransactParams,
  type TransactResult,
} from "@cloak.dev/sdk";

interface TransactBatchItem {
  params: TransactParams;
  options?: Partial<TransactOptions>; // per-item overrides
}

interface TransactBatchOptions extends Omit<TransactOptions, "relayAuthBatch"> {
  proofConcurrency?: number; // items proved at once (default 2)
  submitConcurrency?: number; // items released at once after signing (default 3)
}

type TransactBatchItemOutcome =
  | { status: "fulfilled"; value: TransactResult }
  | { status: "rejected"; reason: unknown };

interface TransactBatchResult {
  results: TransactBatchItemOutcome[];
  approvals: number;
}

declare const items: readonly TransactBatchItem[];
declare const batchOptions: TransactBatchOptions;

const outcome: TransactBatchResult = await transactBatch(items, batchOptions);
console.log(outcome.approvals, RELAY_BATCH_AUTH_MAX_ITEMS);
```

`results` has one entry per item in input order, and a rejected item leaves the others unaffected.
`approvals` counts the wallet dialogs actually raised: 1 for the batch, plus 1 per wave of
stale-root re-proves.

The call requires `relayUrl` and an authenticated sender: `depositorKeypair`, or `signer`, or
`walletPublicKey` with `signMessage`. Both are checked before any proof is computed, so a batch that
cannot be authenticated fails without doing work.

> [!WARNING]
>
> **`transactBatch` does not plan the rows.** Two items that spend the same note collide on their
> nullifier, and an item that spends another item's change cannot be proved until that change has
> landed. Give each item its own already-landed input notes; selecting them is the caller's job.
> Above `RELAY_BATCH_AUTH_MAX_ITEMS` the call throws, so chunk the payout. The practical bound is
> lower than 64, because the chain keeps a ring of 100 recent roots and each item consumes room in
> it.

## Solana Kit runtime

Since 0.2.5 the SDK is built on `@solana/kit`. These are the helpers a normal integration touches.

```ts theme={null}
import {
  address,
  addressFromPublicKey, // web3.js PublicKey -> Address
  confirmSignature,
  createCloakRpc, // pass the result as `connection`
  fetchLatestBlockhash,
  generateKeyPairSigner,
  isAddress,
  sendInstructions,
  sendRawTransaction,
  signerFromKeypair,
  signerFromSecretKey,
  signerFromWalletAdapter, // browser wallet-adapter bridge
  toAddress,
  type Address,
  type CloakRpc, // Rpc<SolanaRpcApi> & { readonly endpoint: string }
  type KeyPairSigner,
  type LegacyWalletAdapter,
  type WalletAdapterBridgeOptions,
} from "@cloak.dev/sdk";

declare const secretKey: Uint8Array;
declare const wallet: LegacyWalletAdapter;
declare const bridgeOptions: WalletAdapterBridgeOptions;
declare const publicKey: { toBase58(): string };
declare const wire: Uint8Array;

const rpc: CloakRpc = createCloakRpc("https://your-keyed-mainnet-rpc.example");
const a: Address = address("11111111111111111111111111111111");
const b: Address = toAddress(a);
const c: Address = addressFromPublicKey(publicKey);
const valid: boolean = isAddress("not an address");

const throwaway: KeyPairSigner = await generateKeyPairSigner();
const fromBytes: KeyPairSigner = await signerFromSecretKey(secretKey);
const fromKeypair: KeyPairSigner = await signerFromKeypair({ secretKey });
const walletSigner = signerFromWalletAdapter(wallet, bridgeOptions);

const blockhash = await fetchLatestBlockhash(rpc);
const signature: string = await sendRawTransaction(rpc, wire);
await confirmSignature(rpc, signature);
console.log(b, c, valid, throwaway, fromBytes, fromKeypair, walletSigner, blockhash, sendInstructions);
```

`connection` takes a `CloakRpc`, `programId` and other addresses take Kit `Address` strings, and
`depositorKeypair` takes a `KeyPairSigner`. Wiring a browser wallet is covered in [Solana Kit
integration](https://docs.cloak.ag/sdk/kit-integration.md).

## Protocol and service docs

* [Protocol Architecture](https://docs.cloak.ag/concepts/privacy-architecture.md)
* [Shield Pool Program](https://docs.cloak.ag/concepts/shield-pool-program.md)
* [Transaction Flows](https://docs.cloak.ag/concepts/transaction-lifecycle.md)
* [Code Examples](https://docs.cloak.ag/examples/free-functions.md)


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