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

# Private swaps

> Swap SOL from the private balance into any SPL token through Jupiter, delivered to an address you choose

A private swap spends SOL notes from the private balance, swaps through Jupiter, and delivers the
output token to a public token account. The swap is not linked to the wallet that funded the
balance. Swaps are a low-level feature: `createCloak` does not offer them.

## How a swap works

1. The client proves a spend of SOL notes and submits it. The program escrows the SOL, minus the
   pool's fee, in a swap state account (`TransactSwap`).
2. A follow-up transaction executes the Jupiter route and delivers the output to `recipientAta`. It
   must deliver at least `minOutputAmount`.
3. If the swap cannot execute before its deadline, the escrow becomes reclaimable as a refund note.

| Constraint | Value |
| - | - |
| Input | SOL only (the SOL pool) |
| Output | Any SPL token Jupiter routes to |
| Fee | The SOL pool's withdrawal fee, taken from the input |
| Delivery | A public associated token account you name |

## Prerequisites

* The low-level setup: a `CloakRpc`, `ownerUtxoKeypair` and `nk` from a persistent seed, and your own
  note storage. See [Low-level API](https://docs.cloak.ag/sdk/low-level-api.md).
* SOL notes in the private balance.
* A Jupiter quote for the minimum output. The SDK does not quote; get one from Jupiter for the swap
  amount and apply your slippage.

## Swap

```ts theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  createCloakRpc,
  swapWithChange,
  type Utxo,
  type UtxoKeypair,
  type UtxoSwapResult,
} from "@cloak.dev/sdk";
import type { Address, KeyPairSigner } from "@solana/kit";

declare const signer: KeyPairSigner; // a server key; see the wallet-adapter variant below
declare const ownerUtxoKeypair: UtxoKeypair;
declare const nk: Uint8Array;
declare const solNotes: Utxo[]; // one or two SOL notes covering the swap amount
declare const outputMint: Address;
declare const recipientWallet: Address; // who receives the output
declare const recipientAta: Address; // recipientWallet's token account for outputMint
declare const minOutputAmount: bigint; // from your Jupiter quote, after slippage
declare function persistNotes(notes: Utxo[]): Promise<void>;
declare function saveSwapRefund(swapStatePda: string, refund: UtxoSwapResult["refund"]): Promise<void>;

const swapped = await swapWithChange(
  solNotes,
  200_000_000n, // 0.2 SOL to swap
  outputMint,
  recipientAta,
  minOutputAmount,
  {
    connection: createCloakRpc(process.env.SOLANA_RPC_URL!),
    programId: CLOAK_PROGRAM_ID,
    relayUrl: CLOAK_PRODUCTION_RELAY_URL,
    depositorKeypair: signer,
    walletPublicKey: signer.address,
    ownerUtxoKeypair,
    chainNoteViewingKeyNk: nk,
    onProgress: (status) => console.log(status),
  },
  recipientWallet, // the ATA is created if it does not exist
);

await persistNotes(swapped.outputUtxos); // the SOL you did not swap
await saveSwapRefund(swapped.swapStatePda, swapped.refund); // reclaims the input on a timeout
console.log("swap:", swapped.signature, "state:", swapped.swapStatePda);
```

> [!WARNING]
>
> **Persist two things.** `outputUtxos` is the change. `refund` is the authorization that reclaims the
> principal if the swap times out. Because `chainNoteViewingKeyNk` was passed, `discoverSwapRefunds`
> can rebuild a lost refund from `nk`, but storing it is the fast path.

## From a browser wallet

Replace `depositorKeypair` with `signMessage` and `walletPublicKey` from the wallet adapter. A swap
re-proves on every stale-root retry, and each proof is a new request the wallet must approve. Cap
the prompts with `maxWalletApprovals` (default 5). The full variant is in
[Low-level API](https://docs.cloak.ag/sdk/low-level-api.md#swap-example).

## Tuning

| Option | Default | Use |
| - | - | - |
| `swapSlippageBps` | 500 | Slippage the route may take |
| `swapStatusMaxAttempts`, `swapStatusDelayMs` | 60, 2000 ms | How long to wait for execution |
| `swapDexes`, `swapExcludeDexes` | none | Restrict Jupiter's route |

## Related

* [Fees](https://docs.cloak.ag/concepts/fees.md): the swap fee comes from the SOL input.
* [Transaction lifecycle](https://docs.cloak.ag/concepts/transaction-lifecycle.md#swap-flow)


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