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

# Pool client reference

> Every export of the Fluton Pool client SDK, grouped by area: keys and addresses, scanning, pool reads, transactions, eTOKEN deposits and obligations, the relayer and API clients, screening, referrals and outcomes.

> [!NOTE]
>
> The Fluton SDK is not yet published to npm. It will ship as `@fluton/sdk`.
> This page lists the pool client as it exists today; the planned intent client is described on
> [Intent client](https://docs.fluton.io/sdk/intent-client.md).

The Fluton Pool client has two entry points. `@fluton/sdk` is the full surface, including the
snarkjs prover and its node wrappers (`proof`, `transact`) and the node CoFHE client (`cofheNode`).
`@fluton/sdk/browser` leaves those three out and exports `inputs`, the circuit-input assembly,
directly; the node entry reaches the same names through `proof`. Everything else is in both, and
the tables say when an export is not.

Throughout, amounts are `bigint` in note units, asset ids are 1-based numbers, `publicClient` and
`walletClient` are viem clients, and `pool` is the pool's address.

## Keys and addresses

One secret, the spend key, derives everything else: the Poseidon keypair notes are created for,
the x25519 keypair ciphertexts are encrypted to, the shielded address a payer needs and the
read-only view key. [Keys and view keys](https://docs.fluton.io/concepts/keys-and-view-keys.md) explains the split;
[Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md) explains the note itself.

| Export | Signature | What it does |
| - | - | - |
| `deriveSpendKey` | `deriveSpendKey(walletClient, { chainId, pool }) → Promise<bigint>` | One wallet prompt: signs the domain message and hashes the signature into a spend key. |
| `spendKeyMessage` | `spendKeyMessage({ chainId, pool }) → string` | The exact text the wallet signs, with the pool address lower-cased. |
| `spendKeyFromSignature` | `spendKeyFromSignature(signature) → bigint` | The pure step: keccak of `fluton-spend-key` and the signature, 31 bytes of it, always inside the field. |
| `keypairFromPrivate` | `keypairFromPrivate(privateKey) → Promise<Keypair>` | Private key, nullifier key and Poseidon public key. |
| `createKeypair` | `createKeypair() → Promise<Keypair>` | A random spending keypair. |
| `nullifierKeyFromPrivate` | `nullifierKeyFromPrivate(privateKey) → Promise<bigint>` | `Poseidon(privateKey, NULLIFIER_KEY_DOMAIN)`. |
| `watchOnlyKeypair` | `watchOnlyKeypair(publicKey) → Keypair` | Public key only, for notes owned by someone else. |
| `viewOnlyKeypair` | `viewOnlyKeypair(publicKey, nullifierKey) → Keypair` | Recognises spent notes, cannot spend. |
| `shieldedAddressFromSpendKey` | `shieldedAddressFromSpendKey(spendKey) → Promise<string>` | The `pp-addr:` address to hand out. |
| `serializeShieldedAddress` | `serializeShieldedAddress(address) → string` | `pp-addr:<spendPubHex>:<encPubHex>`. |
| `parseShieldedAddress` | `parseShieldedAddress(text) → ShieldedAddress` | Decodes an address; refuses anything but three parts, a field public key and a 32-byte encryption key. |
| `encryptionKeypairFromSpendKey` | `encryptionKeypairFromSpendKey(spendKey) → EncryptionKeypair` | The x25519 keypair derived from the spend key. |
| `encryptionKeypairFromSecret` | `encryptionKeypairFromSecret(secret) → EncryptionKeypair` | The x25519 keypair of a raw 32-byte secret, such as a view key's. |
| `encryptNote` | `encryptNote(recipientEncPub, amount, blinding, asset) → Uint8Array` | The 168-byte ciphertext of a note opening. |
| `tryDecryptNote` | `tryDecryptNote(keys, blob) → opening or null` | Authenticated decryption; null for another owner's blob, a malformed one or a non-canonical opening. |
| `viewKeyFromSpendKey` | `viewKeyFromSpendKey(spendKey) → Promise<ViewKey>` | Public key, nullifier key and encryption secret, each one-way from the spend key. |
| `serializeViewKey` | `serializeViewKey(view) → string` | `pp-view:<spendPubHex>:<nullifierKeyHex>:<encSecretHex>`. |
| `parseViewKey` | `parseViewKey(text) → ViewKey` | Decodes and validates a view key. |
| `keypairFromViewKey` | `keypairFromViewKey(view) → Keypair` | The view-only keypair discovered notes are attributed to. |
| `encryptionKeypairFromViewKey` | `encryptionKeypairFromViewKey(view) → EncryptionKeypair` | A view key's decryption keys. |
| `shieldedAddressFromViewKey` | `shieldedAddressFromViewKey(view) → string` | The address a view key watches, identical to the spend key's. |
| `createUtxo` | `createUtxo(amount, asset, keypair?) → Promise<Utxo>` | A fresh note with a random blinding. Amount 0 is a valid dummy. |
| `utxoCommitment` | `utxoCommitment(utxo) → Promise<bigint>` | `Poseidon(amount, publicKey, blinding, asset)`, the leaf. |
| `utxoNullifier` | `utxoNullifier(utxo) → Promise<bigint>` | `Poseidon(commitment, index in its tree, nullifierKey)`. Needs a nullifier key. |
| `isCanonicalOpening` | `isCanonicalOpening(amount, blinding, asset) → boolean` | Amount below 2^248, blinding inside the field, asset a uint32. |
| `fieldEncode` | `fieldEncode(x) → bigint` | A signed amount as the circuit's `publicAmount`. |
| `serializeUtxo` | `serializeUtxo(utxo) → string` | A `pp-note:` bearer string. The leaf index is not stored; scanning recovers it. |
| `parseUtxo` | `parseUtxo(text) → Promise<Utxo>` | Decodes a `pp-note:` string and checks its ranges. |
| `poseidon` | `poseidon(inputs) → Promise<bigint>` | Poseidon of 1 to 4 field elements, identical to the circuit and the on-chain hasher. |
| `hashLeftRight` | `hashLeftRight(left, right) → Promise<bigint>` | The tree's node hash. |
| `randomFieldElement` | `randomFieldElement() → bigint` | A random field element. |
| `toBytes32` | `toBytes32(x) → Hex` | A field element as 32-byte hex. |

Types: `SpendKeyDomain` (`chainId`, `pool`), `Keypair` (`publicKey`, plus `privateKey` and
`nullifierKey` when present), `Utxo` (`amount`, `asset`, `blinding`, `keypair`, `index`, its leaf
position, once landed, `encryptTo` for watch-only outputs), `ShieldedAddress`, `EncryptionKeypair` and `ViewKey`.

```ts theme={null}
import { deriveSpendKey, shieldedAddressFromSpendKey, serializeViewKey, viewKeyFromSpendKey } from "@fluton/sdk";

const spendKey = await deriveSpendKey(walletClient, { chainId: 42161, pool });
const address = await shieldedAddressFromSpendKey(spendKey); // pp-addr:…
const viewKey = serializeViewKey(await viewKeyFromSpendKey(spendKey)); // pp-view:…
```

## Scanning and the tree

Scanning rebuilds the pool's commitment trees and discovers the notes a key owns by trial
decryption. An indexer is an optional accelerator that is verified against the pool before a single
leaf is trusted; [Keys, notes and scanning](https://docs.fluton.io/sdk/keys-and-scanning.md) walks through the checks.

| Export | Signature | What it does |
| - | - | - |
| `scanShieldedNotes` | `scanShieldedNotes(publicClient, pool, key, scan?) → Promise<{ notes, spendable, balances }>` | Trial-decrypts every commitment ciphertext with a spend key or a `ViewKey`. Returns every owned note with its spent flag, the unspent ones, and unspent value per asset. |
| `balancesOf` | `balancesOf(notes) → AssetBalances` | Sums note value per asset id. Amounts of different assets are never added together. |
| `scanCommitments` | `scanCommitments(publicClient, pool, scan?) → Promise<CommitmentRecord[]>` | Every leaf in insertion order, from the indexer when it verifies, otherwise from RPC. |
| `buildTreesFromChain` | `buildTreesFromChain(publicClient, pool, levels, scan?) → Promise<{ trees, records }>` | Rebuilds every tree of the pool exactly as the pool holds them, as a `PoolTrees`. |
| `findUtxoIndex` | `findUtxoIndex(records, utxo) → Promise<number>` | The leaf position of a note's commitment. Throws if the note has not landed. |
| `indexerHealth` | `indexerHealth(source) → Promise<IndexerHealth>` | Refuses an indexer that serves another chain or pool, reports unhealthy, or has no `indexedBlock`. |
| `fetchIndexedCommitments` | `fetchIndexedCommitments(source, levels) → Promise<{ indexedBlock, records }>` | Every commitment through the indexer's block, checked to follow one another in position from leaf 0 and to lie inside the field. |
| `fetchIndexedNullifiers` | `fetchIndexedNullifiers(source, at) → Promise<{ indexedBlock, nullifiers }>` | Every spent nullifier through block `at`. |
| `fetchIndexedDeposits` | `fetchIndexedDeposits(source) → Promise<{ indexedBlock, deposits }>` | Every deposit receipt id with its depositor. |
| `readPinned` | `readPinned(read) → Promise<T>` | Retries a pinned-block read up to twice, for a load-balanced RPC that has not seen the block yet. |
| `reportIndexerFallback` | `reportIndexerFallback(source, what, error)` | Reports an abandoned indexer read through the source's `onFallback`, or `console.warn`. Never throws. |
| `MerkleTree.build` | `MerkleTree.build(levels, leaves, number?) → Promise<MerkleTree>` | One fixed-depth tree from its ordered leaves; `number` (default 0) says which of the pool's trees it is. The instance has `root`, `leafCount`, `levels`, `number` and `proof(index) → MerkleProof`, where `index` is the leaf's index in that tree. |
| `PoolTrees.build` | `PoolTrees.build(levels, leaves) → Promise<PoolTrees>` | Every tree of the pool from all its leaves in insertion order. The instance has `trees` (by number, never empty), `current` (the tree the pool appends to now) and `treeAt(position) → MerkleTree`. |
| `treeCapacity` | `treeCapacity(levels) → number` | The leaves one tree takes before the pool starts the next: whole transactions only. |
| `treeOf` | `treeOf(position, levels) → number` | The number of the tree a leaf position is in. |
| `indexInTree` | `indexInTree(position, levels) → number` | A position's index in its tree: what its Merkle path and its nullifier use. |
| `positionOf` | `positionOf(ordinal, levels) → number` | The position of the `ordinal`-th leaf the pool inserts, counted from 0 across trees. |
| `ordinalOf` | `ordinalOf(position, levels) → number` | How many leaves the pool inserts before `position`. Throws for a position that is never used. |

A leaf's **position** is its tree's number times 2^`levels` plus its index in that tree. It is what
the pool logs for every commitment and what a note's `index` holds, and it identifies a note on its
own: the pool starts another tree when a transaction's three leaves no longer fit the current one
([Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md#the-merkle-tree)).

`ScanOptions` is the window: `fromBlock` (default 0), `chunkSize` (unset means one call),
`toBlock` (default the latest block, read fresh) and `indexer`. `IndexerSource` is `url`,
`chainId`, `pool`, and optionally `timeoutMs` (default 8000), `pageSize` (default 5000) and
`onFallback`. A scan returns `DiscoveredNote` values (`utxo`, `spent`) and `AssetBalances`, asset
id to `bigint`; an `IndexedCommitment` is `commitment`, `index` (the position) and
`encryptedOutput`. A failed indexer check raises `IndexerError` internally and the scan continues
from RPC.

```ts theme={null}
import { scanShieldedNotes } from "@fluton/sdk/browser";

const scan = { fromBlock: deployBlock, chunkSize: logChunk, indexer: { url: indexerUrl, chainId: 42161, pool } };
const { spendable, balances } = await scanShieldedNotes(publicClient, pool, spendKey, scan);
```

## Pool reads

The read side of the pool: its configuration and asset registry, the fee arithmetic, `ExtData`,
and the receipt, obligation and attempt records. [TOKEN and eTOKEN](https://docs.fluton.io/concepts/token-formats.md)
explains the records; [Fees and referrals](https://docs.fluton.io/concepts/fees.md) explains the arithmetic.

| Export | Signature | What it does |
| - | - | - |
| `getPoolConfig` | `getPoolConfig(publicClient, pool) → Promise<PoolConfig>` | Tree depth, every listed asset, the fee rate, the referral share and the bonus signer. Every asset is read the same way, so the reads reveal nothing about the caller's intent. |
| `assetOf` | `assetOf(config, id) → PoolAsset` | The listed asset, or a clear error. |
| `readWithdrawFeeBps` | `readWithdrawFeeBps(publicClient, pool) → Promise<number>` | The current withdrawal fee in basis points. |
| `readReferralShareBps` | `readReferralShareBps(publicClient, pool) → Promise<number>` | The base referral share, in basis points of the fee. |
| `readBonusSigner` | `readBonusSigner(publicClient, pool) → Promise<Address>` | The address whose attestations set bonuses. The zero address means none can be set. |
| `readReferralBonus` | `readReferralBonus(publicClient, pool, referrer) → Promise<ReferralBonus>` | A referrer's stored bonus, all zeros when none was set. |
| `readReferralShareOf` | `readReferralShareOf(publicClient, pool, referrer) → Promise<number>` | The share a deposit landing now would credit this referrer, base plus bonus. |
| `readReferralCredit` | `readReferralCredit(publicClient, pool, referrer, asset) → Promise<bigint>` | Credited and not yet claimed, in note units. |
| `noteUnitsToUnderlying` | `noteUnitsToUnderlying(units, rate) → bigint` | Note units to TOKEN base units. |
| `underlyingToNoteUnits` | `underlyingToNoteUnits(amount, rate) → bigint` | TOKEN base units to note units. Throws unless exact; the pool never rounds. |
| `withdrawFeeOf` | `withdrawFeeOf(amount, bps) → bigint` | The fee a withdrawal of `amount` pays, rounded up, exactly as the pool computes it. |
| `withdrawReceivedOf` | `withdrawReceivedOf(amount, bps) → bigint` | What the recipient of a withdrawal of `amount` receives. |
| `withdrawFeeFor` | `withdrawFeeFor(received, bps) → bigint` | The fee to spend on top so the recipient receives exactly `received`. |
| `referralRewardOf` | `referralRewardOf(amount, feeBps, shareBps) → bigint` | The referral credit a deposit earns, rounded down, never more than the fee. |
| `referralShareOf` | `referralShareOf(baseBps, bonus, nowSeconds) → number` | Base share plus the bonus in force at `nowSeconds`, capped at the whole fee. |
| `hashExtData` | `hashExtData(ext) → bigint` | `keccak256(abi.encode(ExtData))` reduced into the field: the proof's `extDataHash`. |
| `readDeposit` | `readDeposit(publicClient, pool, id) → Promise<DepositState>` | One receipt with its current status. |
| `readObligation` | `readObligation(publicClient, pool, id) → Promise<ObligationState>` | One obligation. |
| `readAttempt` | `readAttempt(publicClient, pool, id) → Promise<AttemptState>` | One attempt, with its wrapper claim id when it is a burn. |
| `readObligationWithAttempts` | `readObligationWithAttempts(publicClient, pool, id) → Promise<ObligationWithAttempts>` | An obligation and every attempt, read directly. Cheap to poll. |
| `attemptIdOf` | `attemptIdOf(obligationId, attemptNumber) → Hex` | `keccak256(abi.encode(obligationId, attemptNumber))`, as the pool derives it. |
| `listDeposits` | `listDeposits(publicClient, pool, depositor, scan?) → Promise<DepositState[]>` | Every receipt of a depositor with its current status. Ids may come from the indexer; status always comes from the pool. |
| `listObligations` | `listObligations(publicClient, pool, { to?, ids? }, scan?) → Promise<ObligationWithAttempts[]>` | Obligations from events plus state, optionally only those paying `to`. |
| `readClaim` | `readClaim(publicClient, wrapper, claimId) → Promise<WrapperClaim>` | A wrapper claim: recipient, encrypted handle, decrypted amount and whether it was claimed. |
| `parseTxEffects` | `parseTxEffects(receipt, pool) → TxEffects` | Commitments with leaf positions, obligations, attempts and a deposit request, from the receipt's own logs and never inferred. |
| `assignIndicesFromReceipt` | `assignIndicesFromReceipt(effects, outputs) → Promise<void>` | Sets each output note's leaf position from the receipt. Throws if an output did not land. |

Types: `PoolConfig`, `PoolAsset` (`id`, `wrapper`, `underlying`, `rate`), `PoolFormat`
(`"confidential"` or `"public"`; `FORMAT_CODE` maps them to 0 and 1), `ExtData`, `ReferralBonus`
(`fixedBps`, `expiringBps`, `expiresAt`, `issuedAt`), `DepositState`, `ObligationState`,
`AttemptState`, `ObligationWithAttempts`, `WrapperClaim` and `TxEffects`. The enums mirror the
pool: `DepositStatus` (`None`, `Pending`, `Verified`, `Failed`, `Finalized`, `Cancelled`),
`ObligationKind` (`Withdraw`, `Refund`, `Burn`), `ObligationStatus` (`None`, `InFlight`,
`RetryAllowed`, `Settled`) and `AttemptStatus` (`None`, `InFlight`, `Succeeded`, `Failed`).
`WithdrawFeeChangedError` carries `bound`, `current` and `bps`.

## Transactions

Every transaction is one join-split assembled by `transactWith`, proven by a `ProveFn` the caller
supplies, and submitted from a wallet or through a relayer. The node entry wraps it with the
snarkjs prover; a browser supplies its own. [Deposits, withdrawals and transfers](https://docs.fluton.io/sdk/transactions.md)
describes the flow step by step.

| Export | Signature | What it does |
| - | - | - |
| `transactWith` | `transactWith(publicClient, walletClient, params, prove) → Promise<TransactResult>` | One join-split: a transfer or withdrawal, a TOKEN deposit when `screen` is set, or a finalization when `depositId` is set. `walletClient` may be null when relaying. |
| `depositPublicWith` | `depositPublicWith(publicClient, walletClient, { pool, asset, amount, keypair, screen, referrer?, wrapEther?, onStatus?, scan? }, prove) → Promise<TransactResult & { note }>` | A one-step TOKEN deposit as a new note. With `wrapEther`, what the wallet lacks of a wrapped-ether token is wrapped from its ETH first. |
| `finalizeDepositWith` | `finalizeDepositWith(publicClient, walletClient, { pool, depositId, keypair, referrer?, onStatus?, scan? }, prove) → Promise<TransactResult & { note }>` | Turns a `Verified` receipt into a note. Depositor only; safe to re-run after a failed proof. |
| `withdrawWith` | `withdrawWith(publicClient, walletClient, params, prove) → Promise<TransactResult & { change }>` | Pays `recipient` exactly `amount`; the pool's fee and any relayer fee are spent in addition, and the surplus returns as change. |
| `transferWith` | `transferWith(publicClient, walletClient, params, prove) → Promise<TransactResult & { payment, change }>` | A private transfer to a `pp-addr:` address. Nothing crosses the boundary and no asset is named. |
| `wrapEtherWith` | `wrapEtherWith(publicClient, walletClient, { token, need, onStatus?, pollMs?, polls? }) → Promise<WrapEtherResult>` | Brings the wallet's balance of a wrapped-ether token up to `need` by wrapping exactly the shortfall from its ETH; sends nothing when it already holds enough. Simulated first. Throws `InsufficientEtherError` before anything is sent when the wallet's ETH does not cover the wrap and its gas. |
| `commonAsset` | `commonAsset(notes) → number` | The one asset of a list of notes. Throws on an empty list or mixed assets. |
| `encryptOutput` | `encryptOutput(utxo) → Hex` | The on-chain ciphertext of an output note, addressed to its owner. |
| `serializeRelayPayload` | `serializeRelayPayload(proof, ext) → RelayPayload` | The JSON-safe form a relayer accepts. |
| `parseRelayPayload` | `parseRelayPayload(payload) → { proofArg, ext }` | The inverse, shape-validated. |
| `transact`, `depositPublic`, `finalizeDeposit`, `withdraw`, `transfer` | the same parameters plus `wasm`, `zkey` and `large?` | The node wrappers, `@fluton/sdk` only: they build the snarkjs prover from the artifacts and call the matching `…With` function. |
| `buildTransactionInputs` | `buildTransactionInputs({ inputs, outputs, tree, asset, publicAsset, publicAmount, extDataHash, nIns? }) → Promise<{ circuitInputs, inputs, outputs }>` | Pads inputs to 2 or 16 and outputs to 3 with dummies of the same asset and builds every circuit signal. Refuses watch-only inputs, mixed assets and a note that is not in `tree`: notes of different trees are spent in separate transactions. |
| `inputCountFor` | `inputCountFor(notes) → number` | 2 for up to two notes, 16 for more. |
| `isWholeJoinSplits` | `isWholeJoinSplits(nullifiers, leaves) → boolean` | Whether a nullifier count and a leaf count can be whole join-splits. |
| `circuitInputsToJson` | `circuitInputsToJson(inputs) → object` | The signals as decimal strings for a witness calculator. |
| `parseSolidityCallData` | `parseSolidityCallData(raw) → SolidityProof` | Parses snarkjs's Solidity call data. |
| `generateTransactionProof` | `generateTransactionProof(inputs, wasm, zkey) → Promise<SolidityProof>` | A Groth16 proof with one circuit's artifacts. `@fluton/sdk` only. |
| `snarkjsProver` | `snarkjsProver(wasm, zkey, large?) → ProveFn` | A prover that picks the 2-input or 16-input circuit by the inputs' size; without `large`, spending more than two notes throws. `@fluton/sdk` only. |

`TransactParams` takes `pool` and `asset`, and optionally `inputs`, `outputs` (at most two),
`extAmount`, `withdrawFee`, `format` (default `"confidential"`), `recipient`, `fee`, `depositId`,
`referrer`, `screen`, `wrapEther`, `onStatus`, `scan`, `relay` and the `TxHooks` under [Outcomes](#outcomes).
`WithdrawParams` is `pool`, `notes`, `amount`, `recipient`, `format` and the options;
`TransferParams` is `pool`, `notes`, `amount`, `to` and the options without `withdrawFee`. A
`TransactResult` carries `hash`, all three `outputs` with leaf indices, `feeNote` when relayed,
the `withdrawFee` kept and `effects`. `TransactionCircuitInputs`, `SolidityProof`, `ProveFn` and
`CircuitFiles` describe the proving side. `WrapEtherParams` is `token`, `need` (the token base units
the wallet must hold afterwards) and optionally `onStatus`, `pollMs` and `polls`; a `WrapEtherResult`
is `wrapped` (0 when nothing had to be wrapped) and the wrap's `hash` when one was sent.
`InsufficientEtherError` carries `needed` and `held`, in wei.

## eTOKEN deposits, obligations and claims

Everything on the Fhenix CoFHE side: token-first eTOKEN deposits, the authenticated confirmation of
every confidential movement, retries, wrapper claims and encrypted balances. The functions that
decrypt take a `CofheDecryptor`, which a connected client from `@cofhe/sdk` satisfies; the browser
builds its own, and the node entry offers `createNodeCofheClient`.
[TOKEN and eTOKEN](https://docs.fluton.io/concepts/token-formats.md) explains why a receipt alone proves nothing here.

| Export | Signature | What it does |
| - | - | - |
| `requestDepositWith` | `requestDepositWith(publicClient, walletClient, { pool, asset, amount, screen, operatorTtlSeconds?, onStatus? }) → Promise<{ depositId, ok, hash }>` | Step 1: screens the depositor, makes the pool an operator of the wrapper, pulls the eTOKEN and records a receipt. |
| `ensureOperator` | `ensureOperator(publicClient, walletClient, { wrapper, pool, ttlSeconds? }) → Promise<Hex or null>` | Grants the pool operator rights on one wrapper for `ttlSeconds` (default 3600). Null when already granted. |
| `verifyDepositWith` | `verifyDepositWith(publicClient, walletClient, client, { pool, depositId, timeoutMs? }) → Promise<DepositStatus>` | Step 2, permissionless: submits CoFHE's signed decryption of the receipt's `ok` bit. Idempotent once the receipt left `Pending`. |
| `waitForDepositStatus` | `waitForDepositStatus(publicClient, { pool, depositId, until, timeoutMs?, intervalMs? }) → Promise<DepositStatus>` | Polls a receipt until `until(status)` holds. Defaults: 180000 ms, every 2000 ms. |
| `cancelDepositWith` | `cancelDepositWith(publicClient, walletClient, { pool, depositId }) → Promise<{ hash, refundObligation, attemptId }>` | Depositor only: abandons an open receipt and refunds what was actually received. |
| `confirmAttemptWith` | `confirmAttemptWith(publicClient, walletClient, client, { pool, attemptId, timeoutMs? }) → Promise<ConfirmOutcome>` | Permissionless: authenticates an obligation's current attempt. Returns `stale` when it is no longer the in-flight one. |
| `retryObligationWith` | `retryObligationWith(publicClient, walletClient, { pool, obligationId }) → Promise<{ hash, attemptId, asset, claimId }>` | Permissionless: pays the residual through a new attempt after an authenticated failure. |
| `claimUnshieldWith` | `claimUnshieldWith(publicClient, walletClient, client, { wrapper, claimId, timeoutMs? }) → Promise<{ hash, amount }>` | Permissionless: completes a TOKEN withdrawal's claim on the obligation's own wrapper. `hash` is null when it was already claimed. |
| `settleObligationWith` | `settleObligationWith(publicClient, walletClient, client, { pool, obligationId, maxRounds?, timeoutMs? }) → Promise<ObligationState>` | Drives one obligation toward `Settled`: confirm, then retry after a failure, for at most `maxRounds` (default 3). |
| `claimReferralWith` | `claimReferralWith(publicClient, walletClient, { pool, asset, amount, to?, format? }) → Promise<{ hash, obligationId, attemptId }>` | Pays the caller's referral credit through an obligation, as eTOKEN by default or TOKEN. |
| `setReferralBonusWith` | `setReferralBonusWith(publicClient, walletClient, { pool, bonus, signature }) → Promise<{ hash, bonus }>` | Submits a signed bonus attestation. Simulated first, so a stale or badly signed one fails before gas is spent. |
| `unwrapWith` | `unwrapWith(publicClient, walletClient, client, { wrapper, amount, timeoutMs?, onStatus?, onSubmitted?, onUnshielded? }) → Promise<UnwrapResult>` | The wallet's own eTOKEN back to TOKEN, outside the pool, in two wallet transactions: `unshield` burns the amount into a claim, and `claimUnshielded` pays it out once CoFHE has decrypted what was burned. |
| `resumeUnwrapWith` | `resumeUnwrapWith(publicClient, walletClient, client, { wrapper, requested, hash, claimId?, timeoutMs?, receiptTimeoutMs?, onStatus?, onUnshielded? }) → Promise<UnwrapResult>` | Finishes an unwrap whose run was lost after its unshield was sent, from the claim id when it is known, otherwise from the unshield's hash. Never unshields again, and a claim already paid resolves without sending anything. |
| `unwrapClaimIdOf` | `unwrapClaimIdOf(receipt, wrapper) → Hex` | The claim an unshield transaction created on `wrapper` for its sender, read from the receipt's logs. |
| `readConfidentialBalance` | `readConfidentialBalance(publicClient, client, { wrapper, owner }) → Promise<bigint>` | The owner's eTOKEN balance through an ACP-backed view decryption, never the wrapper's indicator `balanceOf`. |
| `decryptForTxWithRetry` | `decryptForTxWithRetry(client, handle, { timeoutMs?, intervalMs?, onRetry? }) → Promise<DecryptedForTx>` | A publicly decryptable handle's value and signature, retried until CoFHE has it. Defaults: 180000 ms, every 3000 ms. |
| `createNodeCofheClient` | `createNodeCofheClient(publicClient, walletClient, { selfAcp? }) → Promise<CofheClient>` | A connected CoFHE client for the wallet's chain. Needs a local account. `@fluton/sdk` only. |

`ConfirmOutcome` is either `{ kind: "confirmed", success, hash }` or `{ kind: "stale", status }`;
`DecryptedForTx` is `{ value, signature }`. An `UnwrapResult` is `unshieldHash`, `claimId`, the
claim's `hash` (null when it had been claimed already) and the `amount` unwrapped. `UnwrapHooks` are
`onStatus`, `onSubmitted(hash)`, called when the unshield is sent, and
`onUnshielded({ hash, claimId })`, called when it ran: persist what they hand you, because once the
unshield ran only its claim pays the tokens back. `UnwrapShortfallError` (`requested`, `unwrapped`, `claimHash`) means the
encrypted balance was below the amount asked for, so less was burned, possibly nothing; what was
burned has been claimed.

## Relayer client

A relayer submits a finished transaction and pays the gas in exchange for a fee note in output
slot 2. The client reads the relayer's identity before any proof is made and quotes the fee at
current gas prices. [Running a relayer](https://docs.fluton.io/operators/relayer.md) documents the service itself.

| Export | Signature | What it does |
| - | - | - |
| `createRelayClient` | `createRelayClient(baseUrl, { chainId?, pool? }) → Promise<RelayClient>` | Reads `GET /status` and refuses a relayer serving another chain or pool. |
| `relay.quote` | `quote() → Promise<RelayQuote>` | `GET /fees`: every served asset at once, per job kind, with `fee` asked and `min` accepted. A relayer without that route is quoted at its minimums. |
| `relay.submit` | `submit(payload) → Promise<Hex>` | `POST /relay`; the hash the transaction was sent under. |
| `relay.txStatus` | `txStatus(nullifier) → Promise<RelayTxStatus>` | `GET /relay/:nullifier`: `pending`, `mined`, `failed` or `unknown`, with the last hash. |
| `relayFeeKind` | `relayFeeKind(extAmount) → RelayFeeKind` | `"transfer"` for a private transfer, `"withdraw"` for anything crossing the boundary. |
| `parseRelayFees` | `parseRelayFees(response) → RelayQuote` | The `GET /fees` body as bigints. |
| `fixedQuote` | `fixedQuote(minFees) → RelayQuote` | A quote made of fixed minimums, for every kind. |
| `waitForRelayedReceipt` | `waitForRelayedReceipt(publicClient, hash, nullifiers) → Promise<TransactionReceipt>` | Follows a re-priced re-send to its receipt. A cancel, any other replacement or a timeout raises `RelayOutcomeUnknownError`. |
| `readFeeNote` | `readFeeNote(keys, commitment, ciphertext) → Promise<FeeNote or null>` | The relayer's own check: decrypts slot 2 and confirms it opens the commitment for the relayer's key. |

A `RelayClient` carries `address`, `pool`, `chainId`, `noteAddress` (parsed) and
`noteAddressText`, and `minFees` per served asset id. `RelayQuote` has `at`, `gasPrice` and
`fees` keyed by asset id and kind. The errors are `RelayFeeChangedError` (`offered`, `fee`,
`min`, thrown before proving), `RelayRefusedError` (a 400: nothing was broadcast) and
`RelayOutcomeUnknownError` (anything else: the transaction may have been sent; `nullifiers` names
the notes). `RelayStatus` and `RelayFeesResponse` are the JSON bodies of `GET /status` and
`GET /fees`. `FEE_SLOT` is 2.

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

const relay = await createRelayClient(relayerUrl, { chainId: 42161, pool });
const fee = (await relay.quote()).fees[asset].transfer.fee;
const res = await transfer(publicClient, null, { pool, notes, amount: 10n, to, relay, fee, wasm, zkey });
```

## Screening

Every pull of value needs a screening of the depositor. The SDK fetches it through the
backend API client, checks it against the pool's current `screeningSigner`, renews it when it is
close to expiry and replaces it once when the pool calls it stale.
[Deposit screening](https://docs.fluton.io/concepts/deposit-screening.md) explains where the verdict comes from.

| Export | Signature | What it does |
| - | - | - |
| `api.screening.screen` | `screen(depositor) → Promise<DepositScreening>` | On an `ApiClient` (see below): a fresh screening of `depositor`. Throws `ScreeningRefusedError` or `ScreeningUnavailableError`. |
| `api.screening.available` | `boolean` | Whether that API serves deposit screening at all. |
| `freshScreening` | `freshScreening(publicClient, screen, current?) → Promise<DepositScreening>` | `current` while it is valid for `SCREENING_MIN_REMAINING_S` past the chain's latest block, otherwise a new one. |
| `simulateWithScreening` | `simulateWithScreening(screen, current, simulate) → Promise<DepositScreening>` | Simulates with `current`; if the pool calls it stale, once more with a new one. Returns the one that passed. |
| `assertPoolTrustsScreening` | `assertPoolTrustsScreening(publicClient, screening, subject) → Promise<void>` | Throws `ScreeningUnavailableError` unless the pool's current `screeningSigner` signed it, before anything is proved or approved. |
| `readScreeningSigner` | `readScreeningSigner(publicClient, pool) → Promise<Address>` | The address whose screenings the pool takes; zero on a pool that names none, which takes no deposits. |
| `isStaleScreening` | `isStaleScreening(error) → boolean` | Whether a revert says the screening expired or its nonce was spent. |
| `screeningRevertReason` | `screeningRevertReason(error) → ScreeningRevert or null` | The pool's screening error inside a viem error, or null. |
| `parseDepositScreening` | `parseDepositScreening(json) → DepositScreening` | A well-formed screening from untrusted JSON, or a throw. |
| `screeningToJson` | `screeningToJson(screening) → DepositScreeningJson` | The JSON form, with the expiry as a decimal string. |
| `screeningDomain` | `screeningDomain(chainId, pool) → domain` | The pool's EIP-712 domain, the one referral bonuses use. |
| `screeningDigest` | `screeningDigest({ chainId, pool, depositor, nonce, expiresAt }) → Hex` | The digest the signer signs and the pool recovers from. |
| `screeningSignerOf` | `screeningSignerOf(screening, subject) → Promise<Address>` | Who signed a screening for that subject. Any 65-byte signature recovers to someone, so compare it. |
| `signDepositScreening` | `signDepositScreening(signer, params) → Promise<DepositScreening>` | A screening of `params.depositor`. In production the backend API signs. |
| `verifyScreeningAnswer` | `verifyScreeningAnswer(body, { chainId, pool, depositor }) → DepositScreening` | Checks the API's answer is about this chain, pool and depositor, and turns a refusal into `ScreeningRefusedError`. |

A `DepositScreening` is `nonce`, `expiresAt` (unix seconds) and `signature` (65 bytes); a `ScreenFn`
is any function returning a fresh one, and a `ScreeningSubject` is the `chainId`, `pool` and
`depositor` it certifies. `ScreeningRefusedError` carries the `depositor` and screening's `code` and
`reason` when given. `SCREENING_MIN_REMAINING_S` is 60, `MAX_SCREENING_TTL_S` is 3600, and
`DEPOSIT_SCREENING_TYPES` is the typed-data definition.

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

const api = await createApiClient(apiUrl, { chainId: 42161, pool });
const screen = () => api.screening.screen(depositor);
const { note } = await depositPublic(publicClient, walletClient, { pool, asset, amount: 40n, keypair, screen, wasm, zkey });
```

## Referrals and bonuses

The pool credits a deposit's referrer by address. Short codes, the Discord and voucher-code
bonuses and deposit screening live in Fluton's backend API, which the SDK treats as untrusted:
every record is wallet-signed and verified before use, and a bonus attestation is checked against
the pool's own `bonusSigner`. [Invite and referrals](https://docs.fluton.io/wallet/invite-and-referrals.md) shows the
wallet side.

| Export | Signature | What it does |
| - | - | - |
| `createApiClient` | `createApiClient(baseUrl, { chainId, pool, timeoutMs? }) → Promise<ApiClient>` | Checks `/health` names this chain and pool and returns a client. Default timeout 8000 ms. |
| `api.referral.byCode` | `byCode(code) → Promise<ReferralRecord or null>` | The verified record for a code, or null when no address holds it. |
| `api.referral.byAddress` | `byAddress(address) → Promise<ReferralRecord or null>` | The verified record of an address's code. |
| `api.referral.claim` | `claim(claim, signature) → Promise<ReferralRecord>` | Claims or changes a code. The API answers 409 when it is taken or a newer claim exists. |
| `api.bonus.status` | `status(address) → Promise<BonusStatus>` | What the address has verified and the signed attestation it adds up to. |
| `api.bonus.discordStartUrl` | `discordStartUrl(state) → Promise<string>` | The Discord consent URL to open. |
| `api.bonus.discordFinish` | `discordFinish(claim, signature) → Promise<BonusStatus>` | Attaches the account a ticket verified to the signing wallet. |
| `api.bonus.redeemCode` | `redeemCode(claim, signature) → Promise<BonusStatus>` | Redeems a voucher code for the signing wallet. |
| `normalizeReferralCode` | `normalizeReferralCode(input) → string or null` | Trimmed and lower-cased, 3 to 32 of `a-z`, `0-9`, `-`, `_`, never starting with `0x`. |
| `isValidReferralCode` | `isValidReferralCode(input) → boolean` | Whether `normalizeReferralCode` accepts it. |
| `parseReferrer` | `parseReferrer(input) → Address or null` | A referrer given as an address: checksum-strict, never zero. |
| `parseReferralRef` | `parseReferralRef(input) → ReferralRef or null` | What an invite link names: an address or a code. |
| `referralCodeMessage` | `referralCodeMessage(claim) → string` | The exact text a referrer signs to claim a code. |
| `signReferralClaim` | `signReferralClaim(walletClient, claim) → Promise<Hex>` | Signs it. The wallet must be `claim.address`. |
| `verifyReferralSignature` | `verifyReferralSignature(claim, signature) → Promise<boolean>` | Checks an EOA signature over the claim message. |
| `verifyReferralRecord` | `verifyReferralRecord(record, expect) → Promise<ReferralRecord>` | Shape, domain and signature of a served record, or `ReferralError`. |
| `referralBonusDomain` | `referralBonusDomain(chainId, pool) → ReferralBonusDomain` | The EIP-712 domain of one pool. |
| `assertReferralBonus` | `assertReferralBonus(bonus)` | Shape and range checks; the two parts together may not exceed `MAX_REFERRAL_BONUS_BPS`. |
| `signReferralBonus` | `signReferralBonus(signer, domain, bonus) → Promise<Hex>` | The EIP-712 signature a bonus signer produces. |
| `verifyReferralBonus` | `verifyReferralBonus(signer, domain, bonus, signature) → Promise<boolean>` | Whether `signature` is `signer`'s. Pass the `bonusSigner` read from the pool. |
| `waitForBonusDate` | `waitForBonusDate(client, issuedAt, { timeoutMs?, intervalMs? }) → Promise<void>` | Waits until the chain's latest block is at or past `issuedAt`, because the pool refuses an attestation dated after the block it lands in. Throws `ReferralBonusError` after `timeoutMs` (default 60000). |
| `normalizeBonusCode` | `normalizeBonusCode(input) → string or null` | Whitespace dropped and upper-cased, 4 to 64 of `A-Z`, `0-9`, `-`, `_`. |
| `bonusCodeMessage`, `discordLinkMessage` | `(claim) → string` | The exact texts a wallet signs to redeem a code or attach a Discord account. |
| `signBonusCodeClaim`, `signDiscordLinkClaim` | `(walletClient, claim) → Promise<Hex>` | Sign them. |
| `verifyBonusCodeSignature`, `verifyDiscordLinkSignature` | `(claim, signature) → Promise<boolean>` | Check them. |
| `verifyBonusStatus` | `verifyBonusStatus(body, expect) → BonusStatus` | Shape and domain of a served status. The attestation's signature is checked separately with `verifyReferralBonus`. |

Types: `ApiClient`, `ApiHealth`, `ReferralDomain` (`chainId`, `pool`), `ReferralClaim`,
`ReferralRecord` (a claim with `signature` and `updatedAt`), `ReferralRef`,
`ReferralBonusDomain`, `ReferralBonusAttestation` (a `ReferralBonus` with its `referrer`),
`SignedReferralBonus`, `BonusCodeClaim`, `DiscordLinkClaim`, `BonusStatus`, `DiscordBonusRoleInfo`
(a role's `name` and the `bps` it adds, as the API lists them) and `ChainClock` (what
`waitForBonusDate` needs of a public client). Errors: `ApiError`
(`status`, 0 when unreachable), `ReferralError`, `ReferralBonusError`, `BonusError`. The EIP-712
domain is `REFERRAL_BONUS_DOMAIN_NAME` (`PrivacyPool`) and `REFERRAL_BONUS_DOMAIN_VERSION` (`1`),
with `REFERRAL_BONUS_TYPES` and `REFERRAL_BONUS_PRIMARY_TYPE` as the typed-data definition;
`REFERRAL_CODE_PATTERN`, `BONUS_CODE_PATTERN` and `DISCORD_TICKET_PATTERN` are the formats.

## Outcomes

A hash is a poor handle for a transaction: a relayer's re-send changes it and the page may be gone
before it arrives. What never changes is the proof, so the SDK hands you its identity before
anything is sent and answers from pool state afterwards.

| Export | Signature | What it does |
| - | - | - |
| `checkTransaction` | `checkTransaction(publicClient, tx, { hash?, scan? }) → Promise<TxOutcome>` | What became of a `PreparedTx`, read at one block. The hash is a shortcut only. Throws while the chain cannot answer. |
| `checkDeposit` | `checkDeposit(publicClient, { pool, depositId, fromBlock, scan? }) → Promise<{ status, finalized? }>` | A receipt's status and, once `Finalized`, the transaction that finalized it, whoever sent it. |
| `receiptCarries` | `receiptCarries(receipt, tx) → boolean` | Whether a receipt succeeded and the pool logged every one of the transaction's nullifiers and commitments. |

`TxHooks` has `onPrepared(tx)`, called with a `PreparedTx` (`pool`, `root`, `nullifiers`,
`commitments`, `fromBlock`) while nothing has been sent, where throwing aborts the send, and
`onSubmitted(hash)`, called as soon as it is on its way, where an exception is ignored.
`TxOutcome` is one of `landed` (with `hash`, `receipt` and `effects`), `reverted` (with `hash`),
`superseded` (with `by`) and `pending`; the first three are final. The pool keeps every root, so a
prepared transaction stays valid until its notes are spent.
`TransactionRevertedError` carries `functionName` and `hash`.

## Chains

The public networks the pool client knows, as viem chains, and the Chainlink ETH/USD feed of each.

| Export | Signature | What it does |
| - | - | - |
| `chainFor` | `chainFor(chainId, rpcUrl, name?) → Chain` | The viem chain for `chainId`, reading and writing through `rpcUrl`. A known chain keeps its name, currency and explorer; any other id becomes a custom chain named `name`. |
| `KNOWN_CHAINS` | `readonly Chain[]` | Sepolia, Arbitrum Sepolia and Arbitrum One. |
| `CHAINLINK_ETH_USD` | `Record<number, Address>` | Chainlink's ETH/USD feed by chain id, for Ethereum, Sepolia, Arbitrum One and Arbitrum Sepolia. |
| `ETH_USD_MAX_AGE_S` | `7200` | The oldest feed answer that still counts as a price, in seconds. |

## ABIs and constants

Both entry points export the ABIs the SDK calls through: `poolAbi`, `erc20Abi`,
`wrappedEtherAbi` and `confidentialWrapperAbi`. The constants below are the protocol's fixed
points, shared with the circuits and the contracts.

| Constant | Value | Meaning |
| - | - | - |
| `FIELD_SIZE` | the BN254 scalar field prime | Every commitment and nullifier lies below it |
| `ZERO_VALUE` | `keccak256("fluton")` reduced into the field | The empty-leaf value of the tree |
| `TREE_LEVELS` | 20 | Tree depth, matching the circuits and the deployed pool |
| `MAX_NOTE_AMOUNT` | 2^248 − 1 | Largest note amount the circuit range-checks |
| `MAX_ASSET_ID` | 2^32 − 1 | Asset ids are uint32 |
| `NULLIFIER_KEY_DOMAIN` | the ASCII bytes of `fluton-nullifier-key` as an integer | Poseidon domain tag of the nullifier key |
| `NOTE_CIPHERTEXT_LENGTH` | 168 | Bytes in every note ciphertext |
| `N_INS`, `N_INS_LARGE`, `N_OUTS` | 2, 16, 3 | Input slots of the two circuits, output slots of both |
| `FEE_SLOT` | 2 | The output slot that carries a relayer's fee note |
| `FEE_DENOMINATOR` | 10000 | Basis points |
| `MAX_REFERRAL_BONUS_BPS` | 5000 | The most a bonus adds to the referral share |
| `SCREENING_MIN_REMAINING_S` | 60 | Validity a screening must still have when sent |
| `MAX_SCREENING_TTL_S` | 3600 | The furthest ahead a screening may expire (the pool's `MAX_SCREENING_TTL`) |
| `FORMAT_CODE` | `confidential: 0`, `public: 1` | `PoolFormat` to `ExtData.format` |

The concept pages behind these numbers are [Notes and proofs](https://docs.fluton.io/concepts/notes-and-proofs.md),
[Private transfers](https://docs.fluton.io/concepts/private-transfers.md) and [Fees and referrals](https://docs.fluton.io/concepts/fees.md).


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