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

> A payout worker: business-mode account, encrypted storage, an idempotent job queue, retries and crash recovery

A Node.js worker that pays out from a treasury's private balance. Your application inserts payout
jobs into a table; the worker takes them one at a time, pays each exactly once, and records the
result. It survives restarts, retries what can be retried, and parks what needs a human.

The patterns are explained in [Backend integration](https://docs.cloak.ag/sdk/backend-integration.md). This page is the code.

## Prerequisites

* Node 22 or later, `@cloak.dev/sdk` 0.2.20.
* A database with two tables: a key-value table for SDK state and a jobs table. Any database works;
  the code below talks to them through small interfaces you implement.
* In your secret store: the treasury account key (32 random bytes as hex) and a storage secret
  (32 random bytes as hex).

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

## The jobs table

| Column | Type | Notes |
| - | - | - |
| `id` | text, primary key | Your stable payout id; becomes the `ref` |
| `to` | text | A `cloak_` address, a Solana address, or a Base, Polygon, Sui or Tron address |
| `chain` | text, nullable | `base` or `polygon` for an EVM address |
| `amount` | text | Decimal string in USDC |
| `status` | text | `queued`, `paid`, `retry`, `needs_review`, `refused` |
| `attempts` | integer | |
| `result` | json | The receipt, or the error code and message |

## The worker

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

interface Job {
  id: string;
  to: string;
  chain: string | null;
  amount: string;
  attempts: number;
}

// Implement these against your database.
declare const kv: {
  get(key: string): Promise<string | null>;
  set(key: string, value: string): Promise<void>;
};
declare const jobs: {
  next(): Promise<Job | null>; // oldest `queued` or due `retry` job, locked for this worker
  paid(id: string, receipt: CloakReceipt): Promise<void>;
  retry(id: string, reason: string, delayMs: number): Promise<void>;
  needsReview(id: string, reason: string): Promise<void>;
  refused(id: string, reason: string): Promise<void>;
};

const MAX_ATTEMPTS = 5;

const cloak = await createCloak({
  account: process.env.TREASURY_ACCOUNT_KEY!, // 64 hex characters
  storage: encryptedStorage(kv, process.env.CLOAK_STORAGE_SECRET!),
  rpc: process.env.SOLANA_RPC_URL,
  onWarning: (message) => console.warn("[cloak]", message),
});

// Cross-chain payouts a previous run left open are finished in the background.
cloak.on("finished", (item) => console.log("[cloak] finished from an earlier run:", item));

console.log("treasury", cloak.address, await cloak.balance());

async function payOne(job: Job): Promise<void> {
  try {
    const receipt = await cloak.send({
      to: job.to,
      ...(job.chain ? { chain: job.chain } : {}),
      token: "USDC",
      amount: job.amount,
      ref: `payout:${job.id}`, // the same job can never pay twice
      onProgress: (step) => console.log(`[${job.id}] ${step}`),
    });
    await jobs.paid(job.id, receipt); // receipt.repeated is true if an earlier run already paid it
  } catch (e) {
    if (!isCloakCallError(e)) {
      await jobs.needsReview(job.id, String(e));
      return;
    }
    const reason = `${e.code}: ${e.message}`;
    if (e.code === "ref.unsettled") {
      // An earlier attempt started and did not record its end. It may have paid: a human checks.
      await jobs.needsReview(job.id, reason);
    } else if (e.code === "payout.screening_refused" || e.code === "payout.refused") {
      await jobs.refused(job.id, reason); // final: the same recipient is refused again
    } else if (e.retryable && job.attempts + 1 < MAX_ATTEMPTS) {
      await jobs.retry(job.id, reason, 30_000 * 2 ** job.attempts);
    } else {
      await jobs.needsReview(job.id, reason);
    }
  }
}

// One payout at a time: the Cloak object serializes money-moving calls anyway.
for (;;) {
  const job = await jobs.next();
  if (!job) {
    await new Promise((resolve) => setTimeout(resolve, 5_000));
    continue;
  }
  await payOne(job);
}
```

## Why it is safe to restart

* **Idempotency.** Each job's `ref` is derived from its id. After a crash, the worker picks the job up
  again and `send` returns the stored receipt with `repeated: true` instead of paying again.
* **Unknown outcomes are not retried blindly.** `ref.unsettled` means a call started and never
  recorded its end, for example a process killed mid-payment. The worker parks the job for review.
* **State outlives the process.** `encryptedStorage` keeps receipts, refs and open cross-chain orders
  in your database, encrypted, so the next process sees them.

## Funding the treasury

Shield into the treasury from a wallet the organization controls, or have anyone `send` to
`cloak.address`. To shield from a server-held key, open the same account with both the key and the
wallet: `createCloak({ account, wallets: [fundingSigner], storage, rpc })`, then
`cloak.shield({ from: "solana", ... })`.

## Monitoring

| Signal | Action |
| - | - |
| Jobs in `needs_review` | Check the job's last receipt and the account's history before re-queuing |
| `payout.screening_refused` | Do not retry. Contact the payee |
| `balance.insufficient` | Top up the treasury; every following job fails the same way |
| Private balance below a threshold | Alert before payouts start failing |

## Related

* [Payroll](https://docs.cloak.ag/guides/payroll.md)
* [Transaction history](https://docs.cloak.ag/guides/transaction-history.md): reconcile payouts against the account's history.


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