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

# Backend integration

> Run Cloak from a Node.js service: account keys you hold, encrypted storage, idempotent payouts and resumable flows

The SDK runs the same way in Node.js as in a browser: it proves on the machine it runs on, signs, and
submits. A backend integration differs in three decisions: whose account it opens, where it
keeps state, and how it avoids paying twice when a request is retried.

## Prerequisites

* Node 22 or later.
* `@cloak.dev/sdk` 0.2.20 and `@solana/kit`.
* A mainnet RPC with generous limits.
* A database for SDK state, and a secret store for keys.

```bash theme={null}
npm install @cloak.dev/sdk@^0.2.20 @solana/kit
```

## Choose the account model

| Model | Open with | Use when |
| - | - | - |
| **Business mode** | `account: <32-byte key>` | Your service holds each customer's or treasury's account key. No wallet signature at all |
| **Server wallet** | `wallet: signerFromSecretKey(...)` or a Privy server wallet | The account should be the one a specific Solana key opens, anywhere |
| **Cloak Key** | `cloakKey: "<24 words>"` | You operate an account created on cloak.ag |

Business mode is the usual choice for payouts and treasury. Generate a key per account once, keep it
in your secret store, and never log it.

```ts theme={null}
import { randomBytes } from "node:crypto";

// Once per account. Store the hex in your secret manager.
const accountKeyHex = randomBytes(32).toString("hex");
```

## Keep state in your database, encrypted

`createCloak` keeps payment links, open cross-chain orders, payout records and `ref` receipts in
`storage`. The default on a server is memory, which is lost on exit. Wrap your own key-value store
with `encryptedStorage`, which encrypts every value with AES-256-GCM, bound to the key and the
network:

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

// Any store with get and set. Here, a table keyed by string.
declare const kv: {
  get(key: string): Promise<string | null>;
  set(key: string, value: string): Promise<void>;
};

const accounts = new Map<string, Promise<Cloak>>();

export function cloakFor(accountId: string, accountKeyHex: string): Promise<Cloak> {
  let opened = accounts.get(accountId);
  if (!opened) {
    opened = createCloak({
      account: accountKeyHex,
      storage: encryptedStorage(
        { get: (k) => kv.get(`${accountId}:${k}`), set: (k, v) => kv.set(`${accountId}:${k}`, v) },
        process.env.CLOAK_STORAGE_SECRET!, // 32+ random bytes as hex, from your secret store
      ),
      rpc: process.env.SOLANA_RPC_URL,
      onWarning: (message) => console.warn(`[cloak ${accountId}]`, message),
    });
    accounts.set(accountId, opened);
  }
  return opened;
}
```

Keep one `Cloak` object per account per process. Its money-moving calls are serialized, so two calls
never pick the same notes.

## Make every payment idempotent with `ref`

Pass a `ref` on every `shield`, `send` and `withdraw`. A second call with the same `ref` returns the
first receipt with `repeated: true` and moves nothing:

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

export async function payInvoice(invoiceId: string, to: string, amountUsdc: string) {
  const cloak = await cloakFor("treasury", process.env.TREASURY_ACCOUNT_KEY!);
  try {
    const receipt = await cloak.send({ to, token: "USDC", amount: amountUsdc, ref: `invoice-${invoiceId}` });
    return { ok: true as const, repeated: receipt.repeated === true, txs: receipt.txs };
  } catch (e) {
    if (isCloakCallError(e, "ref.unsettled")) {
      // An earlier attempt started and did not record its end. It may have moved money:
      // reconcile before paying again.
      return { ok: false as const, reconcile: true, message: e.message };
    }
    if (isCloakCallError(e)) return { ok: false as const, retryable: e.retryable, code: e.code, message: e.message };
    throw e;
  }
}
```

A `ref` is 1 to 128 printable characters. Use your own stable identifier (invoice, payout row,
withdrawal request).

## Resume what a crash left open

A shield from another chain or a send to one can stop halfway if the process exits. `createCloak`
resumes open work shortly after start, and every minute while something is open. Subscribe to see it:

```ts theme={null}
import { cloakFor } from "./cloak";

const cloak = await cloakFor("treasury", process.env.TREASURY_ACCOUNT_KEY!);
cloak.on("finished", (item) => console.log("finished from an earlier run:", item));
cloak.on("warning", (message) => console.warn(message));

const { finished, problems, openDeposits } = await cloak.resume(); // one pass, on demand
```

This only works if `storage` outlived the crash, which is why the store above is your database.

## Proving on a server

* Each spend generates a Groth16 proof in-process, in worker threads. No prover service is needed.
* The first proof in a process downloads about 23 MB of circuit files and checks their hashes. Warm
  them at boot with `verifyAllCircuits(getCircuitsPath())`.
* Proving is CPU and memory heavy. Size workers for concurrent proofs, or queue spends per process.
  For many payouts in one go, see [Batch signing](https://docs.cloak.ag/sdk/batch-signing.md).

## Exposing Cloak to other languages

There is no Rust or Python SDK. A backend in another language runs a small Node service that holds
the account keys and exposes your own API (pay, balance, quote) to the rest of your system. Keep that
service on a private network: whoever can call it can spend.

## Security checklist

* Account keys and `CLOAK_STORAGE_SECRET` in a secret manager, never in source or logs.
* One `ref` per business operation, persisted before the call.
* Alert on `ref.unsettled`, `payout.screening_refused` and any `*.failed` that is not retryable.
* Rate-limit and authenticate the endpoints that trigger spends.
* Back up the storage table: it holds receipts and open orders.

See [Security considerations](https://docs.cloak.ag/resources/security.md) for the full list.

## Related

* [Backend orchestration example](https://docs.cloak.ag/examples/backend-orchestration.md): a complete payout worker.
* [Payroll](https://docs.cloak.ag/guides/payroll.md): many recipients, one run.
* [createCloak](https://docs.cloak.ag/sdk/create-cloak.md#business-mode)


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