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

# Cross-chain

> Shield from Base, Polygon and Sui, send to Base, Polygon, Sui and Tron, and move BRS to and from Base

Money can come into the private balance from another network, and leave it for one. With
[`createCloak`](https://docs.cloak.ag/sdk/create-cloak) each direction is one call; the free functions underneath are at
the [end of this page](#lower-level-bridging-in-with-the-free-functions). The user-facing behaviour
is [Bridging in](https://docs.cloak.ag/guide/bridge.md), and the guarantees each route does and does not give are in
[Bridge routes](https://docs.cloak.ag/guide/bridge-routes.md). Everything on this page is exported by `@cloak.dev/sdk`
0.2.20.

| Network | Shield from it | Arrives in the private balance as | Send to it | Arrives there as |
| - | - | - | - | - |
| Base | USDC or ETH | USDC | USDC | USDC |
| Polygon | USDC | USDC | USDC | USDC |
| Sui | USDC | USDC | USDC | USDC |
| Tron | not offered | | USDC | USDT (TRC-20) |
| Base, through LayerZero | BRS | BRS | BRS | BRS |

`NETWORKS` is the same list in code, with each network's tokens and minimums (`depositMinimumHint`,
`payoutMinimum`, `payoutToken`). Read it rather than hard-coding a network.

## Shielding from another network

```ts theme={null}
// From the Base wallet passed to createCloak: it signs the transfer on Base.
const q = await cloak.quote({ from: "base", token: "USDC", amount: "6" });
console.log(`at least ${q.arrives.atLeast} USDC arrives`);
const receipt = await cloak.shield({ from: "base", token: "USDC", amount: "6" });
console.log(receipt.sent, receipt.txs); // "6 USDC", { base: "0x…", solana: "…" }
```

The money goes to a one-time receiving address on Solana derived from the account, and the SDK
shields it when it arrives. Base, Polygon and Sui go through NEAR Intents (1Click), which signs the
deposit address and the recipient (the SDK verifies that signature before anything is sent) and
refunds an order it cannot fill to the wallet that sent it. The wallet's funds and gas are checked
before any address is reserved. Getting the deposit into the pool is a Solana network cost covered
out of the bridged amount; arriving carries no Cloak fee. The minimum is about 3 USDC, and the live
quote's minimum is the one that counts. While the money is between the two chains the route holds
it: no route here is trustless in transit.

If the shield stops after the money left the origin wallet, the money waits at the receiving address
and the SDK shields it on the next start, or when you call `cloak.resume()`.

## Sending to another network

```ts theme={null}
await cloak.send({ to: "0x07f0…", chain: "base", token: "USDC", amount: "5" }); // or "polygon"
await cloak.send({ to: "<a Sui address>", token: "USDC", amount: "5" }); // names its own network
await cloak.send({ to: "<a Tron address>", token: "USDC", amount: "5" }); // USDT arrives
```

The SDK withdraws the amount and the pool's fee from the private balance and hands it to the route,
which delivers it on the other network. `quote` shows first what arrives at least; its `fee` covers
everything in between, which is the program's withdrawal fee and what the route deducts to deliver.
A send resolves once it is delivered; pass `wait: false` to resolve as soon as it is sent, and call
`receipt.track()` later.

* **Screening.** Every recipient is screened against sanctions lists before the send is quoted. A
  refused one throws `payout.screening_refused`: nothing moved, and the same address is refused
  again, so do not retry it.
* **Minimums.** `payoutMinimum(network)`: 3.5 USDC to Sui, 5 USDC to Tron. Below it the call
  throws `payout.refused` before anything is asked.
* **Routes.** A send goes through NEAR Intents (1Click), which signs the quote, the recipient and
  the amount that arrives included, and the SDK checks that signature. A send to Sui that 1Click
  cannot quote falls back to Jupiter Universal Deposit, which signs nothing and has no refund path:
  that quote carries no signed floor.

### Tron

A Tron address is recognised by decoding it (base58check, version byte `0x41`), not by its shape,
which a Solana address can share; `isTronAddress` and `classifyRecipient` give the same answer, and
the hex form is refused rather than converted. The money arrives as native TRC-20 USDT, because the
route lists no USDC on Tron (`payoutToken("tron")`), and the receipt's `token` says `USDT`. A TRC-20
delivery costs the route about 1.55 USDC, which is why the minimum is 5 USDC. Tron's USDT and USDC
contracts and its burn address are refused with `payout.refused` before anything is asked: money
sent to them could never move again. There is no shielding from Tron.

### BRS to and from Base

BRS has its own pool on Solana and also lives on Base. It moves between the two 1:1 through
LayerZero, on BRS's own token contracts:

```ts theme={null}
await cloak.shield({ from: "base", token: "BRS", amount: "100" });
await cloak.send({ to: "0x07f0…", chain: "base", token: "BRS", amount: "100" });
```

* **From Base**, the Base wallet pays LayerZero's fee in ETH, and the transfer also carries the SOL
  the receiving address needs to shield, so the user needs no SOL.
* **To Base**, LayerZero's fee comes from the private SOL balance, so the account needs some private
  SOL as well as the BRS.
* `quote` and the receipt report that fee as `networkFee` (`{ token: "ETH", amount }` or
  `{ token: "SOL", amount }`).
* Both directions are refused with `route.unavailable` while the BRS pool is not available, so no
  BRS is left waiting at a receiving address. Like every route here, the transfer is not trustless
  in transit: it depends on LayerZero's messaging and on BRS's contracts on both chains.

## Lower level: bridging in with the free functions

The shape is always the same: derive a one-time receiving address from the user's own keys, get a
quote, let the user send on the origin chain, then shield what arrives. Nothing here is stored for
you. Every address is re-derivable from the wallet's `ownerUtxoKeypair`, which is why a closed tab loses
nothing.

> [!WARNING]
>
> **Shielding runs on the client.** Funds that arrive while nothing is running wait at the receiving
> address until a later call picks them up. That is what `listBridgeDeposits` is for, and it is why an
> integration needs a resume path rather than a single happy-path call.

### Deriving the receiving address

```ts theme={null}
import {
  deriveBridgeReceiver,
  deriveSpendKey,
  deriveUtxoKeypairFromSpendKey,
  generateMasterSeed,
  MAX_RECEIVER_INDEX,
} from "@cloak.dev/sdk";

// `seed`: 32 bytes generated once (generateMasterSeed()) and stored like a private key.
const seed = generateMasterSeed().seed;
const { sk_spend } = deriveSpendKey(seed);
const ownerUtxoKeypair = await deriveUtxoKeypairFromSpendKey(sk_spend);

// A KeyPairSigner for receiving address number 0. MAX_RECEIVER_INDEX is 10000.
const receiver = await deriveBridgeReceiver(ownerUtxoKeypair, 0);
console.log(receiver.address, MAX_RECEIVER_INDEX);
```

The receiver is derived from the wallet's spend-level key material (`ownerUtxoKeypair`), not from the
viewing key `nk`: the receiver is a full signer that holds funds in transit, and `nk` may be shared.
`index` is a small sequential counter, not a timestamp. Discovery derives `0…N` and reads each
one on chain, so a sparse index space makes the user's own deposits undiscoverable. `deriveBridgeReceiver`
throws on a non-integer, a negative value, or anything above `MAX_RECEIVER_INDEX`.

`BRIDGE_ESCROW_LABEL` and `deriveLegacyBridgeReceiver(nk, index)` belong to the first bridge release,
which derived receivers from `nk`. They exist so discovery can find and finish old deposits; never
route a new deposit to a legacy receiver. The current label is `BRIDGE_ESCROW_LABEL_V2`.

### Quoting, and refusing a bad one

```ts theme={null}
import {
  assessBridgeQuote,
  ECONOMIC_MINIMUM, // below this, fixed costs dominate the amount
  MIN_DEPOSIT_SPL_BASE_UNITS, // 1_000_000n: the program's USDC/USDT deposit minimum
  renderAssessment,
  WITHDRAW_FEE_BPS, // 30n (0.3%)
  WITHDRAW_FIXED_FEE, // 450_000n base units
  withdrawFeeFor,
  type BridgeQuoteInput,
} from "@cloak.dev/sdk";

const quote: BridgeQuoteInput = {
  sent: 100_000_000n, // 100 USDC sent on the origin chain, in base units
  arrivesMin: 99_000_000n, // the route's guaranteed floor: assess against this
  arrivesTarget: 99_500_000n, // the route's target, for display only
  paymasterFee: 150_000n, // what funding the receiver costs, same units
  refunds: true, // the route refunds an order it cannot fill; anything else applies a higher minimum
};

const assessment = assessBridgeQuote(quote);
if (!assessment.viable) throw new Error(assessment.reasons.join("; "));
console.log(renderAssessment(assessment));
console.log(
  assessment.shieldedMin >= MIN_DEPOSIT_SPL_BASE_UNITS,
  assessment.shieldedMin >= ECONOMIC_MINIMUM,
  withdrawFeeFor(assessment.shieldedMin),
  WITHDRAW_FIXED_FEE,
  WITHDRAW_FEE_BPS,
);
```

`assessBridgeQuote` returns what the user ends up with, and whether the quote is worth
taking at all: `viable` is false when what would arrive cannot clear the program's deposit minimum
once costs are covered. It throws rather than compute on a nonsensical quote (a negative amount, or
a route claiming to deliver more than it was given). `renderAssessment` formats the same numbers for
a CLI.

> [!NOTE]
>
> `WITHDRAW_FIXED_FEE` and `WITHDRAW_FEE_BPS` are compile-time fallbacks for quote arithmetic, used
> when live values are not supplied. The authority is the program's per-mint `pool_config` PDA, and the
> fee is collected on-chain by the program (see [Fee model](https://docs.cloak.ag/concepts/fees.md)). Never present these
> constants as the fee the user will be charged.

### Verifying the deposit address yourself

```ts theme={null}
import { canonicalPayloadString, ONECLICK_PUBKEY_B58, verifyQuoteSignature } from "@cloak.dev/sdk";

// `response` is the quote response object exactly as the route returned it.
declare const response: unknown;

const { valid, reason } = verifyQuoteSignature(response);
if (!valid) console.warn("This route cannot be verified:", reason);
console.log(canonicalPayloadString(response), ONECLICK_PUBKEY_B58);
```

One route signs its quote, including the deposit address; the other signs nothing. Running
`verifyQuoteSignature` client-side is what lets a caller detect a substituted deposit address
independently, rather than trusting whatever forwarded the quote. A route that returns no signature
comes back `{ valid: false }` with a reason. Treat that as "this route cannot be verified", not as
an error to swallow.

### Finding what already arrived

```ts theme={null}
import {
  CLOAK_PROGRAM_ID,
  createCloakRpc,
  listBridgeDeposits,
  address,
  type BridgeDeposit,
  type DiscoverOptions,
  type UtxoKeypair,
} from "@cloak.dev/sdk";

declare const ownerUtxoKeypair: UtxoKeypair; // derived as in the first section

const rpc = createCloakRpc("https://your-keyed-mainnet-rpc.example");
const opts: DiscoverOptions = {
  programId: CLOAK_PROGRAM_ID,
  mint: address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), // USDC
  scanDepth: 20,
  stopAfterUnused: 5,
};

const deposits: BridgeDeposit[] = await listBridgeDeposits(rpc, ownerUtxoKeypair, opts);
for (const d of deposits) console.log(d.index, d.state, d.tokenBalance, d.legacyExposed);
```

`BridgeDeposit.state` is a `BridgeDepositState`: `"unused"`, `"awaiting"`, `"arrived"`, `"complete"`,
`"needs-cleanup"` or `"unknown"`. `"unknown"` means an RPC read failed; it is not evidence that nothing
is there, so retry instead of reporting an empty address.

Discovery derives receiving addresses from `ownerUtxoKeypair` and reads each on chain, stopping after
`stopAfterUnused` consecutive empty ones or at `scanDepth` (default 20, capped at
`MAX_RECEIVER_INDEX + 1`). It also scans the legacy `nk`-derived receivers unless you set
`includeLegacy: false`, and flags those entries `legacyExposed`. This is the resume path: the user
reopens the app with the same wallet and anything unshielded is found again from their keys alone.

### Completing and cleaning up

```ts theme={null}
import {
  CLOAK_PRODUCTION_RELAY_URL,
  CLOAK_PROGRAM_ID,
  cleanupReceivingAddress,
  createCloakRpc,
  depositFromDerivedKey,
  fundReceiverViaPaymaster,
  address,
  type DepositOutcome,
  type KeyPairSigner,
  type PaymasterTopUpResult,
} from "@cloak.dev/sdk";

declare const receiver: KeyPairSigner; // deriveBridgeReceiver(ownerUtxoKeypair, index)
declare const funder: KeyPairSigner; // pays the receiver's minimal funding
declare const noteSpendKey: Uint8Array; // the wallet's sk_spend
declare const arrived: bigint; // the receiver's token balance, from listBridgeDeposits

const rpc = createCloakRpc("https://your-keyed-mainnet-rpc.example");
const usdc = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");

// Fund the receiver through the paymaster; the caller submits the returned transaction.
const topUp: PaymasterTopUpResult = await fundReceiverViaPaymaster(
  CLOAK_PRODUCTION_RELAY_URL,
  receiver,
  1_000_000n, // lamports to grant the receiver
);
console.log(topUp.feeMint, topUp.feeTokenAmount);

// Shield what arrived, with the receiver as the only signer of the deposit.
const outcome: DepositOutcome = await depositFromDerivedKey(
  rpc,
  receiver,
  funder,
  arrived,
  console.log,
  undefined, // grantOverride: leave unset
  { relayUrl: CLOAK_PRODUCTION_RELAY_URL, programId: CLOAK_PROGRAM_ID, mint: usdc, noteSpendKey },
);
console.log(outcome.signature);

// Close the empty token account. Leave dustDestination unset unless the user knows the cost:
// any destination they control publishes receiver -> them.
const cleanup = await cleanupReceivingAddress(rpc, receiver, undefined, usdc);
console.log(cleanup.closed, cleanup.note);
```

A receiving address arrives holding no SOL, so it cannot pay for its own shield. The paymaster
helpers cover that, and `cleanupReceivingAddress` closes the token account afterwards. It never sweeps
leftover dust unless you pass `dustDestination`. `depositFromDerivedKey` throws `DepositError` when
the funding step ran before the failure; its `fundedAccounts` field says what already landed.

Also exported: `validatePaymasterTopUpTransaction(tx, expectation)`, which refuses a top-up
transaction that is not exactly what was asked for before the receiver signs it, plus
`deriveFundingTargets`, `readRent`, `FEE_BUDGET`, `CLEANUP_FEE_BUDGET`, `MAINNET_RENT_0` and
`MAINNET_RENT_1` for budgeting the receiver's SOL.

### Retrying without double-spending

```ts theme={null}
import {
  classifyPostFailure,
  DoNotRetry,
  mayRetry,
  withShieldRetries,
  type RetryHooks,
} from "@cloak.dev/sdk";

declare function readReceiverBalance(): Promise<bigint | null>; // your own read of the token account
declare function shield(): Promise<string>; // your own call, for example depositFromDerivedKey

const attempted = 100_000_000n; // what the receiver held when the attempt started
const hooks: RetryHooks = {
  attempts: 3,
  onRetry: (attempt, delayMs, lastError) => console.log(attempt, delayMs, lastError),
};

const signature = await withShieldRetries(async () => {
  try {
    return await shield();
  } catch (error) {
    const verdict = classifyPostFailure(attempted, await readReceiverBalance());
    const message = error instanceof Error ? error.message : String(error);
    if (!mayRetry(verdict, message)) throw new DoNotRetry(message);
    throw error;
  }
}, hooks);
console.log(signature);
```

The distinction that matters: a request that failed before submission can be retried freely, and
one that failed after it may already have landed. `classifyPostFailure(attempted, after)` compares the
receiver's balance before and after the attempt and returns `"landed"`, `"did-not-land"` or
`"unknown"`; `mayRetry(verdict, message)` turns that into a yes or no, and anything the evidence
cannot explain resolves to no. `withShieldRetries` runs the loop and stops when the attempt throws
`DoNotRetry`. `isTerminalFailure(message)`, `TERMINAL_FAILURE` and `retryDelayMs(attempt)` are the
smaller pieces it is built from.

## Lower level: sending to another network with the free functions

`createCloak`'s sends are built on these, which stay exported. `checkPayoutRecipient` is the one
rule for who can be paid, and it answers before anything is asked:

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

const check = checkPayoutRecipient({ address: "<a Tron address>", token: "USDC", amountBaseUnits: 5_000_000n });
if (!check.ok) throw new Error(`cannot pay: ${check.reason}`); // "not_a_wallet", "below_minimum", …
console.log(check.network, payoutMinimum(check.network)); // "tron" 5000000n
```

`previewPayout` is the dry quote: it reserves nothing. `payOutFromPrivateBalance(ctx, { id,
network, recipient, netBaseUnits, notes, withdraw })` makes a whole payout: it runs the check,
plans the notes (`planPayoutWithdrawals`), reserves the payout and saves its record before anything
moves, and makes each withdrawal (`payoutWithdrawer`); when an earlier payout to the same recipient
already has money moving, it finishes that one instead of paying again. Follow it with `watchPayout`
for delivery. A refusal by screening is a `PayoutServiceError` that
`isPayoutScreeningRefusal(e)` recognizes; it is final.

## Related

* [createCloak](https://docs.cloak.ag/sdk/create-cloak.md): every call, receipts and error codes
* [Bridging in](https://docs.cloak.ag/guide/bridge.md): the user-facing flow, costs and recovery
* [Bridge routes](https://docs.cloak.ag/guide/bridge-routes.md): what each route does and does not guarantee
* [Fee model](https://docs.cloak.ag/concepts/fees.md): where the fee comes from


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