> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fluton.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Deposits, withdrawals and transfers

> Build, prove and submit every kind of Fluton Pool transaction with the SDK, relay it, and read back what became of it.

Every transaction that spends or creates notes in Fluton Pool is one join-split proof, and in the pool client every one of them goes through the same function. `transactWith` assembles the join-split, delegates proving to a `ProveFn` the caller supplies, and submits, either from a wallet or through a relayer. `transact` is the node wrapper that wires in snarkjs and the circuit artifacts; the browser calls `transactWith` directly with its own prover.

```ts theme={null}
import { transact, depositPublic, withdraw, transfer } from "@fluton/sdk";

// transact(publicClient, walletClient, { ...params, wasm, zkey, large? })
```

`wasm` and `zkey` are the 2-input circuit's artifacts (paths or buffers). `large` adds the 16-input circuit (`transaction16.wasm`, `transaction16_final.zkey`); without it, spending more than two notes at once throws.

## How one transaction is assembled

`transactWith` always does the same things, in this order, and most of them can abort before anything is sent:

**1. Check the shape**

One asset for every note; at most 2 caller outputs (slot 2 is reserved); a withdrawal needs a recipient; only a deposit may name a referrer; deposits are never relayed; a relayer fee needs a relay client and must clear that relayer's minimum.

**2. Re-quote the relayer**

Gas prices may have risen since the fee was chosen, so the quote is read again before any proving time is spent.

**3. Screen the depositor**

A TOKEN deposit asks `screen()` first, before the tree, the proof or the approval, and checks who signed the screening against the pool's `screeningSigner`.

**4. Read the pool and the fee**

`getPoolConfig` gives the tree depth and the whole asset registry (every asset read the same way whatever the caller is about to do, so the reads reveal nothing about which asset the transaction uses), plus the current withdrawal-fee rate.

**5. Rebuild the trees**

`buildTreesFromChain` reproduces the pool's trees, which also resolves each input note's leaf position. The proof is made against the tree that holds the notes being spent, or the current tree when none is, so notes of different trees are spent in separate transactions. See [Keys, notes and scanning](https://docs.fluton.io/sdk/keys-and-scanning.md).

**6. Build the outputs and ExtData**

Slots 0 and 1 hold the caller's outputs, padded with zero-value dummies; slot 2 holds the relayer's fee note or another dummy. Each output gets a 168-byte ciphertext addressed to its owner.

**7. Prove, then simulate**

`buildTransactionInputs` produces the circuit inputs, `prove` the Groth16 proof, and the call is simulated before it is signed.

**8. Hand over the identity, then send**

`onPrepared` receives a `PreparedTx` while nothing has been sent; then the relayer or the wallet sends it, and the receipt is parsed into `effects`.

`ExtData` is the public side of the transaction, hashed into the proof. It is domain-bound (`chainId`, `pool`, `asset`, `format`, `depositId`) and canonical (fields a route does not use are zero), so a proof cannot be replayed against another chain or pool, and every client fills the same fields the same way:

| Field | Meaning |
| - | - |
| `recipient` | Withdrawals only; zero otherwise |
| `extAmount` | Note units entering (+) or leaving (−) the pool; 0 for a private transfer |
| `withdrawFee` | What the pool keeps; non-zero only on a withdrawal |
| `encryptedOutputs` | One 168-byte ciphertext per output note, in slot order |
| `chainId`, `pool` | The chain and pool this proof is for |
| `asset` | The asset crossing the boundary; exactly 0 when `extAmount` is 0 |
| `format` | 0 = confidential (eTOKEN), 1 = public (TOKEN) |
| `depositId` | Non-zero only for `finalizeDeposit` |
| `referrer` | Deposits only; zero otherwise |

A `TransactResult` carries the `hash` that ran, all three `outputs` in slot order with their leaf positions, the `feeNote` when relayed, the `withdrawFee` the pool kept, and `effects`: the output commitments with the leaf position of each, and the obligations and attempts, parsed from the receipt's own logs and never inferred.

## Deposit

Pulling value into the pool is the only thing that needs a **screening** of the depositor: a TOKEN deposit and `requestDeposit` carry one, and transfers, withdrawals and finalization need none. See [Deposit screening](https://docs.fluton.io/concepts/deposit-screening.md).

### TOKEN: one step

```ts theme={null}
const { note, hash } = await depositPublic(publicClient, wallet, {
  pool,
  asset: USDC,
  amount: 40n,
  keypair: aliceKeys,
  screen,                 // () => Promise<DepositScreening>
  referrer,               // optional, public like the deposit itself
  wasm,
  zkey,
});
```

`screen` is a `ScreenFn`: a function that returns a fresh screening of the depositor, normally by asking Fluton's backend API for one ([Deposit screening](https://docs.fluton.io/concepts/deposit-screening.md)). It is called before anything is spent, so a refused wallet raises `ScreeningRefusedError` having granted nothing, and `ScreeningUnavailableError` when screening cannot run at all — including when the service signs with a key the pool does not trust, which `assertPoolTrustsScreening` catches before any proving or approval. Just before sending, `freshScreening` fetches a new one if the first expires within `SCREENING_MIN_REMAINING_S` (60) seconds, and `simulateWithScreening` replaces it once more if the pool calls it stale during the simulation.

The pool pulls `amount × rate` of the asset's TOKEN, so the SDK approves that much first when the allowance is short. `transact` refuses a deposit without `screen`, and refuses `screen` on anything that is not a TOKEN deposit.

When the asset's TOKEN is wrapped ether, pass `wrapEther: true` and the deposit covers what the wallet lacks of the token from its ETH. The wrap is a transaction of its own, sent after the screening and the proof and right before the approval, so a deposit that stops earlier wraps nothing. `wrapEtherWith` is that step on its own: it wraps exactly the shortfall, sends nothing when the wallet already holds enough, and throws `InsufficientEtherError` before anything is sent when the wallet's ETH does not cover the wrap and its gas.

### eTOKEN: token-first

A successful receipt is never proof that a confidential transfer moved the amount it asked for, so an eTOKEN deposit is three steps and the pool credits nothing until it has verified CoFHE's signed decryption of what arrived ([TOKEN and eTOKEN](https://docs.fluton.io/concepts/token-formats.md)):

**1. requestDeposit**

`requestDepositWith(publicClient, wallet, { pool, asset, amount, screen })` makes the pool an operator of the wrapper, pulls the eTOKEN and records a depositor-owned receipt. It returns `{ depositId, ok, hash }`. No proof and no nullifiers are involved yet.

**2. verifyDeposit**

`verifyDepositWith(publicClient, wallet, client, { pool, depositId })` decrypts the receipt's `ok` handle (whether the pull moved the full amount) and submits that answer with CoFHE's signature, returning the new `DepositStatus`. It is permissionless (the relayer's keeper normally does it) and idempotent: a receipt that already left `Pending` is returned untouched.

**3. finalizeDeposit**

`finalizeDeposit(publicClient, wallet, { pool, depositId, keypair, referrer?, wasm, zkey })` proves the join-split that turns a `Verified` receipt into a note of the receipt's asset. Only the depositor can call it, and the proof binds the `depositId`.

A failed proof leaves the receipt `Verified`, so finalizing is safe to retry without the tokens being pulled again. The three steps, end to end:

```ts theme={null}
const { depositId } = await requestDepositWith(publicClient, wallet, { screen, pool, asset: USDC, amount: 12n });

const status = await verifyDepositWith(publicClient, wallet, cofheClient, { pool, depositId });
// DepositStatus.Verified when the pull moved the full amount, DepositStatus.Failed otherwise

const res = await finalizeDeposit(publicClient, wallet, { pool, depositId, keypair, wasm, zkey });
// readDeposit(publicClient, pool, depositId) reports the receipt's status at any point
```

`cancelDepositWith(publicClient, wallet, { pool, depositId })` abandons a non-terminal receipt instead and refunds what the pool actually received; it returns the `refundObligation` to follow. Finalizing and cancelling are mutually exclusive.

## Withdraw

```ts theme={null}
const res = await withdraw(publicClient, null, {
  pool,
  notes,                  // 1 to 16 notes, all of one asset
  amount: 4n,             // what the RECIPIENT receives
  recipient,
  format: "confidential", // or "public" for TOKEN
  relay,
  fee: 1n,                // the relayer's fee note
  wasm,
  zkey,
});
```

`amount` is what the recipient receives. The pool's fee is spent **on top** of it, and so is the relayer's fee when one submits; the surplus comes back as a change note of the same asset. `withdrawFeeFor(received, bps)` is the fee of the smallest withdrawal that pays exactly `received`, and that is the default: `withdraw` reads the current rate itself when `withdrawFee` is not given. `ExtData` then binds `extAmount = -(amount + withdrawFee)` and the fee, so no submitter can patch either. [Fees and referrals](https://docs.fluton.io/concepts/fees.md) explains the arithmetic.

Pass `withdrawFee` to bind the figure you showed the user. If the owner has changed the rate since, the call throws `WithdrawFeeChangedError` **before** proving and nothing is sent:

```ts theme={null}
const fee = withdrawFeeFor(1_000_000n, 35); // 3_513n: ceil(0.35% of 1_003_513)

try {
  await withdraw(publicClient, wallet, { pool, notes, amount, withdrawFee: fee, recipient, format: "confidential", wasm, zkey });
} catch (e) {
  if (e instanceof WithdrawFeeChangedError) {
    // e.bound is the fee you showed, e.current the fee at the rate now in force; show it and prove again
  }
}
```

A withdrawal whose fee would take the whole amount is refused outright. Spending more than two notes needs the 16-input circuit, so pass `large`.

## Transfer

A private transfer pays a shielded address and nothing crosses the pool boundary, so `extAmount` is 0, `ExtData.asset` is 0 and no token is named on-chain, relayed or not ([Private transfers](https://docs.fluton.io/concepts/private-transfers.md)):

```ts theme={null}
const to = await shieldedAddressFromSpendKey(bobSpendKey); // "pp-addr:…"
const res = await transfer(publicClient, alice, { pool, notes: [aliceWeth], amount: 10n, to, wasm, zkey });
// res.payment is Bob's note and res.change is Alice's; res.feeNote is undefined when nothing was relayed
```

`to` is parsed with `parseShieldedAddress`, the payment note is created for that public key and encrypted to that key, and the change note returns to the first input note's keypair. The result carries `payment` and `change`. The recipient finds the payment by scanning; they never touch the chain.

## Relayer

`createRelayClient(baseUrl, { chainId, pool })` reads `GET /status` and refuses a relayer serving another chain or pool before any proof is made. The client it returns is what `relay` expects, and it carries the relayer's EOA, its fee-note shielded address and its `minFees` floor per served asset.

| Call | Endpoint | What it gives |
| - | - | - |
| `quote()` | `GET /fees` | Every served asset at once, per job kind: `fee` asked and `min` accepted right now |
| `submit(payload)` | `POST /relay` | The hash it was sent under |
| `txStatus(nullifier)` | `GET /relay/:nullifier` | `pending`, `mined`, `failed` or `unknown` |

`relayFeeKind(extAmount)` picks the kind: a private transfer is `"transfer"`, anything crossing the boundary is `"withdraw"`, which costs the relayer more. Asking for a quote reveals nothing about the spend, because every asset is quoted in one answer. A fee between `fee` and `min` stays good while gas prices rise by less than the relayer's margin; below `min`, `transactWith` throws `RelayFeeChangedError` (with the `offered`, `fee` and `min` values) before proving.

The relayer is paid by output slot 2, never publicly, and the proof binds that commitment and its ciphertext, so the relayer can only submit or refuse. `readFeeNote` is the check it runs itself.

How the submission's answers map to errors matters, because re-sending the same notes another way is only safe when nothing was broadcast:

* **400** is the relayer's own refusal, before broadcasting: `RelayRefusedError`.
* **409** means those notes are already in flight under another payload. The same payload twice returns the first hash instead.
* Anything else (an unreachable relayer, a 5xx, an unreadable body) raises `RelayOutcomeUnknownError`, and `transactWith` attaches the transaction's input nullifiers to it. Ask `txStatus` and the chain before offering the user's own wallet.

A relayer may re-send a stuck transaction under a new hash, so `waitForRelayedReceipt` follows the replacement to its receipt, and the `hash` in the result is the one that actually ran. The service itself is described in [Running a relayer](https://docs.fluton.io/operators/relayer.md).

## Unwrap

An eTOKEN in a wallet goes back to its TOKEN on the wrapper itself, outside the pool, in two wallet transactions: `unshield` burns the amount into a claim, and `claimUnshielded` pays the TOKEN out once CoFHE has decrypted what was burned.

```ts theme={null}
const res = await unwrapWith(publicClient, wallet, cofheClient, {
  wrapper,
  amount: 5_000_000n,                              // eTOKEN units
  onSubmitted: (hash) => save({ hash }),           // the unshield was sent
  onUnshielded: ({ hash, claimId }) => save({ hash, claimId }),
});
// res.amount is what was unwrapped; res.hash is the claim's transaction
```

A short encrypted balance does not revert the unshield: it burns less, possibly nothing. The decrypted amount, never the unshield's receipt, says what was unwrapped, and `unwrapWith` throws `UnwrapShortfallError` after claiming whatever was burned. Once the unshield ran, only its claim pays the tokens back, so persist what the hooks hand you: `resumeUnwrapWith` finishes a lost run from the claim id or the unshield's hash, and never unshields again.

## Outcome

A hash is a poor handle: it exists only once the transaction is sent, the page can go away before it arrives, and a relayer's re-send changes it. What never changes is the proof. `TxHooks` hands you that identity instead:

```ts theme={null}
await transact(publicClient, wallet, {
  ...params,
  onPrepared: (tx) => save(tx),   // PreparedTx: pool, root, nullifiers, commitments, fromBlock
  onSubmitted: (hash) => note(hash),
});
```

`onPrepared` runs while nothing has been sent (throwing in it aborts the send), so whatever it persists is enough to find the transaction later. `onSubmitted` runs as soon as it is on its way, and an exception there is ignored.

`checkTransaction(publicClient, tx, { hash, scan })` then answers what became of it, using the hash only as a shortcut:

| `status` | Meaning |
| - | - |
| `landed` | It ran in `hash`; the receipt and parsed `effects` come with it. Final |
| `reverted` | The hash it was sent under reverted and its notes are unspent. Final |
| `superseded` | Another transaction spent its notes first, so it can never run. Final |
| `pending` | It has not run and still can: in the mempool, dropped, or never sent. The pool keeps every root, so it stays valid until it runs or its notes are spent |

The answer is read at one block so the reads agree with each other, and `receiptCarries` is the test: a receipt ran this transaction only if it succeeded and the pool logged every one of its nullifiers and commitments. While the chain cannot answer, `checkTransaction` throws rather than guess. Ask again later. `checkDeposit` does the same for an eTOKEN receipt, returning its `DepositStatus` and, once `Finalized`, the transaction that finalized it (whoever sent it).

Start from [SDK overview](https://docs.fluton.io/sdk/overview.md) for the module map, the [Pool client reference](https://docs.fluton.io/sdk/reference.md) for every export, or [Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md) for what the circuit proves.


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