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

# Low-level end-to-end

> Mainnet examples for send, swap, payroll and compliance history, on both the server keypair path and the browser wallet-adapter path

All examples target `@cloak.dev/sdk` 0.2.20 on Solana mainnet (test with
small amounts) and use the program ID `CLOAK_PROGRAM_ID`:

* `zh1eLd6rSphLejbFfJEneUwzHRfMKxgzrgkfwA6qRkW`

For a first run, start with the [Quickstart](https://docs.cloak.ag/get-started/quickstart.md).

## One call per action

The SDK's maintained partner example, as a script: it opens the account from the wallet's
signature, shields USDC from Solana, sends part of it privately, withdraws to a Solana address and
pays out to Base, one call each. The SDK finds and picks the notes, merges them when needed, adds
the fee on a withdrawal, and finishes anything an earlier run left open. See
[createCloak](https://docs.cloak.ag/sdk/create-cloak.md) for every call.

```ts theme={null}
import { readFileSync } from "node:fs";
import { createCloak, isCloakCallError, memoryStorage, signerFromSecretKey } from "@cloak.dev/sdk";

const wallet = await signerFromSecretKey(
  Uint8Array.from(JSON.parse(readFileSync(process.env.KEYPAIR_PATH!, "utf8")) as number[]),
);
const cloak = await createCloak({ wallet, rpc: process.env.SOLANA_RPC_URL, storage: memoryStorage() });
cloak.on("finished", (item) => console.log("finished from an earlier run:", item));
console.log("Cloak address:", cloak.address);

try {
  console.log(await cloak.shield({ from: "solana", token: "USDC", amount: "5" }));
  if (process.env.PAY_TO) console.log(await cloak.send({ to: process.env.PAY_TO, token: "USDC", amount: "1" }));
  if (process.env.WITHDRAW_TO) console.log(await cloak.withdraw({ to: process.env.WITHDRAW_TO, token: "USDC", amount: "1" }));
  if (process.env.BASE_TO) console.log(await cloak.send({ to: process.env.BASE_TO, chain: "base", token: "USDC", amount: "3.5" }));
  console.log("Balance:", await cloak.balance());
} catch (e) {
  // Every error names its code, whether a retry can work, and where the money is.
  console.error(isCloakCallError(e) ? String(e) : e);
  process.exitCode = 1;
}
```

`PAY_TO` is a `cloak_` address, `WITHDRAW_TO` a Solana address and `BASE_TO` a Base address, each
optional. The wallet needs the USDC and a little SOL for the deposit. The rest of this page uses the
free functions, for full control and for private swaps.

## Pick your path before you copy anything

> [!WARNING]
>
> Everything under [Shared setup](#shared-setup) is the server keypair path. It passes
> `depositorKeypair`, which a browser wallet adapter cannot supply: an adapter holds no secret key.
> Deposits work on either path, but every other flow here is submitted for you and carries an
> authenticated sender, so from a browser you pass `signMessage` plus `walletPublicKey` instead.
> Copying `depositorKeypair` into a frontend is what produces a `401` on the first send after a deposit
> that looked fine. Read [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md) first, or start from
> [the wallet-adapter version of the send flow](#the-same-send-from-a-browser-wallet-adapter) below.

| You are writing | Pass in `TransactOptions` | Prompts the user |
| - | - | - |
| A Node service, a CLI, a script | `depositorKeypair` and `walletPublicKey` | no |
| A browser app on wallet-adapter | `signer` (from `signerFromWalletAdapter`), `signMessage` and `walletPublicKey` | yes, once per submitted request |

Nothing else differs. The parameters, the amounts, the helpers and the results are identical on both
paths; only the signer changes.

> [card] [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md)
>
> Which flows need a signed sender, the 300-second approval window, how many wallet prompts to
> expect, and what to do when a request is rejected.

## Shared setup

Set `KEYPAIR_PATH` (a Solana keypair file) and `SEED_HEX_FILE` (a file holding your 32-byte seed as
hex, from `generateMasterSeed().seedHex`) before running anything below.

```typescript theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  NATIVE_SOL_MINT,
  createRecoverableDepositUtxo,
  createZeroUtxo,
  deriveSpendKey,
  deriveUtxoKeypairFromSpendKey,
  fullWithdraw,
  getNkFromUtxoPrivateKey,
  hexToBytes,
  partialWithdraw,
  serializeUtxo,
  swapWithChange,
  transact,
  scanTransactions,
  toComplianceReport,
  type Utxo,
  address,
  createCloakRpc,
  generateKeyPairSigner,
  signerFromSecretKey,
  type Address,
  type UtxoSwapResult,
} from "@cloak.dev/sdk";
import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS } from "@solana-program/token";
import { appendFileSync, readFileSync } from "node:fs";

const USDC_MINT = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const USDT_MINT = address("Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB");

// Your own RPC. Cloak never inspects, replaces or proxies it.
const connection = createCloakRpc("https://api.mainnet-beta.solana.com");
const signer = await signerFromSecretKey(
  Uint8Array.from(JSON.parse(readFileSync(process.env.KEYPAIR_PATH!, "utf8"))),
);

// Keys come from one persistent 32-byte seed (created once with `generateMasterSeed()` and
// stored like a private key; a lost seed loses the notes). Here it is read from SEED_HEX_FILE.
const seed = hexToBytes(readFileSync(process.env.SEED_HEX_FILE!, "utf8").trim());
const { sk_spend } = deriveSpendKey(seed);
const ownerUtxoKeypair = await deriveUtxoKeypairFromSpendKey(sk_spend);
// View-only: finds and reads notes, can never spend them.
const viewingKeyNk = getNkFromUtxoPrivateKey(ownerUtxoKeypair.privateKey);

// Server keypair path: `depositorKeypair` signs both the deposit transaction and
// every submitted request, without prompting. Every spend flow requires
// `ownerUtxoKeypair` and the wallet `nk`; pass both on deposits too.
const baseOptions = {
  connection,
  programId: CLOAK_PROGRAM_ID,
  relayUrl: CLOAK_PRODUCTION_RELAY_URL,
  depositorKeypair: signer,
  walletPublicKey: signer.address,
  chainNoteViewingKeyNk: viewingKeyNk,
  ownerUtxoKeypair,
};

// A deposit note owned by the wallet keypair, with a blinding the wallet's `nk`
// can re-derive. Pass the returned `noteSalt` to `transact` as `chainNoteSalt`.
async function deposit(amount: bigint, mint: Address) {
  const { utxo, noteSalt } = await createRecoverableDepositUtxo({
    amount,
    viewingKeyNk: viewingKeyNk,
    ownerUtxoKeypair,
    mintAddress: mint,
  });
  return transact(
    {
      inputUtxos: [await createZeroUtxo(mint)],
      outputUtxos: [utxo],
      externalAmount: amount,
      depositor: signer.address,
    },
    { ...baseOptions, chainNoteSalt: noteSalt },
  );
}

// The SDK stores nothing for you. `serializeUtxo` is the 128-byte encoding that
// carries everything a note needs to stay spendable: amount, private key,
// blinding, mint and leaf index. Two append-only files stand in here for whatever
// durable store your service already has.
const NOTES_FILE = "./cloak-notes.jsonl";
const SWAP_REFUNDS_FILE = "./cloak-swap-refunds.jsonl";

function saveNotes(utxos: Utxo[]): void {
  for (const utxo of utxos) {
    if (utxo.amount === 0n) continue; // padding output, nothing to lose
    const line = JSON.stringify({
      mint: utxo.mintAddress,
      amount: utxo.amount.toString(),
      note: Buffer.from(serializeUtxo(utxo)).toString("base64"),
    });
    appendFileSync(NOTES_FILE, `${line}\n`);
  }
}

// Swaps only. `refund` reclaims the swap input if the swap times out before it
// settles, so it is stored next to the notes rather than inside them.
function saveSwapRefund(
  swapStatePda: string,
  refund: UtxoSwapResult["refund"],
): void {
  appendFileSync(
    SWAP_REFUNDS_FILE,
    `${JSON.stringify({ swapStatePda, ...refund })}\n`,
  );
}
```

> [!NOTE]
>
> `relayUrl` is a value you pass on every call, and it is not read from the environment. The SDK
> reads no environment variable for it, so exporting `CLOAK_RELAY_URL` does nothing on its own. If you
> like that convention, read the variable in your own code and pass the value as `relayUrl`; the value
> still has to be an origin on this build's allowlist, which is what the exported
> `CLOAK_PRODUCTION_RELAY_URL` is. Omitting `relayUrl`, or passing `""`, throws
> `Viewing key registration is mandatory: relayUrl is required.` before any network call, on every
> flow including deposits. `""` only means "I will submit this myself" when
> `enforceViewingKeyRegistration` is also set to `false`, because the viewing-key gate runs first
> and fires either way. See the warning in [Cloak SDK](https://docs.cloak.ag/get-started/introduction.md) before you reach for that
> pair: it is a privacy hazard on a transfer or a withdrawal, not a configuration shortcut.

> [!WARNING]
>
> Write `result.outputUtxos` down before you report success. Every call on this page returns the
> notes it just created and then forgets them. A change note is your own money coming back. With the
> keys derived from your seed, deposit and change notes the SDK creates can be found again by a scan
> (`scanTransactions` returns `recoveredDepositNotes` and `recoveredChangeNotes`), but that is a
> recovery path, not a plan: it needs the same seed, a scan of the chain, and a note built without
> the SDK's recoverable helpers is gone for good if you drop it. That is why every example below
> captures its result and calls `saveNotes` at the point where your service would commit to its own
> database. The browser version of
> `saveNotes` is in [the wallet-adapter example](#the-same-send-from-a-browser-wallet-adapter) below;
> for the two storage exports the SDK ships, read
> [where your notes live between sessions](https://docs.cloak.ag/wallets/wallet-adapter.md#where-your-notes-live-between-sessions).

## Send flow (SOL->SOL, USDC->USDC, USDT->USDT)

```typescript theme={null}
async function sendSameMint(args: {
  mint: Address;
  amount: bigint;
  recipientWallet: Address;
  partialWithdrawAmount?: bigint; // use for partial withdrawal example
}) {
  const deposited = await deposit(args.amount, args.mint);

  // Store the deposit note first. If the withdrawal below throws, this file is the
  // only claim anyone has on the funds that just entered the pool.
  saveNotes(deposited.outputUtxos);

  if (args.partialWithdrawAmount !== undefined) {
    const withdrawn = await partialWithdraw(
      deposited.outputUtxos,
      args.recipientWallet,
      args.partialWithdrawAmount,
      {
        ...baseOptions,
        cachedMerkleTree: deposited.merkleTree,
      },
    );

    // The recipient got their part; the remainder came back as a private change
    // note. Store it before you tell anyone the payment succeeded.
    saveNotes(withdrawn.outputUtxos);
    return withdrawn;
  }

  const withdrawn = await fullWithdraw(
    deposited.outputUtxos,
    args.recipientWallet,
    {
      ...baseOptions,
      cachedMerkleTree: deposited.merkleTree,
    },
  );

  // This call is given one note, so it withdraws directly and leaves no change.
  // That is a property of the input count, not of `fullWithdraw`: hand it three or
  // more notes and it consolidates on chain first. Call `saveNotes` regardless, so
  // the call site never has to know which flow produced change.
  saveNotes(withdrawn.outputUtxos);
  return withdrawn;
}

// SOL -> SOL (full withdrawal send)
await sendSameMint({
  mint: NATIVE_SOL_MINT,
  amount: 1_000_000_000n,
  recipientWallet: (await generateKeyPairSigner()).address,
});

// USDC -> USDC (recipient wallet must have a USDC ATA)
await sendSameMint({
  mint: USDC_MINT,
  amount: 8_000_000n,
  recipientWallet: (await generateKeyPairSigner()).address,
});

// USDT -> USDT (recipient wallet must have a USDT ATA)
await sendSameMint({
  mint: USDT_MINT,
  amount: 8_000_000n,
  recipientWallet: (await generateKeyPairSigner()).address,
});

// Partial withdrawal example (withdraw part, keep private change)
await sendSameMint({
  mint: NATIVE_SOL_MINT,
  amount: 1_000_000_000n,
  recipientWallet: (await generateKeyPairSigner()).address,
  partialWithdrawAmount: 250_000_000n,
});
```

## The same send from a browser wallet adapter

Same functions, same arguments, same results. The only change is the signing options: `signer`
(the wallet, wrapped by `signerFromWalletAdapter`) signs the deposit, which the wallet submits
directly, and `signMessage` authenticates the withdrawal request, with `walletPublicKey` as the
sender. The wallet keys (`ownerUtxoKeypair`, `nk`) come from your wallet's seed exactly as in the
server setup above; the hook below receives them as arguments.

```tsx theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  createCloakRpc,
  createRecoverableDepositUtxo,
  createZeroUtxo,
  explainRelayAuthRejection,
  fullWithdraw,
  serializeUtxo,
  signerFromWalletAdapter,
  transact,
  type Address,
  type CloakRpc,
  type UtxoKeypair,
  type Utxo,
} from "@cloak.dev/sdk";
import { useWallet } from "@solana/wallet-adapter-react";

// Cloak takes its own Kit RPC, not the wallet-adapter `Connection`.
const connection = createCloakRpc(process.env.NEXT_PUBLIC_SOLANA_RPC_URL!);

// The browser stand-in for the server path's append-only file, and the same
// `serializeUtxo` encoding: amount, private key, blinding, mint and leaf index.
// `localStorage` is the smallest thing that survives a reload; move to IndexedDB
// or your own backend when you outgrow it. See /wallets/wallet-adapter for the
// two storage exports the SDK ships.
const NOTES_KEY = "myapp.cloak.notes";

function saveNotes(utxos: Utxo[]): void {
  const stored: string[] = JSON.parse(
    window.localStorage.getItem(NOTES_KEY) ?? "[]",
  );
  for (const utxo of utxos) {
    if (utxo.amount === 0n) continue; // padding output, nothing to lose
    stored.push(btoa(String.fromCharCode(...serializeUtxo(utxo))));
  }
  window.localStorage.setItem(NOTES_KEY, JSON.stringify(stored));
}

export function useSendSameMint(
  connection: CloakRpc,
  ownerUtxoKeypair: UtxoKeypair,
  viewingKeyNk: Uint8Array,
) {
  const wallet = useWallet();

  return async function sendSameMint(args: {
    mint: Address;
    amount: bigint;
    recipientWallet: Address;
  }) {
    // Not every adapter implements signMessage. Check before you offer the action, so
    // the user is never asked to approve and then told their wallet cannot sign.
    if (!wallet.publicKey || !wallet.signTransaction || !wallet.signMessage) {
      throw new Error("Connect a wallet that supports message signing.");
    }
    const { signMessage } = wallet;

    // The connected wallet as a Kit signer. `@solana/web3.js` must be installed.
    const signer = signerFromWalletAdapter(wallet);

    const walletOptions = {
      connection,
      programId: CLOAK_PROGRAM_ID,
      relayUrl: CLOAK_PRODUCTION_RELAY_URL,

      // ── the wallet-adapter replacement for `depositorKeypair` ──
      signer, // signs the deposit transaction
      signMessage, // signs the request preimage on submitted flows
      depositorPublicKey: signer.address,
      walletPublicKey: signer.address, // the authenticated `sender`
      // ──────────────────────────────────────────────────────────

      chainNoteViewingKeyNk: viewingKeyNk,
      ownerUtxoKeypair, // required on every spend flow
      onProgress: (status: string) => console.log(status),
      onProofProgress: (percent: number) => console.log(`proof ${percent}%`),
    };

    const { utxo, noteSalt } = await createRecoverableDepositUtxo({
      amount: args.amount,
      viewingKeyNk,
      ownerUtxoKeypair,
      mintAddress: args.mint,
    });

    // Deposit: signed by the wallet, submitted directly. No authenticated sender.
    const deposited = await transact(
      {
        inputUtxos: [await createZeroUtxo(args.mint)],
        outputUtxos: [utxo],
        externalAmount: args.amount,
        depositor: signer.address,
      },
      { ...walletOptions, chainNoteSalt: noteSalt },
    );

    // Store the deposit note before going any further. If the send below fails, or
    // the user closes the tab while the wallet dialog is open, this is the only
    // claim on the funds that just entered the pool.
    saveNotes(deposited.outputUtxos);

    // Send: submitted for you, so this is the call that needs the signed sender.
    try {
      const withdrawn = await fullWithdraw(
        deposited.outputUtxos,
        args.recipientWallet,
        {
          ...walletOptions,
          cachedMerkleTree: deposited.merkleTree,
        },
      );

      // One input note here, so there is no change and nothing to write. With three
      // or more, `fullWithdraw` consolidates on chain first and the exemption stops
      // holding. Keep the call so any flow swapped in stays safe.
      saveNotes(withdrawn.outputUtxos);
      return withdrawn;
    } catch (error) {
      const hint = explainRelayAuthRejection(String(error));
      throw hint ? new Error(hint, { cause: error }) : error;
    }
  };
}
```

`partialWithdraw` and `swapWithChange` take the same `walletOptions` object; swap it in wherever the
server examples spread `baseOptions`. Both of them do return a change note, so the `saveNotes` call
above stops being a no-op the moment you substitute one, and `swapWithChange` needs its `refund`
stored under a second key as well, for the reason given in the swap section below.

> [!NOTE]
>
> `walletPublicKey` and `depositorPublicKey` are the same end user here, which is why both are set to
> `publicKey`. Passing two different keys throws: the SDK uses one key for the request's sender, for
> screening and for viewing-key registration, so splitting it would authenticate one person and screen
> another.

## SOL swap flow (SOL -> token)

```typescript theme={null}
// `deposit` is the helper from the shared setup above.
const swapDeposit = await deposit(600_000_000n, NATIVE_SOL_MINT);

const recipientWallet = (await generateKeyPairSigner()).address;
const [recipientUsdcAta] = await findAssociatedTokenPda({
  mint: USDC_MINT,
  owner: recipientWallet,
  tokenProgram: TOKEN_PROGRAM_ADDRESS,
});

saveNotes(swapDeposit.outputUtxos);

const swapped = await swapWithChange(
  [swapDeposit.outputUtxos[0]],
  300_000_000n, // amount to swap
  USDC_MINT,
  recipientUsdcAta,
  1n, // replace with quote-based min output
  {
    ...baseOptions,
    cachedMerkleTree: swapDeposit.merkleTree,
  },
  recipientWallet,
);

// A swap hands back two things worth keeping, and they are not the same thing.
saveNotes(swapped.outputUtxos); // the 300_000_000n of SOL you did not swap
saveSwapRefund(swapped.swapStatePda, swapped.refund); // reclaims the input on a timeout
```

> [!WARNING]
>
> `result.refund` is the other secret a swap produces, and dropping it is how a timed-out swap
> becomes unrecoverable. If the swap does not settle, the program locks the principal behind an
> amount-bound refund note, and the values in `refund` are what spend it. Because `baseOptions` passes
> `chainNoteViewingKeyNk`, the secret here is derived from your `nk` and comes back with
> `derivedFromNk: true`, so `matchSwapRefundLeaf` can rebuild it from that key plus the swap's first
> input nullifier. Storing it is still the fast path, and when no `nk` was supplied the returned object
> is the only copy that will ever exist.
> Field-by-field detail is in the [API reference](https://docs.cloak.ag/reference/api.md).

> [!NOTE]
>
> Swaps are the one flow that can prompt more than once. A swap re-proves on every stale-root
> retry, and each new proof is a new request that needs a fresh approval, so on the wallet-adapter path
> add `maxWalletApprovals` (default `5`, floored at `1`) to cap how many dialogs one swap may raise. A
> `depositorKeypair` never prompts. Sends and withdrawals sign once per submitted request: network
> retries re-send it, and only a stale Merkle root forces a new proof and a new prompt.

## Payroll flow (multi-recipient private payouts)

```typescript theme={null}
const payroll = [
  { wallet: (await generateKeyPairSigner()).address, amount: 250_000_000n },
  { wallet: (await generateKeyPairSigner()).address, amount: 400_000_000n },
  { wallet: (await generateKeyPairSigner()).address, amount: 350_000_000n },
];

const receipts: { wallet: string; signature: string }[] = [];

for (const payment of payroll) {
  // `sendSameMint` stores the notes each iteration produces before it returns, which
  // is what makes a failure halfway through survivable: the paid runs are settled and
  // the failed run's deposit note is already on disk. A loop is the last place to
  // await a flow and drop the result.
  const paid = await sendSameMint({
    mint: NATIVE_SOL_MINT,
    amount: payment.amount,
    recipientWallet: payment.wallet,
  });

  receipts.push({
    wallet: payment.wallet,
    signature: paid.signature,
  });
}
```

> [!WARNING]
>
> A loop like this belongs on the server path. Each iteration is a deposit plus a submitted send,
> so on a wallet adapter it is two approval dialogs per recipient, in sequence, and each request has to
> be approved inside its window: the user has 285 seconds from the moment they are asked, not from the
> moment the run started. A payroll of any size run from a browser tab will strand itself on an
> unattended prompt.

## History + compliance scan

```typescript theme={null}
// Reuse the same `viewingKeyNk` configured in your transaction options.
// This is a read-only scan: it signs nothing and prompts nobody, on either path.

const scan = await scanTransactions({
  connection,
  programId: CLOAK_PROGRAM_ID,
  viewingKeyNk,
  ownerUtxoPublicKey: ownerUtxoKeypair.publicKey, // matches your own deposits
  limit: 250,
});

const report = toComplianceReport(scan);
console.log(report.summary);
```

## Related pages

> [card] [Request authentication](https://docs.cloak.ag/sdk/request-authentication.md)
>
> The signed-sender contract for every submitted flow, on both paths.

> [card] [Wallet integration](https://docs.cloak.ag/wallets/wallet-adapter.md#where-your-notes-live-between-sessions)
>
> Where your notes live between sessions, plus the full wallet-adapter wiring, progress callbacks
> and stale-root retries.

> [card] [Error handling](https://docs.cloak.ag/reference/errors.md)
>
> `CloakError` categories, `parseError`, and the stale-root retry template.

> [card] [API reference](https://docs.cloak.ag/reference/api.md)
>
> The full exported surface, including every symbol on this page.


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