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

# createCloak

> One call per action: open the account from a wallet, then shield, send, withdraw, quote, read the balance and make payment links

`createCloak` is the SDK's front door. It opens the user's account from one wallet signature and
returns an object with one call per action. The SDK finds and picks the notes, merges them when it
needs to, adds the fee on a withdrawal, keeps what it must remember in `storage`, and finishes
anything an earlier run left open. It is built on the [free functions](https://docs.cloak.ag/sdk/low-level-api.md),
which stay exported for full control.

Everything on this page is exported by `@cloak.dev/sdk` 0.2.20.

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

const cloak = await createCloak({ wallet, rpc: "https://<your-mainnet-rpc>" });

await cloak.shield({ from: "solana", token: "USDC", amount: "10" });
await cloak.send({ to: "cloak_…", token: "USDC", amount: "1" }); // private
await cloak.withdraw({ to: "<a Solana address>", token: "USDC", amount: "2" }); // exactly 2 arrive
console.log(await cloak.balance()); // { USDC: "…", USDT: "0", SOL: "0", BRS: "0" }
```

## Opening the account

The account is the one the Cloak mobile app shows for the same wallet: the SDK asks the wallet to
sign one fixed message and derives the account's keys from the signature. The first time a wallet is
seen in `storage` it signs twice, so the SDK can check that it signs the same way each time. The signature rebuilds
everything, so the same wallet opens the same account on any device.

| Option | Opens |
| - | - |
| `wallet`, or `wallets: [...]` | The account of the first wallet that can sign. Every other wallet is linked to that account (one signature each), so any of them opens it next time. |
| `cloakKey: "24 words"` | A cloak.ag account, from its Cloak Key (or the mobile app's in-app wallet words). Wallets passed with it are linked to it. |
| `account: key` | Business mode: an account key you hold (32 bytes, or 64 hex characters). No wallet opens it, and none is linked to it. |
| `allowStoredAccount: true` | For a wallet that cannot sign the same message the same way twice (a passkey smart wallet): a new account key is created, kept in `storage`, and its 24 backup words are returned once, in `cloak.backupWords`. Off by default, and such a wallet is refused. |

Once open, `cloak.address` is the `cloak_` address to share to get paid privately,
`cloak.accountId` a public id that stays the same across devices and wallets, and `cloak.wallets`
the wallets the object can use (`{ name, chain, address, networks }`). `cloak.connect(wallet)` adds
one later; `cloak.disconnect(wallet, { unlink: true })` drops one and forgets its link.

### The wallets it takes

`wallet` is whatever your wallet library hands you; the SDK recognizes it (`recognizeWallet`):

* `useWallet()` from `@solana/wallet-adapter-react`, or a wallet-adapter adapter;
* a Wallet Standard wallet (Phantom, Solflare, Backpack, Slush, Suiet);
* `window.ethereum`, or an EIP-6963 provider from `discoverEvmWallets()`;
* a Privy wallet;
* a `@solana/kit` signer or a web3.js `Keypair`, a viem `WalletClient` or an ethers `Signer` (keys a
  server holds);
* a Sui key pair;
* or `{ chain, address, signMessage, signTransaction, sendTransaction }`.

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

const [evmWallet] = await discoverEvmWallets();
const cloak = await createCloak({ wallets: [solanaWallet, evmWallet], rpc: SOLANA_RPC_URL });
console.log(cloak.wallets.map((w) => `${w.name}: ${w.networks.join(", ")}`));
```

Spends never prompt the wallet and need no SOL: their requests are signed by a key derived from the
account. A wallet is asked to sign the account message once, and to sign what moves its own funds,
which is a shield from it.

### Options

| Option | Default | |
| - | - | - |
| `rpc` | the public mainnet endpoint (rate-limited) | A Solana RPC URL or a `CloakRpc`. Pass your own for anything beyond a demo. |
| `storage` | the browser's `localStorage`, else memory | Where links, open orders and payouts are kept. A server passes its own (see [Business mode](#business-mode)). |
| `resume` | `true` | Finish what earlier calls left open, shortly after start and again while an order is open. |
| `secureExposedNotes` | `true` | Move notes an older client left readable by others into the account before they are spent. |
| `affiliateCode` | none | An approved partner code, attached to fee-bearing requests ([Earn with the SDK](https://docs.cloak.ag/affiliates/sdk-integration.md)). |
| `onWarning` | none | Non-fatal events: a wallet that could not be linked, a partner code that was dropped. |
| `web3` | none | web3.js `{ VersionedTransaction }`, for a legacy Solana adapter (Ledger) in a bundled app. |

There is no endpoint option: the package talks to the one Cloak endpoint it was built with.

## Tokens and destinations

The private balance holds USDC, USDT, SOL and BRS, each in its own pool. Every call names its
token, and a call whose route cannot carry that token is refused before anything moves.

`to` takes:

| Value | Means |
| - | - |
| a `cloak_` address | a private send, inside the pool |
| a Solana address | a withdrawal to that address |
| `0x…` with `chain: "base"` or `"polygon"` | a send to that network |
| a Sui address | a send to Sui |
| a Tron address (`T…`) | a send to Tron: USDC leaves the private balance, USDT arrives |
| a connected wallet (from `cloak.wallets`) | that wallet's address on its network |

For a shield, `from` is `"solana"`, `"base"`, `"polygon"`, `"sui"`, or a connected wallet; with an
EVM wallet, `chain` picks the network. Which tokens each network takes, the minimums and the route
each one uses are on [Other networks](https://docs.cloak.ag/guides/cross-chain.md).

## The calls

| Call | Does | Resolves with |
| - | - | - |
| `balance()` | the private balance per token, as decimal strings | `{ USDC, USDT, SOL, BRS }` |
| `notes()` | the notes behind it (`token`, `amount`, `from`, `tx`, `exposed`) | a list, with `encryptToSave` |
| `quote(request)` | what a shield, send or withdrawal would deliver; moves nothing | `{ arrives, fee, networkFee? }` |
| `shield(request)` | into the private balance, from Solana or another network | a receipt |
| `send(request)` | privately to a `cloak_` address, or to an address on Solana or another network | a receipt |
| `withdraw(request)` | to a public address; on Solana exactly `amount` arrives and the fee comes on top | a receipt |
| `resume()` | one pass over open deposits and sends | `{ finished, problems, openDeposits, openSends? }` |
| `secureExposedNotes()` | move exposed notes into the account now | how many moved |
| `createPaymentLink(request)` | a link that holds money: whoever opens it can claim it | `{ url, token, amount, ref?, receipt? }` |
| `claimPaymentLink(url, options?)` | claim a link into this balance, or `to` a Solana address | a receipt |
| `paymentLinks()` | the links this account made, and whether each was claimed | a list |
| `requestPayment(request)` | a link that asks for money; the note arrives in this balance | `{ url, id, token, amount, label, paid, … }` |
| `payRequest(url)` | pay a payment request from this balance | a receipt |
| `requests()` | the requests this account made, and whether each was paid | a list |
| `on(event, handler)` | `warning`, `secured`, `finished` (see [Events and callbacks](https://docs.cloak.ag/reference/events-and-callbacks.md)) | a function that unsubscribes |

The money calls take `onProgress: (step) => …` for status text, and `shield`, `send` and `withdraw`
also take `signal` (an `AbortSignal`). Payment links use cloak.ag's format, so the website claims a
link the SDK made and the other way round; the URL's secret is the part after `#`, so treat the
whole URL like cash.

### Quote before you move

```ts theme={null}
const q = await cloak.quote({ to: "0x07f0…", chain: "base", token: "USDC", amount: "5" });
console.log(`${q.arrives.atLeast} ${q.arrives.token} arrives on ${q.arrives.network}, fee ${q.fee}`);
```

`arrives.atLeast` is the least that arrives, the route's signed floor where the route signs one.
`fee` is everything between what leaves the private balance and what arrives, in the arriving token.
`networkFee` appears when a fee is paid in another chain's own coin (BRS through LayerZero).

### Receipts

```ts theme={null}
const receipt = await cloak.withdraw({ to: "<a Solana address>", token: "USDC", amount: "2" });
console.log(receipt.status, receipt.amount, receipt.fee, receipt.txs.solana);
```

| Field | |
| - | - |
| `status` | `"shielded"`, `"sent"`, `"withdrawn"`, `"delivered"`, `"on its way"` or `"claimed"` |
| `token`, `amount` | what arrived, or will arrive, in the arriving token |
| `fee` | every fee on the way, in the arriving token |
| `sent` | for a shield from another network: what left the origin wallet (`"6 USDC"`, `"0.0014 ETH"`) |
| `networkFee` | a fee paid in another chain's own coin |
| `txs` | transaction ids per network: `{ solana: "…", base: "0x…" }` |
| `notes` | how many notes the call spent and created |
| `repeated` | `true` when this is the stored receipt of an earlier call with the same `ref`: nothing moved now |
| `track` | for a send to another network made with `wait: false`: resolves with the delivered receipt |

A send to another network resolves once it is delivered. Pass `wait: false` to resolve as soon as it
is sent (`status: "on its way"`), and call `receipt.track()` later.

## Business mode

A server that holds its customers' keys opens each account with `account`, keeps the records in its
own database, encrypted, and names every money call with a `ref`, so a retry never pays twice:

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

declare const db: {
  get(key: string): Promise<string | null>;
  set(key: string, value: string): Promise<void>;
};

const cloak = await createCloak({
  account: process.env.CUSTOMER_ACCOUNT_KEY, // 64 hex characters you hold
  storage: encryptedStorage(db, process.env.STORAGE_SECRET!),
  rpc: process.env.SOLANA_RPC_URL,
});

// Asking again with the same ref returns the first receipt (`repeated: true`) and moves nothing.
await cloak.send({ to: "cloak_…", token: "USDC", amount: "25", ref: "payout-77" });
```

`encryptedStorage(db, secret)` wraps any store that has `get` and `set` in AES-256-GCM, bound to the
key and the network. A `ref` works on `shield`, `send` and `withdraw`; on `createPaymentLink` it
derives the link's secret, so the same `ref` always rebuilds the same link.

To keep a copy of the notes themselves, save them encrypted and import them on any machine that
opens the same account:

```ts theme={null}
const saved = await (await cloak.notes()).encryptToSave(secret); // one string, bound to this account
const { imported, skipped } = await cloak.importNotes(saved, secret); // only notes still unspent
```

The secret is 32 bytes or more, or a passphrase of 12 characters or more. `restoreNotes(saved,
secret)` reads the same string without opening an account.

## When something goes wrong

Every call throws a `CloakCallError` (`isCloakCallError(e)`), which carries:

* `code`: stable and dotted (`payout.refused`, `wallet.rejected`). Match on it, never on the message.
* `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.

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

try {
  await cloak.send({ to, token: "USDC", amount: "5" });
} catch (e) {
  if (!isCloakCallError(e)) throw e;
  console.error(String(e)); // "CloakError [code], retryable", then the message with moneyAt and next
  if (isCloakCallError(e, "payout")) {
    // any payout.* code
  }
}
```

| Codes | Means |
| - | - |
| `wallet.*` | the wallet: `not_connected`, `rejected` (the wallet declined), `cannot_sign`, `none_for_chain` (no connected wallet on that network), `unrecognized` |
| `account.*`, `secret.*`, `storage.*` | opening the account, or its storage |
| `token.missing`, `amount.invalid`, `amount.too_precise`, `ref.invalid`, `quote.incomplete` | the request itself; nothing moved |
| `route.*` | the destination: `unsupported` (not a route for that token), `ambiguous` (an EVM address without `chain`), `unknown`, `private` (a withdrawal to a `cloak_` address), `unavailable` (the route is not serving right now; retryable) |
| `balance.insufficient` | the private balance cannot cover it |
| `shield.*` | a shield: `insufficient_funds` and `no_gas` (checked before anything is reserved), `closed` (the route closed the order; `moneyAt` says whether it refunded), and the rest by name |
| `deposit.*` | money that arrived but is not shielded yet: `below_minimum`, `receiver_busy`, `origin_reverted`, `finish_failed`. When `retryable`, Cloak finishes it by itself |
| `payout.refused` | this recipient or amount cannot be paid (a token contract, an amount under the minimum); refused before anything is asked or moved |
| `payout.screening_refused` | sanctions screening refused the recipient; final, and nothing moved |
| `payout.failed`, `send.failed`, `withdraw.failed` | the call did not complete; `moneyAt` and `next` say where the money is |
| `link.*`, `request.*` | payment links and payment requests (`link.claimed`: someone already claimed it) |
| `notes.*` | saved notes: `wrong_secret`, `other_account`, `wrong_network`, `corrupt` |

Every code, with when it is thrown and whether it is retryable, is in [Error codes](https://docs.cloak.ag/reference/errors.md#every-cloakcallerror-code).

## Finishing what stopped

A shield from another network, or a send to one, can stop halfway: a closed tab, a dropped
connection. On the next start, and again while an order is open, the SDK finishes it, and
`cloak.resume()` runs a pass on demand. Each item it finishes arrives as a `finished` event:

```ts theme={null}
cloak.on("finished", (item) => console.log("finished from an earlier run:", item));
const { finished, problems, openDeposits } = await cloak.resume();
```

Open orders and sends are kept in `storage`, so a server needs one that outlives the process.

## What `createCloak` does not do

* **Private swaps.** Use `swapWithChange` ([Code examples](https://docs.cloak.ag/examples/free-functions.md)).
* **Choosing notes, building proofs or submitting yourself.** Use the
  [free functions](https://docs.cloak.ag/sdk/low-level-api.md) it is built on.


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