# Deposit screening Source: https://docs.fluton.io/concepts/deposit-screening Why every deposit into the pool carries a Predicate attestation, how one is obtained and checked, and what happens when Predicate is unavailable. Every unit of value enters into the pool through one of two pulls, and each one needs an attestation that the depositor passes the project's [Predicate](https://predicate.io) policy: * `deposit(proof, extData, attestation)` for a TOKEN deposit; * `requestDeposit(asset, amount, attestation)` for an eTOKEN deposit. Verifying and finalizing that receipt need nothing more, because the receipt belongs to the depositor alone. Nothing else is screened. `transact`, the entry point for private transfers and withdrawals, refuses any positive `extAmount` with `DepositRequiresAttestation`, so relayed jobs never carry an attestation and the relayer never has to handle one. Screening sits at the entry to the anonymity set and nowhere else. ## What an attestation is The pool inherits Predicate's `BasicPredicateClient` (from `@predicate/contracts` 2.2.3), which asks about "who", not "what". Before anything is pulled, the pool hands your attestation to the **Predicate Registry**, which checks the attester's ECDSA signature over this statement: ```text theme={null} keccak256(abi.encode(chainId, uuid, depositor, pool, 0, "", policy, expiration)) ``` The registry refuses an expired attestation and an attester it has not registered, and it puts the calling contract in the target's place, so a signature is good only from the pool it was issued for. On success it spends the `uuid` and will never accept it again. So one attestation is good **once, from one wallet, into this pool, on this chain, under the pool's policy**. Nobody else can use yours. It is deliberately not part of the zero-knowledge proof: it is bound to the depositor as `msg.sender`, so swapping it for another attestation of the same depositor changes nothing, and because the registry's bookkeeping is undone when the surrounding transaction reverts, a deposit that fails later leaves its attestation unspent and reusable. The `policy` is the project's verification hash from the Predicate dashboard. The pool registers it with the registry when it initializes, and Predicate's attester reads it back from there. The rules behind the policy (denylists, allowlists, risk providers) change in the dashboard without any transaction on the pool. ## The flow through the API The browser never talks to Predicate and never holds the project's API key. It names its wallet to Fluton's backend API: ```text theme={null} POST /predicate/attestations { "depositor": "0x…" } ``` The API asks Predicate with the project's key and answers one of three things: `status: "attested"` with the attestation, `status: "refused"` with the policy's own reason and code, or HTTP 503 when it could not get a clear answer at all. Anything short of a clear answer (a network error, a timeout, an HTTP error, a malformed or already-expired attestation, or an answer naming another project's policy) becomes that 503. Screening never fails open. The SDK asks **first**, before rebuilding the tree, proving anything or approving any token, so a refused wallet learns it at once and spends nothing on gas or proving time. Predicate's attestations are valid for an **hour** from issue. Just before sending, the SDK fetches a new one if less than a minute of validity is left by the chain's own clock, and once more if the registry calls the attestation stale during simulation. Stale means expired, or spent in the meantime. A refusal is a different thing: it is shown as the policy's answer rather than as a failure, and it is final for that wallet. > [!NOTE] > > A refusal is about the depositing address, not about the amount or the token. The only way past it > is a wallet the policy accepts. ## Trust and failure modes Predicate's attester keys and its upgradeable registry decide who may deposit. The pool's owner can move the pool to another registry with `setRegistry` or to another policy with `setPolicyID`, but **cannot switch screening off**: neither value may be empty, and with no registry in place every deposit reverts. The statement an attester signs names the policy, so an attestation issued under the old policy fails after the pool moves to a new one. If Predicate or the API is unreachable, deposits stop and nothing else does. Transfers, withdrawals, `verifyDeposit` and `finalizeDeposit` never touch the registry, so money already inside the pool keeps moving. And because screening applies at entry only, a depositor flagged after depositing is already in the anonymity set. **What Predicate learns** is what a deposit makes public anyway: the depositor's address, the pool and the chain. Each spent attestation is logged on-chain by the registry as `StatementValidated`, naming the depositor, the pool, the attester and the policy, and the API records every decision (attested, refused or unavailable) in its own database for the audit trail. [What stays public](/concepts/privacy-model) puts that next to everything else a deposit reveals. Attestations are the first thing the deposit flow does, so they show up in every deposit path: see [TOKEN and eTOKEN](/concepts/token-formats) for the two-step eTOKEN route they guard and [Contracts](/reference/contracts) for the exact signatures and errors. # Fees and referrals Source: https://docs.fluton.io/concepts/fees The three money flows around a transaction besides your own: the relayer's fee note, the pool's withdrawal fee, and the referral share credited to whoever invited a depositor. Three payments happen around a transaction in the pool that are not your own movement of value: the note that pays a relayer for your gas, the withdrawal fee the pool keeps on every exit, and the share of that fee credited to the referrer who invited a depositor. A deposit pays no fee at all; a private transfer pays only a relayer, and only if you use one; a withdrawal pays the pool whoever submits it. ## Relayer fee notes A relayer is never paid in public. Its fee is **output slot 2** of the join-split: a note owned by the relayer's shielded address, in the transaction's token, worth what the relayer quotes for current gas prices. Slots 0 and 1 are yours, payment and change; slot 2 holds a zero-amount dummy when you submit the transaction yourself, and on-chain the two cases look the same. See [join-splits](/concepts/notes-and-proofs) for the slot layout. Because the fee never leaves the pool, the contract has **no relayer or caller rule at all**. Anyone may submit a transfer or a withdrawal for you, and the fee note goes to the key named in slot 2 whoever pays the gas. A deposit is the exception: the pool pulls it from the caller, whose own [attestation](/concepts/deposit-screening) it carries. The relayer cannot see inside your proof, so before it spends gas it checks slot 2 itself: * the ciphertext decrypts with its key to a **canonical** opening: an amount below 2^248, a blinding below the field size, a uint32 asset. Poseidon reduces its inputs modulo the field, so without this check a sender could commit to 0 and encrypt the field prime, leaving the relayer paid nothing; * that opening, under the relayer's own spend public key, hashes to slot 2's commitment; * the token is one it serves, and the amount pays for the gas at the current price and is at least the token's fixed minimum; * on a withdrawal, the token named in `ExtData` is the fee note's. The proof binds each slot's ciphertext and commitment together, so a note that passes is exactly the note the transaction creates. Two limits remain. **The token hides only among the tokens that relayer serves**: the relayer is the on-chain sender and its token list is public, so a relayer serving one token names it on every job. And **the relayer knows the token and the fee of what it relays**, because it reads its own fee note; it logs transaction hashes only. Quoting and gas pricing are in [Running a relayer](/operators/relayer). ## Withdrawal fee Every withdrawal pays the pool a fee in basis points of what leaves the notes, rounded up to a whole note unit. The wallet shows it as the **platform fee**: ```text theme={null} withdrawFeeOf(w) = ceil(w * withdrawFeeBps / 10000) ``` Deployments start at **0.35%** (`withdrawFeeBps` 35). The owner can change the rate with `setWithdrawFeeBps`, never above **1%** (`MAX_WITHDRAW_FEE_BPS`, 100 basis points). A withdrawal of `w` note units pays its recipient `w - withdrawFee` and keeps the fee in `protocolFees[asset]`, a public counter per token. Deposits, private transfers and relayer fee notes pay nothing. **It is bound in the proof.** `ExtData.withdrawFee` must equal `withdrawFeeOf(w)` at the rate in force when the transaction lands, and `extDataHash` binds it. If the owner changes the rate between proving and inclusion, the withdrawal reverts with `WithdrawFeeMismatch` and your notes stay unspent. No submitter can patch the fee, because the hash would stop matching, and the SDK and the web app re-read the rate before proving. **It is paid on top of the amount.** The SDK's `withdraw({ amount })` and both web forms treat `amount` as what the recipient receives and spend the fee in addition, exactly like a relayer fee; `withdrawFeeFor(received, bps)` is the fee of the smallest withdrawal that pays out exactly that amount. A withdrawal whose fee would take all of it (one unit at any non-zero rate) reverts with `ZeroPayout`. Nothing new becomes public: the fee is a function of the public amount and the public rate. The owner collects kept fees with `collectFees(asset, amount, to, format)`, paid as eTOKEN or TOKEN through an obligation, just like a withdrawal. Fees owed to referrers are not collectable. ## Referral share A deposit can name a **referrer**: the address that invited the depositor. The pool credits it `referralShareBps` of the withdrawal fee the deposited amount will eventually pay: **25%** (2500 basis points) at deployment, which the owner can change with `setReferralShareBps`, up to the whole fee. The depositor pays nothing extra, because the reward comes out of the pool's own fee. `ExtData.referrer` may be non-zero only on a deposit, where the depositor's wallet is public anyway. A withdrawal never names one, so withdrawals stay as unlinkable as before, and `extDataHash` binds the field, so nobody can add or change a referrer after proving. A cancelled deposit earns nothing. Credits are computed at the rates in force when the deposit lands, rounded down, and never exceed the fee a withdrawal of the same amount pays: ```text theme={null} referralRewardOf(a, r) = floor(a * withdrawFeeBps * referralShareOf(r) / 10000^2) ``` They never change afterwards. Each deposit names its referrer again: the pool keeps no record of who referred whom, only `referralCredit[referrer][asset]`. ### Bonuses A referrer's effective share, `referralShareOf(r)`, is the base `referralShareBps` plus whatever bonus the pool stores for that address: a fixed part, and an expiring part that counts while `block.timestamp` is below its `expiresAt`. The two parts together are capped at `MAX_REFERRAL_BONUS_BPS` (2500), and the resulting share at the whole fee. Bonuses are verified off-chain by Fluton's backend API (the **encrypted** role on Fluton's Discord is worth 2000 basis points for 30 days at a time, a testnet code 500 basis points for good) and arrive on-chain as an **EIP-712** attestation signed by the owner-named `bonusSigner`. Anyone may submit it with `setReferralBonus`; in practice the referrer does, from [the wallet](/wallet/invite-and-referrals). Only an attestation issued strictly later than the stored one is accepted, so a replay cannot roll a bonus back, while a newer one that gives less still lands. A bonus applies to deposits landing after it is set. The owner can revoke one with `revokeReferralBonus`, and `setBonusSigner` changes the signer or, with the zero address, stops new bonuses being set. ### Claiming, and what it reveals Referral credits are a **lien on kept fees**. `referralLiability[X]` is the sum of credits in token X, reserved inside `protocolFees[X]`: the owner collects only the fees above it. A referrer claims its own credit with `claimReferral(asset, amount, to, format)`, paid through an obligation exactly like `collectFees`, once withdrawals have kept at least that much of the token. Until then the call reverts with `InsufficientFees`. Three limits are worth stating plainly. Anyone can refer themselves from a second wallet, which is a 25% rebate on the fee and up to 50% with bonuses. Credits are public per referrer address, as are the link between a deposit and its referrer and the referrer's bonus. And a leaked API signing key can raise anyone's share by at most 25 percentage points of the fee, the bonus cap, until the owner changes the signer and revokes the grants. The wallet side is [invite and referrals](/wallet/invite-and-referrals); what each payment makes public is [what stays public](/concepts/privacy-model). Every function named on this page is listed with its arguments and errors in [Contracts](/reference/contracts); the rates in force and the fees kept per token are public state you can read from the pool. # Keys and view keys Source: https://docs.fluton.io/concepts/keys-and-view-keys How one wallet signature becomes a spend key, what a shielded address and a view key contain, and exactly what read-only access does and does not reveal. A shielded wallet in Fluton has one secret, the **spend key**. Everything else (the address other users pay, the key that decrypts your notes, the key that tells you which of them are spent) is derived from it, one way, so that each piece can be handed out without handing out the ability to spend. ## Spend key Nothing stores a random spend key per browser. Instead your wallet signs one fixed, domain-bound message (EIP-191 `personal_sign`), and the signature is hashed into the key: ```text theme={null} spendKey = keccak256("fluton-spend-key" || signature)[1..32) (31 bytes, always below the field prime) ``` ECDSA in Ethereum wallets uses RFC 6979 deterministic nonces, so the same account always produces the same signature bytes, and therefore the same spend key on every device. There is nothing to back up beyond the wallet itself. The signature never touches the chain and the derivation is one-way, so nothing on-chain links your shielded address to the wallet that signed. The message names the chain and the pool it is for, and spells out what signing it does: ```text theme={null} Fluton - shielded spend key Signing this message derives the SECRET key that controls your shielded balance and decrypts your private payment history. Only sign it inside the Fluton app. Chain ID: Pool: 0x… ``` A different chain or a different pool address yields an unrelated key. In the SDK this is one call, and one wallet prompt: ```ts theme={null} const spendKey = await deriveSpendKey(walletClient, { chainId, pool }); ``` > [!WARNING] > > Anyone who can obtain that signature (through phishing, or a compromised wallet) owns the > shielded funds and can decrypt the whole note history. Only sign it in the app you mean to use. Pasting a raw key stays available as a fallback. It behaves the same afterwards; it is simply not reproducible from a signature. ## Shielded address To be paid privately, you hand out a shielded address. It carries two public values: your Poseidon **spend public key**, which outputs are created for, and an **x25519** public key, which note ciphertexts are encrypted to. The x25519 keypair is derived deterministically from the spend key, so the single secret recovers everything. ```text theme={null} pp-addr:: ``` That is all a payer needs. The recipient of a [private transfer](/concepts/private-transfers) never touches the chain, never needs gas, and never appears in the calldata. ## View key The spend key is split in two, so read-only access is possible without any ability to move funds. Two derived secrets do the reading: * `nullifierKey` is `Poseidon(spendKey, NULLIFIER_KEY_DOMAIN)`, one-way. It computes each note's nullifier, so its holder can ask the pool which notes are spent and derive the true balance. * the x25519 encryption secret is also one-way from the spend key. It decrypts every note ever sent to the address, yielding `(amount, blinding, asset)`, which together with the spend public key reconstructs each commitment and finds its leaf. Handing out those two plus the spend public key is a **view key**: ```text theme={null} pp-view::: ``` ```ts theme={null} const view = await viewKeyFromSpendKey(spendKey); ``` A view key watches exactly the same shielded address as the spend key it came from, and it is enough to run a full scan. What it shows an auditor, an accountant, a server tracking incoming payments, or a **watch-only** wallet on a device you do not trust: | A view key shows | A view key does not show | | - | - | | Every note ever sent to the address, of every token | The spend key, which neither derived value yields | | Which notes are spent, so the real balance | The recipient of an outgoing payment | | The full history: deposits, received payments, change | The amount of an outgoing payment, beyond the change that came back | Neither derived value yields the spend key, and a transaction proof needs the spend key itself, so a view-key holder cannot move funds: the SDK refuses to build transaction inputs for a watch-only keypair rather than producing an unprovable witness. An outgoing viewing key, which would reveal where your payments went, is not implemented. > [!NOTE] > > A view key is a secret, even though it cannot spend. It reveals your entire balance and payment > history to whoever holds it, and it cannot be rotated without moving your notes to a new spend > key. The web wallet can reveal a view key for the current wallet and can open a pasted one in watch-only mode; see [using the wallet](/wallet/using-the-wallet). The SDK side (deriving keys, encoding addresses and scanning with either kind of key) is [keys and scanning](/sdk/keys-and-scanning), and what a scan can and cannot see from the chain alone is in [what stays public](/concepts/privacy-model). # Many tokens, one pool Source: https://docs.fluton.io/concepts/multi-token How several tokens share one tree and one anonymity set in the pool, and why value can never move between them. Fluton has one pool. One Merkle tree, one nullifier set, one **anonymity set** for every token it lists. A second token does not get its own pool; it gets an id. That is the point: separate pools would split the crowd each withdrawal hides in. Sharing one tree means a USDC deposit and a WETH deposit thicken the same set of leaves, and a private transfer that names no token thickens it for all of them at once. ## Asset id Each listed token is numbered in listing order: 1, 2, 3 … The **asset id** is hashed into every note's commitment, alongside the amount, the owner's public key and the blinding. A note is therefore permanently a note of that token: you cannot re-open it as another asset, because the commitment would not match. The pool's registry maps an id to its three facts: the eTOKEN wrapper that holds the reserve, the underlying ERC-20, and the `rate` between note units and token base units (see [TOKEN and eTOKEN](/concepts/token-formats)). The listing is append-only, there is no delist or edit, and the pool refuses more than `MAX_ASSETS` assets, which is **32**. [Contracts](/reference/contracts) covers the rules a new wrapper has to satisfy. ## One join-split, one asset Inside the circuit there is exactly one private `asset` signal per transaction, and it is hashed into all of the input and output commitments. So one join-split can only ever spend and create notes of a single token. Mixing is not forbidden by a check; it is unrepresentable. To let the contract know which token it is paying or pulling, the proof carries one more public input, `publicAsset`, tied to the private asset by a single constraint: ```text theme={null} (asset − publicAsset) · publicAmount === 0 ``` The field has no zero divisors, so one of the two factors must vanish: * **A transaction that crosses the pool boundary** has `publicAmount != 0`, which forces `asset == publicAsset`. It has proved what its notes are made of. The pool reads `publicAsset` from `ExtData.asset`, never from the caller's proof struct, and uses it to pick the token, the wrapper and the rate. * **A private transfer** has `publicAmount = 0`, so the constraint is satisfied whatever the asset is. The token stays private, and `publicAsset` is still bound by the proof, so nobody can patch it afterwards. ## Private transfers name no token Because a transfer leaves the asset unconstrained, the pool insists that it also leaves it unnamed: with `extAmount = 0`, `ExtData.asset` must be 0, or the transaction reverts with `HiddenTransactionNamesAsset`. The calldata of a private transfer therefore contains no token, no amount and no recipient, whether it is relayed or sent from your own wallet. Its three new leaves join **every** token's anonymity set at once. An observer looking at a USDC withdrawal cannot rule out any transfer in the tree as its ancestor, because no transfer admits to being USDC or not. Deposits and withdrawals always name their token: value visibly enters or leaves, so the token is public by construction. ## Why value cannot cross tokens The argument is an induction over accepted transactions, and it rests on four facts: 1. **Every leaf has one opening.** A leaf enters the tree only as an output commitment of an accepted proof, and that proof range-checks the output amount below **2^248** and hashes it with the transaction's asset. 2. **A non-zero input must be such a leaf.** The circuit skips the membership check only for amount-zero dummies, so anything that contributes value was a real, range-checked output of the transaction's asset. 3. **Conservation holds over the integers**, not just modulo the field: outputs are under 2^248, inputs were too, and `extAmount` is bounded by uint64, so `sumIns + publicAmount = sumOuts` cannot wrap. 4. **The asset is pinned when value crosses.** By the constraint above, a transaction changes the unspent value of asset X by `publicAmount` when `publicAsset = X`, and by exactly 0 otherwise. So the pool's per-asset counter `noteLiability[X]`, which the contract moves by `extAmount` on every accepted join-split, always equals the unspent note value of asset X. A note of an asset the pool does not list can only be worth 0, because value enters only through a listed asset's boundary: a transaction of an unfunded id has nothing but dummy inputs, and its non-negative outputs must therefore all be zero. Trying to spend a WETH note in a USDC transaction fails earlier still; under the transaction's asset that note hashes to a commitment that is not in the tree, so its membership check cannot pass. `noteLiability[X]` is one of the four terms in the pool's [backing invariant](/concepts/token-formats), which is checked per asset and never mixes two of them. ## Canonical ExtData If the public fields of a transaction were free-form, they would fingerprint the software that built it, and a fingerprint is a link. So the pool requires `ExtData` to be **canonical**: every field a route does not use must be zero, and anything else reverts. | Field | When it may be non-zero | | - | - | | `recipient` | only when tokens leave the pool | | `withdrawFee` | only when tokens leave the pool, and exactly the fee of that amount | | `referrer` | only when tokens enter the pool, and never the pool itself | | `asset` | zero exactly when `extAmount` is zero | | `format` | confidential or public; must be confidential when `extAmount` is zero | | `depositId` | only in a finalization of an eTOKEN deposit receipt | | `chainId`, `pool` | always this chain and this pool | | `encryptedOutputs` | always exactly three blobs of 168 bytes each | A violation gets a specific error: `NonCanonicalExtData`, `HiddenTransactionNamesAsset`, `InvalidCiphertext`, `DepositIdNotAllowed`, `WrongChain`, `WrongPool` rather than a silent acceptance. And because `extDataHash` binds the whole struct, a submitter cannot quietly fill a field in to mark the transaction either ([Notes and proofs](/concepts/notes-and-proofs)). What the two formats mean for crossing the boundary is on [TOKEN and eTOKEN](/concepts/token-formats); the contract-level registry and errors are in [Contracts](/reference/contracts), and the asset constraint in [Circuits](/reference/circuits). # Notes and proofs Source: https://docs.fluton.io/concepts/notes-and-proofs The UTXO model behind Fluton: what a note is, how commitments and nullifiers are formed, and what one join-split proof proves. Fluton holds no account balances. It holds **notes**, in the UTXO style, and a single append-only Merkle tree of their public commitments. Every state change, whether a deposit, a withdrawal or a private transfer, is one **join-split** proof that destroys some notes and creates exactly three new ones. Nothing about a note is public except its commitment, the ciphertext that delivers it to its owner, and, when it is spent, its nullifier; the only amount the chain ever sees is the net amount crossing the pool boundary. ## A note A note is the tuple `(amount, keypair, blinding, asset)`. Four **Poseidon** hashes derive everything the protocol needs from it: ```text theme={null} publicKey = Poseidon(privateKey) commitment = Poseidon(amount, publicKey, blinding, asset) nullifierKey = Poseidon(privateKey, NULLIFIER_KEY_DOMAIN) nullifier = Poseidon(commitment, leafIndex, nullifierKey) ``` * The **commitment** is the public tree leaf. It hides the amount, the owner and the token behind the random `blinding`. * The **nullifier** is what spending reveals. The leaf index is hashed into it, so one leaf has exactly one nullifier, and the pool can mark it spent without learning which leaf it was. * `nullifierKey` is a one-way derivation from the private key, with the domain tag `NULLIFIER_KEY_DOMAIN`, the ASCII bytes of `fluton-nullifier-key` as a 20-byte integer, the same constant in the circuit and in the SDK. Routing the key through it is the split that makes a read-only [view key](/concepts/keys-and-view-keys) possible: a holder of `nullifierKey` can tell which notes are spent but cannot produce a proof. * `asset` is the pool's asset id for the token, so a note can only ever be spent as that token. See [Many tokens, one pool](/concepts/multi-token). Poseidon reduces its inputs modulo the field prime, so an opening taken from untrusted bytes is believed only after a canonical check: the amount below 2^248, the blinding below the field size, the asset a uint32. Without it, someone could commit to 0 and hand you an opening of `p`, and your wallet would show a balance it does not have. ## The join-split One proof spends up to 2 notes (`transaction.circom`, `Transaction(20, 2, 3)`) or up to 16 (`transaction16.circom`, `Transaction(20, 16, 3)`), and creates **exactly 3** new notes in both cases. Both instantiate the same template, in `joinSplit.circom`. The core constraint is **value conservation**: ```text theme={null} sumIns + publicAmount === sumOuts ``` `publicAmount` is the net amount crossing the pool boundary, encoded in the field: positive is a deposit, and a withdrawal of `x` is the field element `p - x`. A private transfer has `publicAmount = 0`, so nothing enters or leaves. The contract recomputes the value from `ExtData.extAmount` and refuses a proof that does not match it. Unused input slots carry zero-amount **dummy** notes. The circuit computes each input's Merkle root but only forces it to equal the published root when the input's amount is non-zero, so a freshly generated dummy needs no leaf in the tree. Every output is range-checked to 248 bits, which keeps sums of note amounts from ever wrapping the field: even 16 inputs sum to under 2^252. One more rule closes the obvious gap inside one proof: no two inputs of one transaction may share a nullifier, and the circuit compares every pair to enforce it. Across transactions it is the nullifier itself that catches a note already spent. What the pool checks before it accepts a proof is on [Contracts](/reference/contracts). ### Which verifier runs The pool keeps one verifier per circuit and picks it by the **number of nullifiers** in the payload: 2 for the everyday circuit (9 public signals) and 16 for the consolidation circuit (23 public signals). Any other count is refused. That number is public; how many of those inputs are real notes rather than dummies is not. The 16-input circuit is for spending many notes at once, such as a relayer collecting its fee notes. ### What the three output slots are for | Slot | Owner | | - | - | | 0 | the user: the payment, the withdrawal's change, or a dummy | | 1 | the user: change, or a dummy | | 2 | the relayer's fee note when a relayer submits, otherwise a zero-amount dummy | The circuit does not distinguish the slots; the layout is a convention of the SDK and the relayer. On-chain, a fee note and a dummy look the same. See [Fees and referrals](/concepts/fees). ## The Merkle tree `MerkleTreeWithHistory` is an append-only Poseidon tree whose depth is fixed when the pool initializes; 20, to match the circuits. A node is `Poseidon(left, right)`, the same hash as in the circuit and in the client, and empty subtrees start from `ZERO_VALUE`, which is `keccak256("fluton")` reduced into the field. Everything it hashes, the three new leaves included, has to be below `FIELD_SIZE`: a commitment that is not reverts with `NodeOutOfField` instead of being silently reduced. Each accepted transaction appends its three leaves as **one batch** and records **one root**. The batch append hashes at most two nodes per level, no more than two single-leaf appends would. The pool accepts any of its last `ROOT_HISTORY_SIZE` roots, which is **30**. Since every transaction records exactly one root, that window covers the last 30 transactions: a proof built against a slightly stale tree still lands, and one built against a root older than that is refused and has to be rebuilt. Clients rebuild the tree from the pool's commitment events; `getLastRoot()` and `nextIndex()` are the pool's own answers to check a rebuilt tree against (see [Keys, notes and scanning](/sdk/keys-and-scanning)). ## What extDataHash binds Every public side effect of a transaction lives in one `ExtData` struct: the recipient, `extAmount`, the withdrawal fee, all three note ciphertexts, and domain fields; among them the asset, the note format and a deposit's referrer. The circuit sees it as one opaque public input, **extDataHash**, the keccak hash of the encoded struct reduced into the field, which the pool recomputes from the calldata it was given. [Contracts](/reference/contracts) has the struct field by field. So a transaction cannot be re-targeted. Change the recipient, the amount, the fee, a ciphertext or the token, and the hash no longer matches the proof, which the verifier then rejects. An observer watching the mempool can refuse to submit a transaction, but cannot redirect it or overcharge it. ## Deposit and withdrawal, side by side ```text theme={null} Deposit 13.37 Withdraw 4 (partial, through a relayer) ───────────── ─────────────────────────────────────── ins: (dummies) ins: the 13.37 note (nullifier revealed) outs: note(13.37), dummy, dummy outs: change(9.36), dummy, <- all stay fee note(0.01 → relayer) shielded publicAmount: +13.37 publicAmount: -4 extData(recipient, amount, 3 ciphertexts) hash-bound in proof ``` A deposit spends nothing and creates a note for the depositor. A withdrawal spends one note, keeps the change inside the pool, pays the relayer with slot 2, and names only the recipient, the token and the public amount. > [!NOTE] > > A deposit and a withdrawal publish their amount and token because value visibly crosses the > boundary; a [private transfer](/concepts/private-transfers) publishes neither. [What stays > public](/concepts/privacy-model) lists this operation by operation. For the contract functions and errors see [Contracts](/reference/contracts), and for the circuit files, public-input order and trusted setup see [Circuits](/reference/circuits). # What stays public Source: https://docs.fluton.io/concepts/privacy-model Operation by operation, what Fluton reveals on-chain and to whom, what it hides, and the known limits of the anonymity it offers. Fluton hides who paid whom, not that the pool exists. Crossing the pool's boundary is a public act: the circuit needs a plaintext `publicAmount` and `publicAsset`, so a deposit and a withdrawal each name their amount, their token and the format they chose. Everything that happens strictly inside the pool can hide all three. This page is the plain list, so that the guides and the wallet pages do not have to argue it again. ## What is public, and to whom | Operation | What the chain shows | Who else learns something | | - | - | - | | TOKEN deposit | The depositing wallet, the amount, the token, the format chosen (TOKEN). TOKEN balances are public anyway, as for any ERC-20. | The registry logs the attestation it spends: depositor, pool, attester, policy. Predicate learns the depositor's address, which the deposit makes public regardless. | | eTOKEN deposit | The depositing wallet, the amount, the token, the format chosen (eTOKEN). eTOKEN balances, the pool's reserves and any refund stay encrypted. | The same screening log and the same address, for the same reason. | | Withdrawal | The amount, the token, the format and the recipient address. | The relayer, if one submits it, is the on-chain sender and reads its own fee note, so it knows the token and the fee. | | Private transfer, self-sent | A pool transaction with its new commitments and ciphertexts, and the wallet that sent it. No amount, no recipient, no token. | Nobody beyond the chain. | | Private transfer, relayed | A pool transaction with its new commitments and ciphertexts, and the relayer as sender. No amount, no recipient, no token, no sender. | The relayer knows the token and the fee, because it reads its fee note. It logs transaction hashes only. | | Fee collection | The withdrawal fee rate, and the fees kept per token in `protocolFees`, so what the owner has taken is public. A relayer's fee income shows only when it withdraws it: the total of one token since its last withdrawal. | Nobody. | | Referral | A deposit's referrer, each referrer's credits and claims, and a referrer's bonus. A withdrawal names no referrer at all. | Nobody. | An indexer adds nothing to this picture. It is a read-only view of the same public events, so whatever is public on the chain is public to it, and whatever is not is not. ## What is hidden Amounts inside the pool are never revealed; only the net amount crossing the boundary is. A private transfer shows neither its amount, nor its recipient, nor its token, whether you submit it yourself or a relayer does for you; a relayed one does not show its **sender** either, because the relayer is the on-chain sender and it is paid with a note rather than in public. eTOKEN balances, the pool's reserves, refunds and the amounts of notes are encrypted or shielded throughout. With and without the relayer, side by side: | Private transfer | Through the relayer | From the wallet | | - | - | - | | Sender's wallet | Hidden, the relayer sends | Visible | | Token | Not named | Not named | | Amount, recipient | Hidden | Hidden | Deposits and withdrawals always name their token, because value enters or leaves the pool in public. ## Known limits * **A self-sent transfer exposes its sender.** Your wallet visibly interacted with the pool, though nothing links that transaction to the recipient, to any amount or to any token. Submitting through a relayer hides the sender too. * **A relayed token hides only among the tokens that relayer serves.** The relayer's list is public, so a relayer serving one token effectively names it. * **Screening is at entry only.** Predicate's attester keys and its upgradeable registry decide who may deposit, and the pool's owner can only point the pool at another registry or policy. An address flagged after it deposited is already in the anonymity set. If Predicate or the API is down, deposits stop and nothing else does. * **Anyone can refer themselves from a second wallet**, which amounts to a 25% rebate on the withdrawal fee, and up to 50% with bonuses. Credits are public per referrer address, as is the link between a deposit and its referrer. * **The token list is owner-controlled**: append-only, with no removal. * **The pool is upgradeable.** The `ProxyAdmin`'s owner can replace the pool's code and with it every rule on this page, including who can withdraw what. The fee cap, the append-only token list and renouncing ownership bind only until an upgrade. For why the relayer's fee is a note rather than a public payment, see [fees and referrals](/concepts/fees); for what the ciphertexts of a transfer do and do not carry, [private transfers](/concepts/private-transfers). # Private transfers Source: https://docs.fluton.io/concepts/private-transfers Payments that never leave Fluton's Pool: shielded addresses, encrypted note delivery, and scanning as note recovery. A join-split can create an output for **any** public key, not only your own. That is all a payment inside the pool needs. You spend a note you own, you address one of the new notes to someone else's key, and the value never crosses the pool boundary: no tokens move, and the chain carries nothing but the transaction's three commitments, their ciphertexts and its input nullifiers. A private transfer therefore has `extAmount = 0`, and so `publicAmount = 0`. The recipient never has to touch the chain: no gas to pay and no prior on-chain history to have. ## Shielded address The recipient hands out a **shielded address**, serialized as `pp-addr:` followed by two hex fields: ```text theme={null} pp-addr:: ``` The first is the Poseidon spend public key that goes into the note's commitment. The second is an **x25519** public key, derived deterministically from the same spend key, that the note's ciphertext is encrypted to. Both come out of one SDK call: ```ts theme={null} const address = await shieldedAddressFromSpendKey(spendPrivateKey); // pp-addr:1f3…:9c2… ``` Because the encryption key is derived from the spend key rather than stored, there is nothing extra to back up: the one secret reproduces the address, decrypts every note sent to it and spends them. Parsing refuses anything that is not two well-formed hex fields with a public key inside the field. How a wallet signature becomes that spend key is on [Keys and view keys](/concepts/keys-and-view-keys). An address is not an account. Paying one twice creates two unrelated commitments, and nothing on-chain groups them. ## Ciphertext per output A commitment alone is useless to its new owner: they cannot guess the blinding. So every one of the three outputs ships a ciphertext of its opening, `(amount, blinding, asset)`, encrypted to the owner's x25519 key: ```text theme={null} blob = ephemeralPub(32) || nonce(24) || XSalsa20-Poly1305(key, nonce, amount||blinding||asset) key = keccak256(x25519(ephemeralPriv, recipientEncPub)) ``` Every blob is exactly **168 bytes**: 32 for the ephemeral key, 24 for the nonce, 16 for the authentication tag and 32 each for the amount, blinding and asset. The pool rejects any other length, so a ciphertext's size says nothing about the note inside it. A one-unit transfer and a million-unit transfer look identical. The three ciphertexts are fields of `ExtData`, so they are inside `extDataHash` and bound into the proof. Nobody between you and the chain can swap, drop or re-encrypt one: a relayer that tampered with a ciphertext would invalidate the proof it was paid to submit. That is what makes delivery safe over an untrusted path. See [Notes and proofs](/concepts/notes-and-proofs) for the binding itself. ```text theme={null} Transfer 3.33 from Alice to Bob (extAmount = 0: no tokens move) ────────────────────────────────────────────────────────────── ins: Alice's 10 note on-chain: 3 commitments + 3 ciphertexts outs: note(3.33 → Bob's pubkey), NOT on-chain: amount, Bob, Alice's balance change(6.67 → Alice) Bob later: scanShieldedNotes(secretKey) -> discovers + can spend the 3.33 note ``` ## What is on-chain and what is not | On-chain | Not on-chain | | - | - | | Three commitments, with their leaf indices | The amount | | Three 168-byte ciphertexts | The recipient, and that there is a recipient | | The input nullifiers (2 or 16 of them) | Which leaves those nullifiers came from | | The transaction's sender, if you submit it yourself | The token: `ExtData.asset` is 0 for a transfer | A transfer names no token, so its three new leaves join the anonymity set of **every** listed token at once ([Many tokens, one pool](/concepts/multi-token)). Nor does the payload distinguish a payment from mere self-shuffling: a transfer that pays nobody but yourself produces exactly the same shape. ## Scanning as recovery The recipient finds the note by trying to decrypt it. The SDK's `scanShieldedNotes` walks every commitment the pool ever emitted, attempts an authenticated decryption of each ciphertext with your encryption secret, and keeps the ones that open: ```ts theme={null} const { notes, spendable, balances } = await scanShieldedNotes(publicClient, pool, spendPrivateKey); ``` Authenticated decryption is the filter: another user's blob fails its tag check and is skipped. A blob that does open is checked again before it is believed: the opening must be canonical, re-hashing it under your own public key must reproduce the commitment that was published, and the asset must be one the pool lists. The commitment hashes the asset, so a ciphertext claiming the wrong token is discarded, and a transfer that kept its token private on-chain is still **recovered** as the right token. Each note's spent status comes from its nullifier, which your key can compute. This is why scanning doubles as **note recovery**. One secret key, plus chain data, reconstructs every note you own (payments received, your own deposits, every piece of change, of every token) with no server, no backup file and no note strings to keep. A view key does the same read-only. Pass a view key instead of the spend key and the notes come back without a private key: visible, countable, not spendable. Scanning is a full history walk, so clients read the commitment events in chunked block ranges, and may use an indexer to avoid rescanning everything on every refresh. The indexer's answer is accepted only if the tree rebuilt from it matches the pool's own root, leaf count and nullifier count at one pinned block, and is otherwise thrown away for a plain RPC scan. [Keys, notes and scanning](/sdk/keys-and-scanning) covers the SDK side. ## Relayed or sent from your own wallet Submit the transfer yourself and your wallet is the public sender of a pool transaction (nothing more: no amount, no token, no recipient); submit it through the hosted relayer, which pays the gas in exchange for a fee note, and the public sender is the relayer instead. See [Fees and referrals](/concepts/fees) and [What stays public](/concepts/privacy-model). # TOKEN and eTOKEN Source: https://docs.fluton.io/concepts/token-formats The two formats for crossing the pool boundary, the Fhenix wrappers behind them, token-first deposits, obligations, and the backing invariant. The pool does not hold plain ERC-20 reserves. For each listed asset it holds the reserve in a **Fhenix** confidential token: an **FHERC20** wrapper whose balances are encrypted, running on Fhenix **CoFHE**. There is still only one pool: one tree, one nullifier set, one anonymity set for every token ([Many tokens, one pool](/concepts/multi-token)), and the pool's notes are denominated in wrapper units whichever format you used to get in. ## TOKEN and eTOKEN Each listed asset pairs two contracts: the plain ERC-20, the **TOKEN** (for example USDC), and its FHERC20 wrapper, the **eTOKEN** (for example eUSDC), which is the pool's reserve for that asset. TOKEN and eTOKEN are not two pools and not two balances. They are **formats** for crossing the boundary, chosen per transaction: | | in (deposit) | out (withdrawal) | | - | - | - | | **TOKEN** (public ERC-20) | one step: the pool pulls `units × rate` TOKEN and calls the wrapper's `shield` | burn eTOKEN into a wrapper **claim** for the recipient → `claimUnshielded` pays TOKEN | | **eTOKEN** (encrypted balances) | token-first: `requestDeposit` → `verifyDeposit` → `finalizeDeposit` | confidential transfer to the recipient | Deposit in one format and withdraw in the other: the notes in between are the same notes. Which format a boundary transaction uses is public, because value visibly moves; `ExtData.format` carries it, and a private transfer must always be the confidential format. ### Units and rate A wrapper keeps `min(decimals, 6)` decimals, and one note unit is its `rate` in TOKEN base units: `10^(decimals − 6)`, so 1e12 for 18-decimal WETH and 1 for 6-decimal USDC. A TOKEN deposit of `units` therefore pulls `units × rate` TOKEN wei, and a TOKEN claim pays the burned amount times the same rate. An amount crossing the boundary stays within uint64, which is also the cap each wrapper puts on its total supply. ### Domain-bound ExtData Every public side effect of a transaction lives in `ExtData`, which the circuit treats as one opaque hash. Its domain fields (`chainId`, `pool`, `asset`, `format`, and `depositId` for a finalization) are inside `extDataHash`, so a proof cannot be replayed on another chain, pool, token, format or deposit receipt. A finalization must also name its own receipt's asset. ## Why "just swap the token" fails Here is the fact the whole design turns on: an FHERC20 transfer or burn that exceeds the sender's balance **does not revert**. It silently moves 0, and returns the amount it actually moved as an encrypted handle. A successful transaction receipt therefore proves nothing at all about how much value changed hands. So the pool never credits or settles anything on a receipt alone. It reads the returned handle, compares it with what it asked for, and waits for CoFHE's signed decryption before it calls anything done. Two consequences follow. ## Token-first eTOKEN deposits An eTOKEN deposit pulls the tokens **before** any notes exist, and creates the notes only once the pull is authenticated: **1. requestDeposit(asset, amount, attestation)** The depositor's call. The pool pulls eTOKEN from the depositor, who has made the pool an operator of that wrapper, and records a depositor-owned **receipt** in that asset, storing the encrypted amount actually received plus a publicly decryptable `ok` bit for `received == amount`. No proof and no nullifiers yet. The pull needs a Predicate attestation of the depositor ([Deposit screening](/concepts/deposit-screening)). **2. verifyDeposit(depositId, success, signature)** Anyone (the relayer's keeper, or the user's own browser) submits CoFHE's signed decryption of that bit, moving the receipt `Pending → Verified | Failed`. The call does nothing once the receipt has left `Pending`, so a replayed signature can never resurrect a cancelled or finalized receipt. **3. finalizeDeposit(proof, extData) or cancelDeposit(depositId)** Only the **depositor** can close the receipt: `finalizeDeposit` proves a join-split that creates the notes and binds the `depositId`, while `cancelDeposit` abandons it and refunds what was actually received. The two are mutually exclusive. A failed proof or an expired root leaves the receipt `Verified`, so you simply prove again; the tokens are not pulled twice. Receipt statuses are `Pending`, `Verified`, `Failed`, `Finalized` and `Cancelled`, and an open receipt is readable on-chain by its id, which is how a wallet can offer to resume or cancel it later. Deposits are never relayed, so they never pay a relayer fee. A TOKEN deposit needs none of this: `deposit` takes the depositor's attestation, proves the join-split, pulls the ERC-20 and calls the wrapper's `shield` in one step, with both legs checked against balance deltas, so a fee-on-transfer token's short delivery reverts. | Function | Who may call it | | - | - | | `deposit` (TOKEN, one step) | the depositor, with an attestation | | `requestDeposit` | the depositor, with an attestation | | `verifyDeposit` | anyone | | `finalizeDeposit` | the depositor only, on a `Verified` receipt | | `cancelDeposit` | the depositor only, while the receipt is not closed | | `confirmAttempt` | anyone | | `retryObligation` | anyone, after an authenticated failure | | `claimUnshielded` (the wrapper) | anyone, by exact claim id | ## Obligations and attempts Every outbound movement of eTOKEN is an **obligation**: a withdrawal payout, a deposit refund, or a TOKEN burn. Its asset is fixed when it is created, and it is paid only from that asset's wrapper, through one or more **attempts**. Each attempt records what was requested, what actually moved, and a public bit for `sent == requested`: * `confirmAttempt(attemptId, success, signature)` is permissionless, and accepts a signed decryption for the obligation's *current, in-flight* attempt only. A stale or replayed confirmation reverts. * Only an **authenticated failure** enables `retryObligation(obligationId)`, which pays just the encrypted residual through a new attempt. It flips the obligation to in-flight before any external call, so concurrent retries revert. * Obligation statuses run `InFlight → Settled` or `InFlight → RetryAllowed → InFlight …`; an attempt is `InFlight`, `Succeeded` or `Failed`. A TOKEN withdrawal has an extra leg. The pool burns eTOKEN into a wrapper **claim** and records that attempt's exact claim id, read back from `ConfidentialWrapper.lastClaimId()` in the same transaction. Only what was actually burned becomes claimable, any unburned residual stays owed by the pool, and the wrapper's `claimed` flag stops double payment. Claim ids are unique per wrapper only, so the keeper, the indexer and the web app all key a claim by its asset's wrapper plus the claim id, and `claimUnshielded` must be called on that wrapper. ## Backing invariant For every listed asset X the pool maintains: ```text theme={null} eX balance(pool) ≥ noteLiability[X] + protocolFees[X] + depositLiability[X] + payoutLiability[X] ``` * `noteLiability` (plaintext): the value of unspent notes. Every accepted join-split moves it by `extAmount`; a relayer's fee note stays inside it. An eTOKEN deposit adds to it only at finalization. * `protocolFees` (plaintext): withdrawal fees kept and not yet collected ([Fees and referrals](/concepts/fees)). * `depositLiability` (encrypted): the `received` amounts of receipts that are still open. * `payoutLiability` (encrypted): the residuals of unsettled obligations. Anyone can ask the pool to check it. `checkBacking(asset)` is a transaction, not a view: it adds the four terms under encryption, compares the sum with the pool's encrypted eTOKEN balance, makes the resulting bit publicly decryptable and emits `BackingChecked`. A monitor can therefore confirm that the reserve covers the liabilities without learning any of the encrypted terms. Each step changes one asset's row, and moves only that asset's wrapper. A private transfer, relayed or not, and a rate change move nothing: | Step | eX balance | noteLiability\[X] | protocolFees\[X] | depositLiability\[X] | payoutLiability\[X] | | - | - | - | - | - | - | | `addAsset` (X) | 0 | 0 | 0 | 0 | 0 | | TOKEN deposit of `e` units | +e (exact) | +e | | | | | `requestDeposit(X, r)` | +received | | | +received | | | `finalizeDeposit` | | +r | | −received | | | `cancelDeposit` | | | | −received | +received | | withdrawal of `w` units, fee `f` | | −w | +f | | +(w − f) | | `collectFees(X, c)` | | | −c | | +c | | `claimReferral(X, c)` | | | −c | | +c | | payout attempt that moves `s` | −s | | | | −s | | private transfer | | | | | | Why a withdrawal can never exceed the backing, in short: conservation makes a join-split lower note value by exactly what leaves, which is the obligation it creates plus the fee it keeps; nullifiers stop a note being spent twice; notes are credited only after value provably arrived (an exact mint for TOKEN, an authenticated `received == amount` for eTOKEN); a refund comes out of `received`, which never became note value; a relayer's fee is a note, so it adds no payout; an obligation shrinks only by what actually moved, and a retry sends only the residual; and a fee collection or referral claim is at most what was kept. `noteLiability` uses checked arithmetic, so an underflow reverts, and the encrypted sums cannot wrap because the wrapper caps its supply at uint64. # Confidential architecture Source: https://docs.fluton.io/confidential-architecture Why Fluton treats privacy as an execution property rather than a feature, how encryption and proofs divide the work, and what that looks like in the pool that is live today. Public blockchains are transparent by default. Every balance, every transfer and every interaction with a contract is visible to anyone, forever. For a payment that is a leak; for a trading or treasury strategy it is a liability, because what you are about to do can be read, copied or front-run before it settles. Fluton's answer is to make the execution itself confidential: the action still happens on a public chain, but its amounts, its participants and the state it touches stay hidden from everyone who is not party to it. This page explains the architecture behind that goal, in the form it has today. The pool that implements it is documented in detail from [Notes and proofs](/concepts/notes-and-proofs) onwards. ## FHE and zero-knowledge proofs Confidential execution needs two different tools, because two different things have to be hidden. **Fully homomorphic encryption (FHE)** lets a contract compute on encrypted values without ever decrypting them. A balance, a transfer amount or a reserve can live on-chain as a ciphertext; the contract adds, compares and moves those ciphertexts, and only an authorised party ever sees a plaintext, and only for the result it is entitled to. Fluton uses [Fhenix](https://cofhe-docs.fhenix.zone/) **CoFHE** for this: a coprocessor network that performs the encrypted arithmetic and signs decryption results, so a contract can act on an encrypted comparison it never saw in the clear. In Fluton's pool, every token the pool holds is kept in an FHERC20 wrapper, an encrypted ERC-20 whose balances are ciphertexts; the pool's reserves, its payouts and its liabilities are encrypted state ([TOKEN and eTOKEN](/concepts/token-formats)). **Zero-knowledge proofs** solve the other problem: proving that an action is valid without revealing which assets it uses. A proof can show that you own some value inside the system, that you are spending it exactly once, and that the amounts balance, while saying nothing about which deposit was yours or how much you hold. Fluton's Pool uses Groth16 proofs over a note model for this: value is held as private notes, and every state change is one join-split proof that consumes notes and creates new ones. Encryption hides values that a contract must still compute with. Proofs hide the link between an action and the history behind it. Fluton's architecture puts the two together, so that the chain holds encrypted reserves it can account for, while the ownership and movement of value inside those reserves is proven rather than shown. ## The execution model An action in Fluton moves through four stages, and privacy is enforced at each of them rather than bolted onto the result. **1. Entry** Value enters a shared, encrypted pool. The deposit is the one public act: it names the depositor, the token and the amount, and it is screened by a policy check before the pool accepts it ([Deposit screening](/concepts/deposit-screening)). From that moment on, the value is a private note in a shared anonymity set, and the pool's reserve for that token is an encrypted balance. **2. Private state** Inside the pool, nothing is public. A note is a commitment on a Merkle tree; its amount, owner and token are hidden. Every listed token shares one tree and one anonymity set, so a note of one token is indistinguishable from a note of another until it leaves ([Many tokens, one pool](/concepts/multi-token)). **3. Confidential execution** An action is a zero-knowledge proof that consumes notes and creates notes. A payment to another user is a new note addressed to their shielded key, delivered as a ciphertext only they can open; the chain records neither the amount nor the recipient nor the token ([Private transfers](/concepts/private-transfers)). A relayer can submit the proof and pay the gas, taking its fee as another private note, so the acting wallet never appears on-chain either ([Fees and referrals](/concepts/fees)). **4. Settlement** When value leaves, only the net result is public: an amount of a token paid to an address, with no link to the deposit that funded it. The payout itself is an encrypted transfer from the pool's reserve, settled through the FHE coprocessor and verified before it is treated as final. The result is privacy over the whole lifecycle of an action, not only over a transfer. A reader of the chain sees that value entered the pool and that value left it. The connection between the two, everything that happened in between, and the balances that remain are not on the chain in any readable form. ### Confidential execution is not mixing A mixer hides one transfer by pooling it with others of the same size. Fluton's architecture is built for arbitrary use, not for one transfer shape: | | A fixed-denomination mixer | Fluton Pool | | - | - | - | | Amounts | Fixed denominations | Any amount, with change | | Assets | One per pool | Many tokens in one anonymity set | | Inside the pool | Nothing happens | Private payments between users | | Reserves | Public balance | Encrypted FHERC20 balances | | Exit | Withdraw to a wallet | Withdraw, or pay out through a relayer so the recipient needs no gas | | Entry policy | None | Every deposit screened | Because value is held as notes and the reserves are encrypted, new confidential actions can be added as new kinds of proof over the same state rather than as new pools. ## Application-level privacy Fluton does not ask users to move to a private chain. The pool is a set of contracts, the encrypted arithmetic runs on Fhenix CoFHE, and the proofs are generated in the user's own browser; the wallet, the SDK and the relayer are ordinary applications talking to a public network. Privacy is a property of how the application executes, enforced by cryptography at every stage, rather than a property of which chain it runs on. That has three consequences that run through the rest of these docs: * **What is public is explicit.** The design does not promise that nothing is visible; it states exactly what is, and to whom. [What stays public](/concepts/privacy-model) is that list. * **Keys are the user's.** A shielded wallet is derived from one signature of the user's own wallet, and a read-only view key can be handed to an auditor without handing over the ability to spend ([Keys and view keys](/concepts/keys-and-view-keys)). * **Trust is named.** The coprocessor network, the screening provider, the relayer and the pool's upgrade key each have a defined role and a defined limit, and the limits are documented rather than hidden ([What stays public](/concepts/privacy-model)). To use the pool, open the wallet at [app.fluton.io](https://app.fluton.io) and read [Using the wallet](/wallet/using-the-wallet). To build on it, start with the [SDK overview](/sdk/overview). # Introduction Source: https://docs.fluton.io/index Say hello to on-chain privacy > [!NOTE] > > Welcome to the earliest version of Fluton Docs! Fluton is a universal confidential execution layer for blockchains. It enables applications, agents, and users to execute private actions across chains including swaps, bridging, payments, and yield without migrating to a new blockchain and without exposing balances, strategies, or intent. Privacy in Fluton is default, enforced at the execution layer, and designed for composability across existing ecosystems. In a few words, Fluton is: * an application-level privacy execution layer * deployed across existing blockchains * built for cross-chain confidential execution * compatible with users, dApps, and autonomous agents Fluton abstracts privacy away from individual protocols and chains and instead treats it as a shared execution primitive. ## Where to start > [card] [Keep reading](/confidential-architecture) > > Next up: Confidential Architecture > [card] [Understand the protocol](/concepts/notes-and-proofs) > > Notes, join-split proofs, private transfers, TOKEN and eTOKEN, fees, screening and what stays > public. > [card] [Integrate with the SDK](/sdk/overview) > > Derive keys, scan for notes, and build deposits, withdrawals and transfers from Node or a > browser. > [card] [Reference](/reference/contracts) > > Contracts, circuits and the addresses of the Sepolia deployment. > [card] [Check out our blog](https://fluton.io/blog) > > Read our blog posts to learn more about Fluton. > [card] [Check out our X](https://x.com/FlutonIO) > > See our social media posts for the news. # Running a relayer Source: https://docs.fluton.io/operators/relayer Run your own relayer from the Docker image: its HTTP endpoints, how it quotes and caps fees against gas prices, how it prices tokens, the keeper it runs, its configuration, and how to collect its fee notes. A relayer is a small HTTP service holding a funded key, and the reason a fresh wallet can receive from the pool without ever paying gas. Users prove in their own browser and send only the finished transaction; the relayer submits it to the pool and pays the gas. It is never paid in public: its fee is output slot 2 of the relayed transaction, a note owned by the relayer's own shielded address, whose keys derive from `RELAYER_PRIVATE_KEY` exactly as a web wallet's derive from the user's. Because the proof binds every output, a relayer can only refuse to submit; it cannot redirect a payout or change its fee. See [Fees and referrals](/concepts/fees) for why fee notes work this way. Fluton runs the relayer the hosted wallet uses. You can run your own from the same Docker image; clients reach it through the SDK's relayer client ([Deposits, withdrawals and transfers](/sdk/transactions)). > [!WARNING] > > The public Docker image, and the proving artifacts that fee collection needs, are not published > yet. They will be. Until then the relayer behind the hosted wallet is the one in service, and this > page is the reference for the image when it ships. > [!WARNING] > > Use a separate, small-balance key for the relayer. ## Endpoints | Method and path | Answers | | - | - | | `GET /status` | Who the relayer is and which assets it serves. | | `GET /fees` | The current fee for every served asset and job kind. | | `POST /relay` | Submits one finished transaction. | | `GET /relay/:nullifier` | What became of the submission that spent that nullifier. | Every response is JSON, CORS is open by default (`RELAYER_CORS_ORIGIN`), and `OPTIONS` ends with 204. Logs name transaction hashes only: for a hidden transfer the relayer is the one outside party that knows the asset and the fee, and it does not write them down. `GET /status` is what a wallet reads before it offers to relay: **address** `address` The EOA that signs and pays gas. **noteAddress** `string` The shielded address (`pp-addr:…`) that fee notes must be paid to. **chainId** `number` The chain this relayer serves. **pool** `address` The pool this relayer serves. **minFees** `object` Asset id to fixed minimum fee, in that asset's note units, as decimal strings. Only assets with a non-zero minimum appear, and only those are relayed. `GET /fees` quotes every served asset at once, so asking reveals nothing about the spend. It returns `at` (the time of the quote), `gasPrice` (what the relayer would bid now) and `fees`, keyed by asset id and then by job kind, `transfer` or `withdraw`: **fee** `string` The job's gas times the price the relayer would bid now, plus the margin, in the asset's note units. This is what the web app pays. **min** `string` The job's gas times the lowest price that still lands in the next block: the least the relayer accepts right now. `POST /relay` takes the payload the SDK produces, `proof` and `extData`, and answers `{ "hash": "0x…" }`. `GET /relay/:nullifier` takes one of the transaction's input nullifiers and answers a `status` of `unknown`, `pending`, `mined` or `failed`, with the `hash` of the transaction it last broadcast. Submissions are held in memory, so a restart forgets them and the chain stays the final word. ### What it refuses Cheap checks run first, and each refusal is a 400 with a reason: * a payload whose shape is wrong: it relays only transactions with 2 nullifiers, 3 commitments and 3 ciphertexts of exactly 168 bytes. The 16-input circuit is valid on-chain but not relayed, because it costs about 35% more gas than the minimum fees are set for; * deposits, which would pull tokens from the relayer, and deposit finalizations, which only the depositor may send; * a referrer on anything but a deposit, since only a deposit may name one; * a payload whose domain fields name another chain, pool or format, or that names an asset without moving value, or moves value without naming one; * a slot-2 output that is not a fee note to this relayer: the ciphertext must decrypt with its key to a canonical opening that hashes to that slot's commitment under its spend public key; * an asset it does not serve, a fee below that asset's fixed minimum, or a withdrawal whose named asset is not the fee note's; * a fee that no longer pays for the gas, and, while the ETH price is unavailable, anything paid in a USD-priced token. A different payload that spends notes already in flight gets 409; the same payload twice returns the first hash, so a retry never broadcasts twice. A body over 256 KiB gets 413. ## Fee quoting A relayed job costs the relayer gas: roughly 1.3M for a private transfer and 2.4 to 3M for a withdrawal, plus the keeper's follow-ups (confirming the payout, 56k, and for a TOKEN withdrawal the claim, 110k). Gas per kind starts at `RELAYER_GAS`, which defaults to `transfer=1500000,withdraw=3500000`, measured with headroom, and rises on its own when a relay's estimate is higher: the service remembers the gas limits of recent attempts and quotes from the largest. The follow-up budget is 200,000 gas for a withdrawal and nothing for a transfer. The `fee` in a quote includes the margin, `RELAYER_FEE_MARGIN_BPS`, which defaults to 2000 (20%). The margin is the relayer's profit and the room gas prices have to rise between a quote and the relay. Both `fee` and `min` are at least the asset's fixed minimum fee, and a quote is reused for a few seconds. When a transaction arrives, the relayer values its fee note in ETH and divides by the transaction's estimated gas (the estimate plus 10%, which also simulates the call) plus the follow-ups. That is the **cap**: the most it may ever pay per gas for this job. It never bids above the cap, neither at the first broadcast nor when replacing a stuck transaction. If the cap is below the price that still lands in the next block, nothing is signed at all: the answer is a 400 reading `relayer fee too low for current gas prices`, with the least acceptable fee in note units, so the user asks `GET /fees` again and proves afresh. So congestion can delay or refuse a job, but a relayed transaction never costs more than its fee is worth. ## Token prices Each asset is valued in one of two ways. * A **fixed ETH price** per whole token (`ethPrice` in the deployment, or `RELAYER_ETH_PRICES`) needs nothing else. WETH is 1. * A **USD price** per whole token (`usdPrice`, or `RELAYER_USD_PRICES`) is converted at the live ETH/USD price, which the relayer reads from a Chainlink `AggregatorV3` feed through its own RPC: no API key, and every answer carries its update time. `RELAYER_ETH_USD_FEED` names the feed; by default the relayer uses Chainlink's own ETH/USD feed on Ethereum mainnet and on Sepolia. A reading is reused for a minute before the feed is read again. An answer older than `RELAYER_PRICE_MAX_AGE_S` (default 7200 seconds, twice the feed's one-hour heartbeat, measured in chain time against the latest block's timestamp), or zero, or negative, is never used, and the relayer never falls back to an older reading instead. While the price is unavailable, USD-priced assets are left out of `GET /fees` and refused at `POST /relay` before anything is signed, and fixed-price assets carry on as normal. A failing RPC, as opposed to a stale feed, keeps the last reading only while its age is still within the maximum. Each outage and each recovery is logged once. An asset with neither price is relayed at its fixed minimum fee, with no cap, whatever gas costs; the service warns about it at startup. Naming one asset in both `RELAYER_ETH_PRICES` and `RELAYER_USD_PRICES` is a configuration error and the service refuses to start; in the deployment file, an `ethPrice` simply wins over a `usdPrice`. ## Sending and re-sending Every send goes through one serial queue (one nonce at a time) shared with the keeper, and is simulated against the latest state right before it is signed, so a job made stale by someone else is dropped instead of sent. Each broadcast is then watched until its nonce is used, and the submission's status always ends at `mined` or `failed`, never pending after a drop: 1. A transaction still unmined three minutes after its last broadcast was outbid, or dropped by the node, which would also hold back every later nonce. It is re-sent at the same nonce with fees 25% higher, up to three times, as long as it still simulates. A capped job bids the cap itself while that still replaces the stuck transaction. 2. Then, or at once if the call would now revert or a higher bid would exceed the cap, the relayer cancels it: a 0 ETH transfer to itself at that nonce, 21,000 gas, the only cost the fee does not cover. The submission is `failed`, the user's notes were not spent, and the same payload may be sent again. 3. A nonce taken by a transaction this relayer did not send also ends as `failed`, after a few polls confirm it. A wallet waiting for a receipt follows a re-send to its receipt. After a cancel it reports an unknown outcome and asks `GET /relay/:nullifier` and the chain before offering to send from the wallet, because re-sending from the wallet could land first and name the user as the sender. ## The keeper The relayer also runs the keeper (`RELAYER_KEEPER=1`, the default; `KEEPER_INTERVAL_MS` sets the tick period, default 5000 ms). It only ever calls permissionless functions: | Function | What it does | | - | - | | `verifyDeposit` | Authenticates a native eTOKEN deposit receipt with a signed decryption from CoFHE. | | `confirmAttempt` | Authenticates an obligation's current, in-flight payout attempt. | | `retryObligation` | Pays the residual after an authenticated failure, up to five attempts. | | `claimUnshielded` | Completes a public withdrawal's claim, by its exact claim id, on the wrapper of the obligation's own asset. | It never finalizes or cancels a deposit: those are the depositor's alone. It resolves each asset's wrapper from the pool's registry and caches it, so it follows assets listed after it started. Jobs are rebuilt from chain state. Events are scanned from a cursor persisted in a file (one per chain and pool, under a `.keeper` directory by default, or wherever `KEEPER_CURSOR_FILE` points), written to a temporary file and renamed so a crash never leaves a torn cursor, and every job re-reads its on-chain status immediately before acting. Correctness never depends on the keeper: the pool rejects stale confirmations, replays and concurrent retries, and the wrapper rejects a double claim, so a crashed, restarted or duplicated keeper can at worst waste gas on a reverting transaction. ## Run it from the Docker image The relayer ships as a Docker image, `fluton-relayer`. It contains the relayer and the SDK it needs, exposes port 8787 and binds `0.0.0.0`. It reads the pool's addresses from a deployment file: the same JSON the hosted wallet publishes as `deployment.json`, whose contents are listed under [deployments](/reference/deployments). Mount a directory holding that file, saved as `sepolia.json`, at `/app/deployments`, and give the container a key and an RPC: ```bash theme={null} docker run -p 8787:8787 -e RELAYER_PRIVATE_KEY=0x... -e RPC_URL=https://... \ -v $PWD/deployments:/app/deployments fluton-relayer ``` The service then answers on `:8787` and serves every asset it has a minimum fee for; with none it warns and runs the keeper only. Fund the key with a little Sepolia ETH, keep it small and separate from any key that holds funds, and host the container anywhere that runs Docker. Clients that want to use your relayer point the SDK's relayer client at its public URL. ## Configuration Everything is set through environment variables. `RELAYER_PRIVATE_KEY` is the only required one; the rest have the defaults below. | Variable | Default | Meaning | | - | - | - | | `RELAYER_PRIVATE_KEY` | required | The key that pays gas, and the key fee notes are paid to. Keep it small and separate. | | `RPC_URL` | the deployment file's `rpcUrl` | The RPC endpoint the relayer uses. | | `DEPLOYMENT_FILE` | `deployments/sepolia.json` when it exists | The deployment JSON, relative to the working directory (`/app` in the image). | | `RELAYER_MIN_FEES` | each asset's `relayerMinFee` from the deployment file | Fixed minimum fee per token in whole tokens, by symbol, for example `USDC=0.1,WETH=0.00005,USDT=0.1`. Only these tokens are relayed. Setting it replaces the deployment file's defaults for every asset. | | `RELAYER_ETH_PRICES` | each asset's `ethPrice` | A fixed price in ETH per whole token, by symbol, for example `WETH=1`. | | `RELAYER_USD_PRICES` | each asset's `usdPrice` | A USD price per whole token, by symbol, converted at the live ETH/USD price. A token may have one price or the other, never both. | | `RELAYER_ETH_USD_FEED` | Chainlink's own ETH/USD feed on Ethereum mainnet and Sepolia | The Chainlink `AggregatorV3` feed to read. Required if any token has a USD price on a chain with no default. | | `RELAYER_PRICE_MAX_AGE_S` | `7200` | The oldest feed answer the relayer will use, in seconds. Past it, USD-priced tokens are not relayed until the feed updates. | | `RELAYER_GAS` | `transfer=1500000,withdraw=3500000` | Gas per relayed job kind, raised automatically when an estimate exceeds it. | | `RELAYER_FEE_MARGIN_BPS` | `2000` | Profit over the gas cost in the quoted fee, and the room gas prices have to rise between a quote and the relay. | | `RELAYER_KEEPER` | `1` | The keeper: verify receipts, confirm and retry payouts, complete claims. `0` turns it off. | | `KEEPER_INTERVAL_MS` | `5000` | The keeper's tick period. | | `KEEPER_CURSOR_FILE` | `.keeper/-.json` | Where the keeper persists its event cursor. Mount a volume for it if you want the cursor to survive the container. | | `RELAYER_PORT` | `8787` | The HTTP port. | | `RELAYER_HOST` | `0.0.0.0` in the image | The bind address. | | `RELAYER_CORS_ORIGIN` | `*` | `Access-Control-Allow-Origin`. Set it to your web origin in production. | | `CIRCUIT_DIR` | none useful in the image | Fee withdrawals only: the directory holding the circuit `.wasm` and `.zkey` files. Mount one into the container and name it here. | A malformed `KEY=value` list, a key that names no listed token, a token with both prices, a non-positive price, or a non-integer margin or maximum age fails at startup. A token with a minimum fee but no price is relayed at that fixed minimum and the relayer warns about it. ## Collect the fee notes Income accumulates as fee notes, one per relayed transaction, which the relayer finds by scanning the chain with its own note key. The `fees` command runs in the same image, in place of the service, with the same environment and volumes: ```bash theme={null} docker run --rm -e RELAYER_PRIVATE_KEY=0x... -e RPC_URL=https://... \ -v $PWD/deployments:/app/deployments fluton-relayer pnpm --filter relayer fees docker run --rm -e RELAYER_PRIVATE_KEY=0x... -e RPC_URL=https://... -e CIRCUIT_DIR=/app/circuits \ -v $PWD/deployments:/app/deployments -v $PWD/circuits:/app/circuits \ fluton-relayer pnpm --filter relayer fees withdraw USDC ``` The first form lists the fee-note balance per asset. `fees withdraw ` merges the notes and withdraws them to the relayer's address as eTOKEN (add `--public` for TOKEN). Stop the service first: both send from the same key, and the command refuses to run while a relayer answers on the port with that key. Collecting uses the 16-input circuit. Each merge spends 16 fee notes into one with a private transfer to the relayer itself, which names no asset, and the final withdrawal spends up to 16 notes in full. Collecting N notes therefore takes one transaction for up to 16 notes and one more for every 15 beyond that: 100 notes take 7 transactions instead of 99. A 16-input merge costs 1.71M gas against 1.26M for a 2-input transfer, so collecting a fee note costs about 115k gas, a small part of the transaction that paid it. The withdrawal shows that asset's total income since the last one and pays the pool's withdrawal fee like any other withdrawal, so the relayer receives the total minus that fee. Notes below the asset's minimum fee are dust (anyone can send notes to a published shielded address) and are left alone. The proving artifacts are not in the image. `fees withdraw` needs the four circuit files of the deployed pool (`transaction.wasm`, `transaction_final.zkey`, `transaction16.wasm`, `transaction16_final.zkey`) in the directory `CIRCUIT_DIR` names; the 16-input proving key alone is about 61 MB. A key from another build produces proofs the deployed verifier rejects; `fees` simulates every transaction first, so that costs nothing. Without the 16-input artifacts it warns and can still withdraw at most two notes. # Circuits Source: https://docs.fluton.io/reference/circuits The Circom circuits behind Fluton: files, public inputs, the constraints that matter, the generated verifiers and the trusted setup. Fluton proves every state change with one Groth16 join-split proof. The circuits are written in Circom 2, with Poseidon and the helper templates coming from `circomlib`. Two instances of one template are compiled: a 2-input circuit for everyday transactions and a 16-input circuit for consolidating many notes at once. ## Files | File | Role | | - | - | | `joinSplit.circom` | The `Transaction(levels, nIns, nOuts)` template: all signals and all constraints, plus the `Keypair` and `NullifierKey` helpers | | `transaction.circom` | The 2-input instance, `Transaction(20, 2, 3)`: every deposit, transfer and withdrawal that spends at most two notes | | `transaction16.circom` | The 16-input instance, `Transaction(20, 16, 3)`: spends up to 16 notes of one asset in one proof, such as a relayer collecting its fee notes | | `merkleTree.circom` | `HashLeftRight` (Poseidon of a node's two children) and `DualMux`, which orders a pair by a path bit constrained boolean | | `merkleProof.circom` | `MerkleProof(levels)`: computes the root implied by a leaf, its packed index and its siblings, without asserting that it equals anything | Both instances have 20 levels and exactly 3 outputs, so every accepted transaction appends three leaves whatever its size. `merkleProof.circom` deliberately only computes a root and leaves the comparison to the caller; that is what lets the transaction circuit skip the membership check for dummy inputs. A note is `(amount, publicKey, blinding, asset)` and the circuit derives the same four Poseidon hashes the SDK does: ```text theme={null} publicKey = Poseidon(privateKey) commitment = Poseidon(amount, publicKey, blinding, asset) nullifierKey = Poseidon(privateKey, nullifierKeyDomain()) nullifier = Poseidon(commitment, pathIndices, nullifierKey) ``` `nullifierKeyDomain()` is the ASCII bytes of `fluton-nullifier-key` read as an integer, and it must match the SDK's own domain constant. Binding the packed leaf index into the nullifier gives each leaf exactly one nullifier. The nullifier depends on the private key only through `nullifierKey`, a one-way derivation, which is what makes a read-only view key possible. See [notes and proofs](/concepts/notes-and-proofs) and [keys and view keys](/concepts/keys-and-view-keys). ## Public inputs Circom orders public signals by declaration, so the order in `joinSplit.circom` is the order of `publicSignals[]` off-chain and of the verifier's `input[]` array on-chain: 1. `root` 2. `publicAmount` 3. `extDataHash` 4. `publicAsset` 5. `inputNullifier[nIns]` 6. `outputCommitment[nOuts]` That makes 9 public inputs for the 2-input circuit (4 plus 2 plus 3) and 23 for the 16-input one (4 plus 16 plus 3), matching the two verifier interfaces in the [contracts](/reference/contracts). The pool assembles the array in exactly this order and always takes `publicAsset` from `ExtData`, never from the caller. | Signal | What it carries | | - | - | | `root` | A tree root the pool still accepts. The circuit compares each real input's computed root against it | | `publicAmount` | The net amount crossing the pool boundary: positive is a deposit, negative is a withdrawal encoded as the field order minus the amount. The pool recomputes it from the amount in `extData` and requires equality ([contracts](/reference/contracts)) | | `extDataHash` | The field-reduced keccak of the pool's `ExtData`: recipient, amount, fee, the three ciphertexts and the domain fields | | `publicAsset` | The asset crossing the boundary, or 0 when nothing crosses | | `inputNullifier` | One nullifier per input slot, real or dummy | | `outputCommitment` | The three new leaves | The private inputs are the single `asset` of the transaction, and per slot the amounts, private keys, blindings, path indices and sibling hashes of the notes spent, plus the amounts, recipient public keys and blindings of the notes created. ### The constraints that matter * **Membership, skipped for dummies.** Each input's commitment is hashed, its Merkle root computed, and the result compared to `root` through `ForceEqualIfEnabled` with the input's own amount as the enable signal. An input of amount 0 therefore needs no real leaf, so unused slots carry freshly generated dummy notes. * **Nullifier correctness.** Each slot's recomputed nullifier must equal the public `inputNullifier` for that slot, and no two nullifiers in one proof may be equal. * **Output range check below 2^248.** Every output amount passes `Num2Bits(248)`. Inputs need no check, because every real input was once a range-checked output. With amounts under 2^248, even 16 of them sum to under 2^252, well below the field order, so a sum can never wrap. * **Value conservation.** `sumIns + publicAmount === sumOuts`, over the field. Because the public amount is bounded by the pool and every note amount is range-checked, this holds over the integers too. * **The asset constraint.** One private `asset` signal enters all input and output commitments, so a transaction can only spend and create notes of a single asset. On top of that, `(asset - publicAsset) * publicAmount === 0`: whenever value crosses the boundary the asset is pinned to the public one, and when nothing crosses the asset stays private while `publicAsset` remains bound by the proof. Together with the range check, a note of an asset that holds no value is provably worth zero. [Many tokens, one pool](/concepts/multi-token) works through the argument. * **Ext-data binding.** `extDataHash` is squared into a dummy signal, which is enough to make the proof depend on it. Tamper with any public field on-chain and the hash changes, so the proof no longer verifies and a mempool observer cannot re-target it. The circuit does not know about output slots. Slot 0 and 1 being the user's payment and change and slot 2 being the relayer's fee note is a convention of the SDK and the relayer, which is why a fee note and a dummy look alike on-chain. See [Fees and referrals](/concepts/fees). ## Verifiers Each circuit has one on-chain verifier, exported from its proving key by snarkjs: `transaction` into `Verifier.sol` as `Groth16Verifier`, and `transaction16` into `Verifier16.sol` as `Groth16Verifier16`. The pool holds both and picks one by the number of nullifiers in the proof ([contracts](/reference/contracts)). The build compiles both circuits with Circom, runs the Groth16 setup against a 2^17 powers-of-tau file (131072 constraints, enough for the 16-input circuit at around 96k and the 2-input one at around 13.4k), and exports the verification key and the Solidity verifier of each. Because the verifiers are exported from the proving keys, proofs made with a key from another build are rejected by the deployed verifier; the relayer's fee collection therefore needs the artifacts of the deployed build ([Running a relayer](/operators/relayer)). ## Trusted setup Each circuit's proving and verifying keys come from a Groth16 trusted setup for that circuit. The setup bears on proof **unforgeability** only: the hiding properties of the commitments, the ciphertexts and the anonymity set do not depend on it. # Contracts Source: https://docs.fluton.io/reference/contracts Reference for PrivacyPool and the contracts around it: roles, functions, parameters, caps and custom errors. The pool is one Solidity contract, `PrivacyPool`, plus the tree it inherits, two generated Groth16 verifiers, one confidential wrapper per listed token, and the Predicate registry that screens deposits. Everything below comes from the Solidity sources and from the ABIs the SDK ships. The pool is deployed behind a proxy, so the address every client talks to is a `TransparentUpgradeableProxy`. See [deployments](/reference/deployments) for the addresses and [what stays public](/concepts/privacy-model) for what upgradeability means. ## PrivacyPool `PrivacyPool.sol` is a multi-asset shielded pool: one Merkle tree and one nullifier set for every asset. Each asset is a plain ERC-20 (TOKEN) paired with its `ConfidentialWrapper` (eTOKEN), which holds the reserve. Notes are denominated in eTOKEN units. ```solidity theme={null} contract PrivacyPool is MerkleTreeWithHistory, ReentrancyGuardTransient, Ownable2StepUpgradeable, BasicPredicateClient ``` Value enters only through `deposit` (TOKEN) and `requestDeposit` (eTOKEN), and each takes a Predicate attestation of the depositor. Every outbound movement of eTOKEN is an obligation settled by an authenticated decryption, because an FHERC20 transfer moves 0 instead of reverting when the balance is short. Read [TOKEN and eTOKEN](/concepts/token-formats) for why. ### Roles | Role | Who | What it can do | | - | - | - | | Owner | `Ownable2StepUpgradeable` (OpenZeppelin's `Ownable2Step`, two-step transfer); the address `initialize` is given | List assets, change the withdrawal fee and referral share, name the bonus signer, revoke bonuses, re-point the Predicate registry and policy, collect fees | | Upgrader | The owner of the `ProxyAdmin` the proxy deploys | Replace the pool's code with `upgradeAndCall`, and with it every rule on this page | | `bonusSigner` | An address the owner names with `setBonusSigner` | Sign the EIP-712 attestations that `setReferralBonus` accepts | The owner and the upgrader are separate roles: transferring one does not transfer the other. Renouncing ownership freezes the asset list and the fee rates, but only until an upgrade. ### Initialization `initialize` runs once, from the proxy's constructor, so nobody can initialize the pool before the deployer. The implementation's constructor calls `_disableInitializers()`, so it stays ownerless and inert. ```solidity theme={null} function initialize( IVerifier _verifier, IVerifier16 _verifier16, IHasher _hasher, uint32 _levels, bytes32 _wrapperCodehash, uint16 _withdrawFeeBps, uint16 _referralShareBps, address _predicateRegistry, string calldata _predicatePolicyID, address _owner ) external initializer; ``` Both Predicate arguments are required: a zero registry or an empty policy id reverts with `InvalidPredicateConfig`. The policy is registered with the registry for the proxy's own address. ### ExtData Every public side effect of a transaction lives in one struct, which the circuit sees only as a hash. The pool recomputes `keccak256(abi.encode(extData)) % FIELD_SIZE` and requires it to equal the proof's `extDataHash`. **recipient** `address` Where a withdrawal pays out. Must be zero unless `extAmount` is negative. **extAmount** `int256` Note units entering (positive) or leaving (negative) the pool. Zero is a private transfer. **withdrawFee** `uint64` `withdrawFeeOf(-extAmount)` at the rate in force. Must be zero unless `extAmount` is negative. **encryptedOutputs** `bytes[3]` One ciphertext per output commitment, each exactly `CIPHERTEXT_LENGTH` (168) bytes. **chainId** `uint256` Must equal `block.chainid`. **pool** `address` Must equal the pool's own address. **asset** `uint32` The asset crossing the boundary, and the circuit's `publicAsset`. Must be 0 when `extAmount` is 0. **format** `uint8` `FORMAT_CONFIDENTIAL` (0) or `FORMAT_PUBLIC` (1). **depositId** `bytes32` Set only by `finalizeDeposit`; `transact` and `deposit` reject a non-zero value. **referrer** `address` A deposit's referrer. Must be zero unless `extAmount` is positive, and may not be the pool. ### User functions ```solidity theme={null} function transact(TransactProof calldata _proof, ExtData calldata _extData) external; function deposit( TransactProof calldata _proof, ExtData calldata _extData, Attestation calldata _attestation ) external; function requestDeposit(uint32 _asset, uint64 _amount, Attestation calldata _attestation) external returns (bytes32 depositId); function verifyDeposit(bytes32 _depositId, bool _success, bytes calldata _signature) external; function finalizeDeposit(TransactProof calldata _proof, ExtData calldata _extData) external; function cancelDeposit(bytes32 _depositId) external returns (bytes32 obligationId); ``` | Function | Who may call it | What it does | | - | - | - | | `transact` | Anyone | A private transfer (`extAmount == 0`) or a withdrawal (`extAmount < 0`). Reverts with `DepositRequiresAttestation` on any `extAmount > 0`, so relayed jobs never carry an attestation | | `deposit` | The depositor (`msg.sender`) | One-step TOKEN deposit. The registry verifies and spends the attestation before the proof is checked or anything is pulled | | `requestDeposit` | The depositor | Step 1 of an eTOKEN deposit: pulls eTOKEN (the pool must be an operator of that wrapper) and records a depositor-owned receipt, `Pending` | | `verifyDeposit` | Anyone | Step 2: hands in CoFHE's signed decryption of the receipt's `received == amount` bit, moving it `Pending → Verified` or `Pending → Failed`. A no-op once the receipt has moved past `Pending` | | `finalizeDeposit` | The depositor only | Step 3: proves and creates the notes for a `Verified` receipt. The proof binds `depositId` | | `cancelDeposit` | The depositor only | Abandons an open receipt and refunds what actually arrived, through an obligation | Finalize and cancel are mutually exclusive. A failed proof or an expired root leaves the receipt `Verified`, so you re-prove without the tokens being pulled again. `DepositStatus` runs `None, Pending, Verified, Failed, Finalized, Cancelled`. The proof struct picks its verifier by the number of nullifiers: `N_INS` (2) uses `verifier`, `N_INS_LARGE` (16) uses `verifier16`, anything else reverts with `InvalidInputCount`. ```solidity theme={null} struct TransactProof { uint[2] a; uint[2][2] b; uint[2] c; bytes32 root; bytes32[] inputNullifiers; // N_INS or N_INS_LARGE: picks the circuit bytes32[3] outputCommitments; uint256 publicAmount; bytes32 extDataHash; } ``` ### Obligation functions ```solidity theme={null} function confirmAttempt(bytes32 _attemptId, bool _success, bytes calldata _signature) external; function retryObligation(bytes32 _obligationId) external returns (bytes32 attemptId); ``` Both are permissionless, and the relayer's keeper calls them for you. `confirmAttempt` accepts a signed decryption for the obligation's current, in-flight attempt only: anything stale or replayed reverts with `StaleConfirmation`. A success settles the obligation; a failure moves it to `RetryAllowed`, which is the only status `retryObligation` accepts. A retry pays only the encrypted residual, through a new attempt, and flips the status to in-flight before any external call, so concurrent retries revert. `ObligationKind` is `Withdraw`, `Refund` or `Burn` (an `unshield` into a TOKEN claim); `ObligationStatus` is `None`, `InFlight`, `RetryAllowed` or `Settled`; `AttemptStatus` is `None`, `InFlight`, `Succeeded` or `Failed`. A `Burn` attempt records the wrapper claim id it created, read from `ConfidentialWrapper.lastClaimId()` in the same transaction, and reverts with `MissingClaimId` if that is zero. ### Fee and referral functions ```solidity theme={null} function collectFees(uint32 _asset, uint64 _amount, address _to, uint8 _format) external returns (bytes32 obligationId); // onlyOwner function claimReferral(uint32 _asset, uint64 _amount, address _to, uint8 _format) external returns (bytes32 obligationId); function setReferralBonus( address _referrer, uint16 _fixedBps, uint16 _expiringBps, uint64 _expiresAt, uint64 _issuedAt, bytes calldata _signature ) external; function revokeReferralBonus(address _referrer) external; // onlyOwner ``` `collectFees` pays out kept withdrawal fees, except the part reserved for referrers: the owner may take only `protocolFees[asset]` above `referralLiability[asset]`. `claimReferral` pays the caller's own `referralCredit[msg.sender][asset]` out of the same kept fees, which is why it reverts with `InsufficientFees` until withdrawals have kept enough of that token, and with `InsufficientCredit` when you ask for more than you earned. Both are paid through an obligation, as eTOKEN (`FORMAT_CONFIDENTIAL`) or TOKEN (`FORMAT_PUBLIC`). `setReferralBonus` is permissionless: anyone may submit a referrer's attestation. The pool checks the EIP-712 signature against `bonusSigner`, refuses a total above `MAX_REFERRAL_BONUS_BPS`, and accepts only an `_issuedAt` strictly later than the stored one (`StaleBonus` otherwise), so a replay can never roll a bonus back. `revokeReferralBonus` clears a bonus and stamps it with the current time, which also makes every attestation issued so far stale. The reasoning behind the rates is on [Fees and referrals](/concepts/fees). Four pure or view helpers give the arithmetic: ```solidity theme={null} function withdrawFeeOf(uint256 _amount) public view returns (uint256); function referralShareOf(address _referrer) public view returns (uint256); function referralRewardOf(uint256 _amount, address _referrer) public view returns (uint256); function calculatePublicAmount(int256 _extAmount) public pure returns (uint256); ``` `withdrawFeeOf` rounds up: `(amount * withdrawFeeBps + FEE_DENOMINATOR - 1) / FEE_DENOMINATOR`. `referralShareOf` adds the stored bonus to `referralShareBps`, counts the expiring part only while `block.timestamp < expiresAt`, and caps the result at `MAX_REFERRAL_SHARE_BPS`. `referralRewardOf` rounds down. ## Owner functions ```solidity theme={null} function addAsset(IConfidentialWrapper _wrapper) external returns (uint32 id); function setWithdrawFeeBps(uint16 _bps) external; function setReferralShareBps(uint16 _bps) external; function setBonusSigner(address _signer) external; function setRegistry(address _registry) external; function setPolicyID(string memory _policyID) external; ``` `addAsset` appends one asset and is the only way to list a token. It accepts a wrapper only if its runtime code hash is the pinned `wrapperCodehash`, its underlying is a separate contract that is not itself a wrapper, neither address is already listed in either role, and its rate is non-zero. Listing is append-only up to `MAX_ASSETS`: there is no delist, pause or edit. `setWithdrawFeeBps` and `setReferralShareBps` change the rates for transactions that land after them; credits already given never change. `setBonusSigner` with the zero address disables `setReferralBonus` while leaving bonuses already set in place. `setRegistry` and `setPolicyID` move the pool to another Predicate registry or policy. Screening cannot be switched off: neither may be empty, and with no registry code every deposit reverts. [Deposit screening](/concepts/deposit-screening) explains what the registry checks. ## Views | View | Returns | | - | - | | `isSpent(bytes32 nullifier)` | Whether a nullifier has been used | | `assets(uint32 id)` | `wrapper`, `underlying`, `rate` | | `assetCount()`, `assetOfWrapper(address)`, `assetOfUnderlying(address)` | The asset registry | | `deposits(bytes32)`, `obligations(bytes32)`, `attempts(bytes32)` | Receipt, obligation and attempt records | | `noteLiability(uint32)`, `protocolFees(uint32)`, `referralLiability(uint32)` | Plaintext liabilities per asset | | `depositLiability(uint32)`, `payoutLiability(uint32)` | Encrypted liabilities per asset, as handles | | `withdrawFeeBps()`, `referralShareBps()`, `bonusSigner()`, `referralBonus(address)`, `referralCredit(address,uint32)` | Fee and referral state | | `getRegistry()`, `getPolicyID()` | The Predicate registry and policy in force | | `getLastRoot()`, `isKnownRoot(bytes32)`, `nextIndex()`, `nullifierCount()`, `depositNonce()`, `obligationNonce()`, `levels()` | Tree and counter state | `checkBacking(uint32 asset)` is the one check that is a transaction rather than a view: it sums that asset's four liabilities under encryption (in 128 bits), compares them with the pool's encrypted reserve, makes the resulting `ebool` publicly decryptable and emits `BackingChecked`. It exists for monitors; see the [backing invariant](/concepts/token-formats#backing-invariant). ## Parameters and caps | Constant | Value | Meaning | | - | - | - | | `FORMAT_CONFIDENTIAL` | 0 | eTOKEN format | | `FORMAT_PUBLIC` | 1 | TOKEN format | | `MAX_UNITS` | `type(uint64).max` | Largest `abs(extAmount)` in note units | | `MAX_ASSETS` | 32 | Most assets the pool will ever list | | `CIPHERTEXT_LENGTH` | 168 | Exact length of every output ciphertext | | `N_OUTS` | 3 | Output commitments per transaction, always | | `N_INS` | 2 | Inputs of the small circuit | | `N_INS_LARGE` | 16 | Inputs of the large circuit | | `FEE_DENOMINATOR` | 10000 | Basis-point denominator | | `MAX_WITHDRAW_FEE_BPS` | 100 | Hard cap on the withdrawal fee: 1% | | `MAX_REFERRAL_SHARE_BPS` | 10000 | A referrer's share can reach the whole fee, never more | | `MAX_REFERRAL_BONUS_BPS` | 2500 | Cap on one referrer's bonus above the base share | | `ROOT_HISTORY_SIZE` | 30 | Recent roots a proof may use (from `MerkleTreeWithHistory`) | | `FIELD_SIZE` | `21888242871839275222246405745257275088548364400416034343698204186575808495617` | The prime field the circuits work in; an output commitment or tree node at or above it is rejected | | `ZERO_VALUE` | `keccak256("fluton")` reduced modulo `FIELD_SIZE` | The empty-leaf value the tree is built from | The mutable parameters are `withdrawFeeBps` (0 to `MAX_WITHDRAW_FEE_BPS`), `referralShareBps` (0 to `MAX_REFERRAL_SHARE_BPS`), `bonusSigner`, and the Predicate registry and policy. `initialize` sets both rates at deployment; the live values are the `withdrawFeeBps()` and `referralShareBps()` views. ## Errors Every revert the pool raises is a custom error, and the SDK's `poolAbi` lists them so a failed call decodes. Six are absent from that ABI: `initialize`'s own `TreeTooSmall` and `InvalidWrapperCodehash`, and the tree's `InvalidLevels`, `NodeOutOfField`, `NoLeaves` and `TreeIsFull`. It carries the errors the pool's bases raise instead: `OwnableUnauthorizedAccount`, `ReentrancyGuardReentrantCall`, `ECDSAInvalidSignature`, `ECDSAInvalidSignatureLength` and `ECDSAInvalidSignatureS`. ### Routing and `ExtData` | Error | When it fires | | - | - | | `DepositRequiresAttestation` | `transact` was called with `extAmount > 0` | | `NotADeposit` | `deposit` was called with `extAmount <= 0` | | `NativeDepositRequiresRequest` | `extAmount > 0` with a format other than `FORMAT_PUBLIC`: an eTOKEN deposit must go through `requestDeposit` | | `WrongChain`, `WrongPool` | `ExtData.chainId` or `ExtData.pool` names another chain or pool | | `InvalidFormat` | `format` is neither 0 nor 1, in `ExtData` or in a `collectFees` or `claimReferral` call | | `AmountOutOfRange` | `abs(extAmount)` exceeds `MAX_UNITS` | | `NonCanonicalExtData` | A field the route does not use is non-zero: `recipient` or `withdrawFee` on a deposit or transfer, `referrer` on a withdrawal or transfer, or a transfer that is not `FORMAT_CONFIDENTIAL` | | `HiddenTransactionNamesAsset` | `extAmount == 0` but `ExtData.asset` is not 0 | | `InvalidCiphertext` | An entry of `encryptedOutputs` is not 168 bytes | | `DepositIdNotAllowed` | `transact` or `deposit` carried a non-zero `depositId` | | `InvalidRecipient` | A withdrawal, fee collection or claim pays the zero address or the pool itself | | `UnknownAsset` | The asset id is 0 or above `assetCount` | ### Proof and tree | Error | When it fires | | - | - | | `InvalidInputCount` | `inputNullifiers` is neither 2 nor 16 long | | `UnknownRoot` | The proof's root is not among the last 30 | | `NullifierSpent` | One of the nullifiers was already spent | | `DuplicateNullifier` | Two nullifiers in one proof are equal | | `CommitmentOutOfField` | An output commitment is at or above `FIELD_SIZE` | | `IncorrectExtDataHash` | `extDataHash` does not match the `ExtData` supplied | | `InvalidPublicAmount` | `publicAmount` is not `calculatePublicAmount(extAmount)` | | `InvalidProof` | The chosen verifier rejected the proof | | `NoteLiabilityUnderflow` | A withdrawal would take more than the asset's unspent note value | | `InvalidLevels`, `TreeTooSmall`, `TreeIsFull`, `NoLeaves`, `NodeOutOfField` | Tree configuration or capacity problems: `TreeTooSmall` from `initialize`, the rest from `MerkleTreeWithHistory` | ### Deposits and obligations | Error | When it fires | | - | - | | `ZeroAmount` | `requestDeposit`, `collectFees` or `claimReferral` for 0 units | | `UnknownDeposit` | No receipt with that id | | `NotDepositor` | Someone other than the depositor called `finalizeDeposit` or `cancelDeposit` | | `DepositNotVerified` | `finalizeDeposit` on a receipt that is not `Verified` | | `DepositNotCancellable` | `cancelDeposit` on a `Finalized` or `Cancelled` receipt | | `DepositMismatch` | The finalizing `ExtData` disagrees with the receipt's amount, format or asset | | `InvalidDecryption` | `verifyDeposit` or `confirmAttempt` was given a result CoFHE did not sign for that handle | | `UnknownAttempt` | No attempt with that id | | `StaleConfirmation` | The attempt is not the obligation's current in-flight one | | `RetryNotAllowed` | `retryObligation` while the obligation is not `RetryAllowed` | | `MissingClaimId` | A `Burn` attempt whose wrapper reported claim id zero | | `UnderlyingShortfall` | A TOKEN pull or `shield` call did not move exactly the amount asked: a fee-on-transfer token | ### Fees, referrals and configuration | Error | When it fires | | - | - | | `WithdrawFeeMismatch` | `ExtData.withdrawFee` is not `withdrawFeeOf(-extAmount)` at the rate in force when the transaction lands. The notes stay unspent, so you re-prove at the new rate | | `ZeroPayout` | The fee would take the whole withdrawal, leaving the recipient nothing | | `WithdrawFeeTooHigh` | `setWithdrawFeeBps` or `initialize` above `MAX_WITHDRAW_FEE_BPS` | | `InsufficientFees` | `collectFees` or `claimReferral` for more than the kept fees available to that caller | | `InsufficientCredit` | `claimReferral` for more than the caller's credit | | `ReferralShareTooHigh` | `setReferralShareBps` or `initialize` above `MAX_REFERRAL_SHARE_BPS` | | `InvalidReferrer` | `ExtData.referrer` is the pool, or `setReferralBonus` named the zero address | | `BonusSignerUnset` | `setReferralBonus` while `bonusSigner` is zero | | `ReferralBonusTooHigh` | `fixedBps + expiringBps` exceeds `MAX_REFERRAL_BONUS_BPS` | | `StaleBonus` | The attestation's `issuedAt` is not later than the stored one | | `InvalidBonusSignature` | The recovered signer is not `bonusSigner` | | `AttestationRejected` | The Predicate registry refused the depositor's attestation | | `InvalidPredicateConfig` | A zero registry or an empty policy id | | `InvalidAsset`, `DuplicateAsset`, `WrongWrapperCode`, `TooManyAssets` | `addAsset` rejected the wrapper | | `InvalidWrapperCodehash` | `initialize` was given a zero or empty-account code hash | The registry's own `require` strings bubble up through `deposit` and `requestDeposit` unchanged, so an expired or replayed attestation reads as Predicate's message rather than a custom error. ## MerkleTreeWithHistory `MerkleTreeWithHistory.sol` is the append-only Poseidon tree the pool inherits. ```solidity theme={null} function hashLeftRight(IHasher _hasher, bytes32 _left, bytes32 _right) public pure returns (bytes32); function isKnownRoot(bytes32 _root) public view returns (bool); function getLastRoot() public view returns (bytes32); ``` `_insertLeaves` appends a batch and records one root per batch, which is why one transaction's three leaves produce exactly one root and a proof may use any of the last `ROOT_HISTORY_SIZE` roots. `ZERO_VALUE` is `keccak256("fluton")` reduced into the field. Reading a root of zero always returns false. More on the tree in [notes and proofs](/concepts/notes-and-proofs). ## Verifier and Verifier16 The pool keeps one snarkjs Groth16 verifier per circuit, in the `verifier` and `verifier16` variables `initialize` sets, and reaches them through two interfaces in `interfaces.sol` that differ only in the length of the public input array. The verifier contracts themselves are generated from the circuits: see [circuits](/reference/circuits). ```solidity theme={null} interface IVerifier { function verifyProof( uint[2] calldata a, uint[2][2] calldata b, uint[2] calldata c, uint[9] calldata input ) external view returns (bool); } interface IVerifier16 { function verifyProof( uint[2] calldata a, uint[2][2] calldata b, uint[2] calldata c, uint[23] calldata input ) external view returns (bool); } ``` The same file declares `IHasher`, a single `poseidon(bytes32[2])` function implemented by bytecode generated from circomlib so the on-chain hash matches the circuit. The input order is fixed by the circuit: see [circuits](/reference/circuits). ## ConfidentialWrapper `ConfidentialWrapper.sol` is the eTOKEN: an FHERC20 wrapper over one ERC-20, built on `fhenix-confidential-contracts`. It keeps `min(decimals, 6)` decimals and a `rate` of 10 to the power of `decimals - 6`, or 1. Name, symbol, underlying and rate live in storage, so every instance linked to the same `ERC20ConfidentialLib` has identical runtime code, which is what lets the pool pin a single `wrapperCodehash`. Its one deviation from the stock wrapper is `lastClaimId`: ```solidity theme={null} function lastClaimId() external view returns (bytes32); ``` The library keys claims by `keccak256(abi.encode(to, nonce, burnedHandle))`, the per-claimant nonce has no getter, and `getUserClaims(to)` is an unbounded list anyone can grow by unshielding dust to `to`. A caller that must track its exact claim reads `lastClaimId()` in the same transaction instead; it is transient storage, so it is meaningful only there. A claim lives in the wrapper that created it, which is why an attempt records only the id: its obligation's asset names the wrapper. `IConfidentialWrapper` is what the pool uses: `shield`, `unshield`, `confidentialTransfer`, `confidentialTransferFrom`, `confidentialBalanceOf`, `lastClaimId`, `rate` and `underlying`. Every returned amount is what actually moved. The claim itself is paid out by the wrapper: ```solidity theme={null} function claimUnshielded(bytes32 id, uint64 decryptedAmount, bytes decryptionProof) external; ``` Only what was actually burned becomes claimable, and the wrapper's `claimed` flag stops double payment. The keeper calls `claimUnshielded` by exact claim id on the obligation's own wrapper. Never display an FHERC20 `balanceOf`: it is an indicator value, not a balance. ## Predicate registry Predicate's registry is an upgradeable proxy owned by Predicate Labs, and the pool reaches it through `BasicPredicateClient`. The hash an attester signs covers the chain id, uuid, depositor, target, message value, encoded arguments, policy and expiration, and the registry puts the calling contract in the target's place, so a signature is good only from the pool it was issued for. The attester signs that hash itself, with no EIP-191 prefix, and must be registered. An expired attestation is refused, and a uuid is spent on first use. The registry's revert strings bubble up through `deposit` and `requestDeposit`, and the SDK recognises them. [Deposit screening](/concepts/deposit-screening) explains the flow. # Deployments Source: https://docs.fluton.io/reference/deployments Where Fluton Pool is deployed, with every contract and token address of the current Sepolia deployment. Fluton Pool runs on Ethereum Sepolia. The wallet publishes the deployment record as `deployment.json`: the addresses below together with `deployBlock` and `logChunk`, so a client scans events from the deployment block in RPC-sized pages instead of asking a public node for the whole chain. A relayer you run yourself reads the same file ([Running a relayer](/operators/relayer)). ## Sepolia Ethereum Sepolia, chain id `11155111`. Explorer: [sepolia.etherscan.io](https://sepolia.etherscan.io). | Field | Value | | - | - | | `network` | `sepolia` | | `chainId` | `11155111` | | `explorer` | `https://sepolia.etherscan.io` | | `levels` | `20`, the tree parameter the pool was deployed with; [notes and proofs](/concepts/notes-and-proofs) explains the tree | | `deployBlock` | `11929905`, the block the client scans events from | | `logChunk` | `5000`, the block range of one page of that scan | | `rpcUrl` | Not reproduced here. Point your own client or relayer at an RPC endpoint of your own | | `relayerUrl` | `https://demo-relayer.fluton.io` | | `indexerUrl` | `https://demo-indexer.fluton.io` | | `apiUrl` | `https://demo-api.fluton.io` | | `predicatePolicyId` | `x-managed-policy-165f87e9b64631999727736173c07619` | ### Contracts | Key | Address | What it is | | - | - | - | | `pool` | [`0x615FC7B9df2C8C80711f195986c0Ce1a62b469d5`](https://sepolia.etherscan.io/address/0x615FC7B9df2C8C80711f195986c0Ce1a62b469d5) | The address every client talks to: a `TransparentUpgradeableProxy` (OpenZeppelin 5.6), whose constructor called `initialize` in the same transaction | | `poolImplementation` | [`0xC7D9D772Feede616dDF6c0f1088e5475cd1d763E`](https://sepolia.etherscan.io/address/0xC7D9D772Feede616dDF6c0f1088e5475cd1d763E) | The `PrivacyPool` code the proxy runs. Its own constructor disables its initializers, so it stays ownerless and inert | | `proxyAdmin` | [`0x5C1700dBB42427506aBEd995A3B5A6892C7a0942`](https://sepolia.etherscan.io/address/0x5C1700dBB42427506aBEd995A3B5A6892C7a0942) | The `ProxyAdmin` the proxy deployed; its owner alone can call `upgradeAndCall(pool, newImplementation, data)` | | `verifier` | [`0x87812e694B3Da73087d4fb81d2d77d5Cb693bad0`](https://sepolia.etherscan.io/address/0x87812e694B3Da73087d4fb81d2d77d5Cb693bad0) | Verifier for the 2-input join-split; see [circuits](/reference/circuits) | | `verifier16` | [`0x1191fE9521d529513615787b1efEb7534eDE26B1`](https://sepolia.etherscan.io/address/0x1191fE9521d529513615787b1efEb7534eDE26B1) | Verifier for the 16-input join-split; see [circuits](/reference/circuits) | | `hasher` | [`0x83F34f527D880077aCde71A01f44a48De4eeC448`](https://sepolia.etherscan.io/address/0x83F34f527D880077aCde71A01f44a48De4eeC448) | The Poseidon hasher; [notes and proofs](/concepts/notes-and-proofs) covers what it hashes | | `confidentialLib` | [`0xc574f7e89f18B366B38A31c99dc75607F7b71911`](https://sepolia.etherscan.io/address/0xc574f7e89f18B366B38A31c99dc75607F7b71911) | The confidential-token library of this deployment; [TOKEN and eTOKEN](/concepts/token-formats) covers the eTOKEN wrappers | | `predicateRegistry` | [`0xe15a8Ca5BD8464283818088c1760d8f23B6a216E`](https://sepolia.etherscan.io/address/0xe15a8Ca5BD8464283818088c1760d8f23B6a216E) | The Predicate registry the pool was deployed with. The owner can set another one later, so the pool itself holds the live answer | `pool` is the proxy, so it is the address an upgrade keeps. All state lives in the proxy, including the CoFHE ACL grants, which name the proxy's address, so an upgrade keeps notes, receipts, obligations and encrypted liabilities usable. The pool's owner and the upgrader are separate roles: transferring one does not transfer the other. ### Listed assets Three assets are listed, each with an `id` in listing order, a plain ERC-20 (TOKEN) and its confidential wrapper (eTOKEN). | id | Symbol | Name | Decimals | `underlying` | `wrapper` | | - | - | - | - | - | - | | 1 | USDC | USD Coin | 6 | [`0xe2bF47701F71A04c4CD82093f4cE24E0A8C0DC3e`](https://sepolia.etherscan.io/address/0xe2bF47701F71A04c4CD82093f4cE24E0A8C0DC3e) | [`0x8d9FbDb754fC2ff04F8B98491340B1D339404c50`](https://sepolia.etherscan.io/address/0x8d9FbDb754fC2ff04F8B98491340B1D339404c50) | | 2 | WETH | Wrapped Ether | 18 | [`0x9DB43DB59A08168f4d99E52af14565e5A9BAda82`](https://sepolia.etherscan.io/address/0x9DB43DB59A08168f4d99E52af14565e5A9BAda82) | [`0xe8B90154Faca16F1b2334d270cBfD4f51A74e6a2`](https://sepolia.etherscan.io/address/0xe8B90154Faca16F1b2334d270cBfD4f51A74e6a2) | | 3 | USDT | Tether USD | 6 | [`0xD4B28B340b84e38699e802357d49E04b109B514f`](https://sepolia.etherscan.io/address/0xD4B28B340b84e38699e802357d49E04b109B514f) | [`0x5E66e7572e0135832C0146E32Fe4eb5FFbC56dB8`](https://sepolia.etherscan.io/address/0x5E66e7572e0135832C0146E32Fe4eb5FFbC56dB8) | [TOKEN and eTOKEN](/concepts/token-formats) explains the wrapper and how note units relate to `decimals`. | id | Symbol | `mintable` | `relayerMinFee` | Price | | - | - | - | - | - | | 1 | USDC | `true` | `"0.1"` | `usdPrice` `1` | | 2 | WETH | `true` | `"0.00005"` | `ethPrice` `"1"` | | 3 | USDT | `true` | `"0.1"` | `usdPrice` `1` | [Running a relayer](/operators/relayer) explains how `relayerMinFee`, `ethPrice` and `usdPrice` become fee quotes, and [Fees and referrals](/concepts/fees) why the fee is paid as a note. ### What the record does not tell you Treat the record as what was deployed rather than as the live configuration: the owner of the pool can point it at another Predicate registry and policy afterwards, and the owner of `proxyAdmin` can replace the pool's code entirely. Read the live values from the pool. # Intent client (planned) Source: https://docs.fluton.io/sdk/intent-client The planned cross-chain side of the Fluton SDK: a client that creates intents, requests quotes, streams offers and executes them, with React bindings. > [!NOTE] > > This interface is planned and not available yet. It is published here so integrators can see where > the SDK is going; names and shapes may change before release. The pool client that exists today is > documented from [Keys, notes and scanning](/sdk/keys-and-scanning) onwards and listed in the > [Pool client reference](/sdk/reference). The intent client lets a dApp create intents, request quotes, stream offers in real time, execute the selected offer and track an intent's status from start to finish, across chains. It also carries optional confidentiality settings and post-fulfillment actions. ## Packages and entry points * `@fluton/sdk` (core) * `@fluton/sdk/react` (hooks and providers) * `@fluton/sdk/viem` (optional adapter helpers) * `@fluton/sdk/ethers` (optional adapter helpers) ## Create a client ```ts theme={null} import { FlutonClient } from "@fluton/sdk"; const fluton = new FlutonClient({ chains: { ethereum: { chainId: 1, rpcUrl: "…" }, arbitrum: { chainId: 42161, rpcUrl: "…" }, }, signer: ethersOrViemSigner, // optional }); ``` The signer is optional for server-side quoting and intent creation, and required for `execute()`. ## Quote, execute and track ```ts theme={null} const quote = await fluton.bridge.quote({ fromChain: "ethereum", toChain: "arbitrum", token: "USDC", amount: "100", }); const res = await fluton.bridge.execute(quote); fluton.bridge.track(res.intentId, (s) => console.log(s.status)); ``` ## Custom intents The bridge helpers sit on a lower-level intent engine, which you can drive directly: ```ts theme={null} const draft = await fluton.intent.create({ ... }); const signed = await fluton.intent.sign(draft); const { intentId } = await fluton.intent.submit(signed); const offer = await fluton.offers.selectBest(intentId); await fluton.intent.execute(intentId, offer); ``` ## Modules ### `fluton.supported` Discover what is supported: networks, tokens and adapters. * `getSupportedChains(): Promise` * `getSupportedTokens(chain): Promise` * `getCapabilities(): Promise` (confidential support per chain and token) ### `fluton.bridge` Simple bridge workflows. * `quote(params): Promise` * `execute(quote, opts?): Promise` * `track(intentId | txHash, cb?): Unsubscribe` ### `fluton.intent` The low-level intent engine. * `create(params): Promise` * `sign(draft, signer?): Promise` (private key or browser wallet signing) * `submit(signed): Promise<{ intentId: string }>` (registers the intent with the backend) * `get(intentId): Promise` * `status(intentId): Promise` * `execute(intentId | SignedIntent, opts?): Promise` ### `fluton.offers` Offer discovery and selection. * `list(intentId): Promise` * `subscribe(intentId, onOffer, onError?): Unsubscribe` (WebSocket or SSE, both supported) * `selectBest(intentId, strategy?): Promise` ### `fluton.utils` Utility methods. * `parseUnits(amount, decimals)` * `formatUnits(bigint, decimals)` * `toChainKey(chainId)` / `toChainId(key)` ## Types ### Chains and tokens ```ts theme={null} type ChainKey = "ethereum" | "arbitrum" | string; type Token = { symbol: string; // "USDC" address: `0x${string}`; // on that chain decimals: number; name?: string; }; type SupportedChains = Record; ``` ### Intent params ```ts theme={null} type IntentCreateParams = { fromChain: ChainKey; toChain: ChainKey; inputToken: Token | string; // a token symbol is enough outputToken: Token | string; inputAmount: string; // human string, e.g. "100.1" receiver?: `0x${string}`; // default: the signer's address slippageBps?: number; // default 30 (0.30%) deadlineSecs?: number; // default 300 confidential?: boolean; // v1 preview actions?: Action[]; // v1: limited post-fulfillment actions }; type Action = | { type: "contractCall"; chain: ChainKey; // usually toChain contract: `0x${string}`; abiFragment: string; // minimal ABI string for the method method: string; args: unknown[]; value?: string; // optional native value } | { type: "noop"; // placeholder for future kinds }; ``` ### Offer ```ts theme={null} type Offer = { id: string; relayer: `0x${string}`; outputAmount: string; // human string in output token units feeAmount?: string; etaSeconds?: number; expiresAt: string; // ISO signature: `0x${string}`; }; ``` ## React bindings `@fluton/sdk/react` wraps the client in a provider and a set of hooks. ```tsx theme={null} ``` Hooks (v1): * `useSupportedChains()` * `useSupportedTokens(chain)` * `useBridgeQuote(params, { enabled })` * `useExecuteBridge()`: returns `execute(quote)` plus the transaction state * `useIntentStatus(intentId)` (polling or stream) * `useOffers(intentId)` (stream) Hook return shapes follow the TanStack Query style: ```ts theme={null} { data: T; error: Error | null; isLoading: boolean; refetch: () => void; } ``` Until this client ships, the [pool client](/sdk/overview) is the SDK: private deposits, withdrawals and transfers in Fluton Pool on Ethereum Sepolia. # Keys, notes and scanning Source: https://docs.fluton.io/sdk/keys-and-scanning Derive a spend key from a wallet signature, publish an address or a view key, and discover owned notes from RPC or through an indexer. A Fluton Pool wallet is one secret: the spend key. Everything else (the shielded address people pay, the view key an auditor reads with, and the notes the pool holds for you) is derived from it or discovered with it. This page covers the pool client's key and scanning modules; [Keys and view keys](/concepts/keys-and-view-keys) explains why the split works. ## Spend key `deriveSpendKey` asks a wallet to sign one fixed, domain-bound message and hashes the signature into a field element: ```ts theme={null} import { deriveSpendKey, spendKeyMessage, spendKeyFromSignature } from "@fluton/sdk"; const spendKey = await deriveSpendKey(walletClient, { chainId: 11155111, pool }); ``` The message is built by `spendKeyMessage({ chainId, pool })`. It names the chain and the pool (the address lower-cased, so its checksum does not matter), and spells out what signing does: ```text theme={null} Fluton - shielded spend key Signing this message derives the SECRET key that controls your shielded balance and decrypts your private payment history. Only sign it inside the Fluton app. Chain ID: 31337 Pool: 0x… ``` The derivation is `keccak256("fluton-spend-key" || signature)`, of which 31 bytes become the key, so the result is always below the BN254 field size with no modular bias. `spendKeyFromSignature` does that step on its own and is a pure function of the signature bytes. Ethereum wallets sign with RFC 6979 deterministic nonces, so the same account always produces the same signature and therefore the same spend key, on any device, with nothing stored. One account derives the same key, and the same shielded address, every time; another account, another pool or another chain each derive an unrelated key. ```ts theme={null} const k1 = await deriveSpendKey(walletClient, { chainId, pool }); const k2 = await deriveSpendKey(walletClient, { chainId, pool }); // k1 === k2, and 0n < k1 < FIELD_SIZE const address = await shieldedAddressFromSpendKey(k1); // the same on every device ``` > [!WARNING] > > Anyone who obtains that signature owns the shielded balance and can decrypt the whole note history. A key that is not wallet-derived works just as well: `randomFieldElement()` produces one, and `keypairFromPrivate(spendKey)` turns any spend key into the keypair that notes are built with. ## Shielded address The address a payer needs is the spend public key plus the x25519 key that notes are encrypted to: ```ts theme={null} import { shieldedAddressFromSpendKey, parseShieldedAddress } from "@fluton/sdk"; const address = await shieldedAddressFromSpendKey(spendKey); // "pp-addr::" const { publicKey, encryptionKey } = parseShieldedAddress(address); ``` `parseShieldedAddress` rejects anything that is not exactly three `pp-addr:`-prefixed parts with a 32-byte encryption key and a public key inside the field, so an address pasted into a form is validated before it reaches a proof. The encryption keypair itself is derived from the spend key by `encryptionKeypairFromSpendKey`, which is why one secret recovers everything. ## View key `viewKeyFromSpendKey` derives read-only access. A `ViewKey` is three values: the Poseidon spend public key, the `nullifierKey` (`Poseidon(spendKey, NULLIFIER_KEY_DOMAIN)`) and the 32-byte x25519 `encryptionSecret`. All three are one-way from the spend key: ```ts theme={null} import { viewKeyFromSpendKey, serializeViewKey, parseViewKey, scanShieldedNotes } from "@fluton/sdk"; const view = await viewKeyFromSpendKey(spendKey); const shareable = serializeViewKey(view); // "pp-view:::" const notes = await scanShieldedNotes(publicClient, pool, parseViewKey(shareable), scan); ``` With those three values a holder decrypts every note ever sent to the address, rebuilds each commitment, and computes each nullifier, so they see the balance, the history and which notes are spent. `shieldedAddressFromViewKey` returns the same address as the spend key's, and `keypairFromViewKey` returns a view-only keypair that computes identical commitments and nullifiers. What it cannot do is spend: `buildTransactionInputs` rejects a view-only note with a *watch-only* error, because the circuit needs the private key itself. A viewer also does not learn the recipient or amount of outgoing payments, only that a note was spent and what change came back. ## Scan for notes `scanShieldedNotes` is the receiving half of a private transfer and, at the same time, full recovery of a wallet from chain data: ```ts theme={null} import { scanShieldedNotes } from "@fluton/sdk"; const { notes, spendable, balances } = await scanShieldedNotes(publicClient, pool, spendKey, scan); ``` It takes the spend key or a view key and returns three things: `notes`, every discovered note as `{ utxo, spent }`; `spendable`, the unspent ones (ready to spend as they are, when the key was a spend key); and `balances`, an `AssetBalances` map of unspent value per asset id. Amounts of different assets are never added together: `balancesOf` sums per asset id. Discovery is trial decryption. Every `NewCommitment` ciphertext is handed to `tryDecryptNote` with the scanner's encryption keys; a blob that is not addressed to this key fails authentication and is skipped, which is the normal case. Each blob is exactly `NOTE_CIPHERTEXT_LENGTH` (168) bytes, so its size says nothing about the note inside. A decrypted plaintext is accepted only if `isCanonicalOpening` holds for it, because Poseidon reduces its inputs modulo the field: without that check a sender could commit to 0, encrypt the field size, and show a wallet a balance it does not have. [Notes and proofs](/concepts/notes-and-proofs) gives the ranges a canonical opening has to be in. The note is then rebuilt and its commitment compared with the leaf, which authenticates the asset too (the commitment hashes it), so a transfer that kept its asset private on-chain is still recovered as the right asset. A note naming an asset the pool does not list is ignored. Spent status comes from the pool: `isSpent` per note on a plain scan, or from the verified nullifier set when an indexer is used. ### From RPC, in pages `ScanOptions` is the scan window: **fromBlock** `bigint` First block to scan: the pool's deployment block. Default 0. **chunkSize** `bigint` Maximum blocks per `eth_getLogs` call. Left unset, the whole range goes in one call, which only a local node will answer. **toBlock** `bigint` Last block to scan. Default: the latest block, read fresh so a scan never ends at a stale head. **indexer** `IndexerSource` An optional indexer to read history from, verified on-chain, with an RPC fallback on any doubt. A deployment publishes the first two as `deployBlock` and `logChunk` ([Deployments](/reference/deployments) lists the values): a client scans from `deployBlock` in `logChunk`-sized pages by passing them as `fromBlock` and `chunkSize`, so a hosted endpoint is asked for a bounded range from the deployment block instead of the whole chain. An RPC scan refuses incomplete logs rather than build a tree the pool never had: the leaves must be contiguous, must start at leaf 0 when no `fromBlock` was given, and must be whole join-splits. Every transaction appends exactly three leaves. ### Through an indexer An `IndexerSource` points the scan at a standalone indexer, such as the one the hosted wallet uses: ```ts theme={null} const scan = { fromBlock: deployBlock, // from the deployment chunkSize: logChunk, indexer: { url: "https://indexer.example.org", chainId: 11155111, pool }, }; ``` The client treats it as an untrusted accelerator and checks everything before it trusts a single leaf: **1. Identity and health** `/health` must name this chain and this pool and report `healthy: true`, and it must carry an `indexedBlock`. **2. Shape** Every page of `/commitments` and `/nullifiers` must agree on the indexed block and the total, the commitments must be contiguous from leaf 0 and inside the field, and each ciphertext must be valid hex. **3. The tail from RPC** Anything after the indexer's `indexedBlock` is read from RPC up to a pinned block, and the first tail leaf must continue exactly where the indexer stopped. **4. The pool decides** At that pinned block, the merged list must match the chain: the leaf count equals `nextIndex()`, the tree rebuilt from the leaves hashes to `getLastRoot()`, the nullifiers number `nullifierCount()` with no repeats, and the leaf count is whole transactions. Receipt scans add `depositNonce()`. Any failure raises an `IndexerError`, which `reportIndexerFallback` logs through the source's `onFallback` (or `console.warn`), and the scan continues as a plain RPC scan. Requests carry no identifying input at all: the client downloads the full lists and trial-decrypts locally. One gap remains by design. An indexer could alter a note's ciphertext (the commitment and the root stay valid) and so hide that note from discovery. It cannot steal or forge anything, and a scan with `indexer` left out recovers the note. Next: [Deposits, withdrawals and transfers](/sdk/transactions) builds on these keys and on the tree this scan rebuilds. [Notes and proofs](/concepts/notes-and-proofs) covers the note format itself. # SDK overview Source: https://docs.fluton.io/sdk/overview What the Fluton SDK is, which of its two surfaces exists today and which is planned, its entry points, and a map of the pool client's modules. > [!NOTE] > > The Fluton SDK is not published to npm yet. It will ship as `@fluton/sdk`. > These pages describe the pool client as it exists today and the intent client as it is planned. The Fluton SDK is the TypeScript client for Fluton. It has two surfaces: * The **pool client** exists today. It covers notes and keys, tree rebuild and note discovery, proving, deposits, obligations and claims, private transfers, and the relayer and indexer clients of Fluton Pool. [Keys, notes and scanning](/sdk/keys-and-scanning) and [Deposits, withdrawals and transfers](/sdk/transactions) walk through it, and the [Pool client reference](/sdk/reference) lists every export. * The **intent client** is planned. A `FlutonClient` will create intents, request quotes, stream offers and execute the selected offer across chains, with React bindings on top. [Intent client (planned)](/sdk/intent-client) describes that interface ahead of its release. Everything on-chain goes through **viem**. Proofs are Groth16 proofs built with **snarkjs**, Poseidon hashing comes from **poseidon-lite**, the `@noble/ciphers`, `@noble/curves` and `@noble/hashes` packages supply the pure crypto, and the confidential (eTOKEN) side uses **@cofhe/sdk**. `circomlibjs` provides the circomlib-generated Poseidon bytecode that runs on-chain. ## Entry points The pool client has two entry points, and the difference is what each may import: > [tab] @fluton/sdk (node) > > The full surface. It includes the snarkjs-backed proving flows (`proof`, `transact`) and the node CoFHE client (`cofheNode`). > > ```ts theme={null} > import { transact, scanShieldedNotes, deriveSpendKey } from "@fluton/sdk"; > ``` > [tab] @fluton/sdk/browser > > The browser-safe surface: pure crypto, the Merkle tree, the ABIs, the read-side pool operations and the runtime-agnostic transaction core. It excludes the snarkjs modules and the node CoFHE client and adds `inputs`; the web wallet proves with its own snarkjs build and brings its own CoFHE client. > > ```ts theme={null} > import { transactWith, scanShieldedNotes, parseShieldedAddress } from "@fluton/sdk/browser"; > ``` Both entry points re-export whole modules, so every name below is available from the entry point that includes its module. When the intent client ships it adds `@fluton/sdk/react` for hooks and providers, and `@fluton/sdk/viem` and `@fluton/sdk/ethers` as optional adapter helpers. ## Modules One line per module of the pool client, with `inputs` (the one module the browser entry point exports directly) in its place. The last column says which entry points carry the module; the pages linked here document its functions, and the [Pool client reference](/sdk/reference) lists each export. | Module | What it holds | Entry points | | - | - | - | | `crypto` | Pure crypto: Poseidon hashing (`poseidon-lite`) | both | | `merkleTree` | The Merkle tree | both | | `utxo` | Notes and keys: notes, commitments and nullifiers ([Notes and proofs](/concepts/notes-and-proofs)) | both | | `encrypt` | Notes and keys: note ciphertexts and shielded addresses ([Private transfers](/concepts/private-transfers)) | both | | `spendKey` | Notes and keys: the spend key ([Keys, notes and scanning](/sdk/keys-and-scanning)) | both | | `viewKey` | Notes and keys: the view key ([Keys, notes and scanning](/sdk/keys-and-scanning)) | both | | `inputs` | Proving: circuit inputs ([Deposits, withdrawals and transfers](/sdk/transactions)) | both: directly from `@fluton/sdk/browser`, through `proof` from `@fluton/sdk` | | `proof` | Proving: snarkjs ([Deposits, withdrawals and transfers](/sdk/transactions)) | `@fluton/sdk` only | | `scan` | Tree rebuild and note discovery ([Keys, notes and scanning](/sdk/keys-and-scanning)) | both | | `pool` | Read-side pool operations | both | | `cofhe` | Deposits, obligations and claims on the eTOKEN side ([Deposits, withdrawals and transfers](/sdk/transactions)) | both | | `relay` | The relayer client ([Deposits, withdrawals and transfers](/sdk/transactions)) | both | | `indexer` | The indexer client ([Keys, notes and scanning](/sdk/keys-and-scanning)) | both | | `referral` | Referral codes ([Invite and referrals](/wallet/invite-and-referrals)) | both | | `bonus` | The referral bonus ([Fees and referrals](/concepts/fees)) | both | | `bonusClaims` | Referral bonus claims ([Invite and referrals](/wallet/invite-and-referrals)) | both | | `predicate` | Deposit-screening attestations ([Deposit screening](/concepts/deposit-screening)) | both | | `transactCore` | The runtime-agnostic transaction core ([Deposits, withdrawals and transfers](/sdk/transactions)) | both | | `outcome` | Transaction outcomes ([Deposits, withdrawals and transfers](/sdk/transactions)) | both | | `transact` | The snarkjs-backed proving flow for node ([Deposits, withdrawals and transfers](/sdk/transactions)) | `@fluton/sdk` only | | `cofheNode` | The node CoFHE client | `@fluton/sdk` only | | `logs` | `ScanOptions`, exported as a type only | both, type only | | `abi` | `poolAbi`, `erc20Abi`, `confidentialWrapperAbi` and `predicateRegistryAbi` | both | ## Where to go next > [card] [Keys, notes and scanning](/sdk/keys-and-scanning) > > Derive a spend key, hand out an address or a view key, and discover the notes a key owns. > [card] [Deposits, withdrawals and transfers](/sdk/transactions) > > Build, prove, relay and read back every kind of transaction. > [card] [Pool client reference](/sdk/reference) > > Every export of the pool client, module by module, with its signature. > [card] [Intent client (planned)](/sdk/intent-client) > > The cross-chain intent interface the SDK will add: quotes, offers, execution and React bindings. For the ideas behind the API (what a note is, what TOKEN and eTOKEN mean, why a withdrawal pays a fee, and what each transaction still makes public), see [Notes and proofs](/concepts/notes-and-proofs), [TOKEN and eTOKEN](/concepts/token-formats), [Fees and referrals](/concepts/fees) and [What stays public](/concepts/privacy-model). # Pool client reference Source: https://docs.fluton.io/sdk/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](/sdk/intent-client). 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](/concepts/keys-and-view-keys) explains the split; [Notes and proofs](/concepts/notes-and-proofs) explains the note itself. | Export | Signature | What it does | | - | - | - | | `deriveSpendKey` | `deriveSpendKey(walletClient, { chainId, pool }) → Promise` | 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` | Private key, nullifier key and Poseidon public key. | | `createKeypair` | `createKeypair() → Promise` | A random spending keypair. | | `nullifierKeyFromPrivate` | `nullifierKeyFromPrivate(privateKey) → Promise` | `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` | The `pp-addr:` address to hand out. | | `serializeShieldedAddress` | `serializeShieldedAddress(address) → string` | `pp-addr::`. | | `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` | Public key, nullifier key and encryption secret, each one-way from the spend key. | | `serializeViewKey` | `serializeViewKey(view) → string` | `pp-view:::`. | | `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` | A fresh note with a random blinding. Amount 0 is a valid dummy. | | `utxoCommitment` | `utxoCommitment(utxo) → Promise` | `Poseidon(amount, publicKey, blinding, asset)`, the leaf. | | `utxoNullifier` | `utxoNullifier(utxo) → Promise` | `Poseidon(commitment, index, 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` | Decodes a `pp-note:` string and checks its ranges. | | `poseidon` | `poseidon(inputs) → Promise` | Poseidon of 1 to 4 field elements, identical to the circuit and the on-chain hasher. | | `hashLeftRight` | `hashLeftRight(left, right) → Promise` | 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` 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: 11155111, 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 tree 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](/sdk/keys-and-scanning) 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` | Every leaf in insertion order, from the indexer when it verifies, otherwise from RPC. | | `buildTreeFromChain` | `buildTreeFromChain(publicClient, pool, levels, scan?) → Promise<{ tree, records }>` | Rebuilds the tree exactly as the pool holds it. | | `findUtxoIndex` | `findUtxoIndex(records, utxo) → Promise` | The leaf index of a note's commitment. Throws if the note has not landed. | | `getEventsChunked` | `getEventsChunked(publicClient, { address, abi, eventName, args? }, scan?) → Promise` | Paged `eth_getLogs` honouring `fromBlock`, `chunkSize` and `toBlock`. Without a chunk size the whole range goes in one call. | | `indexerHealth` | `indexerHealth(source) → Promise` | Refuses an indexer that serves another chain or pool, reports unhealthy, or has no `indexedBlock`. | | `fetchIndexedCommitments` | `fetchIndexedCommitments(source) → Promise<{ indexedBlock, records }>` | Every commitment through the indexer's block, checked contiguous from leaf 0 and 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` | 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) → Promise` | A fixed-depth tree from ordered leaves. The instance has `root`, `leafCount` and `proof(index) → MerkleProof`. | `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`. 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: 11155111, 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](/concepts/token-formats) explains the records; [Fees and referrals](/concepts/fees) explains the arithmetic. | Export | Signature | What it does | | - | - | - | | `getPoolConfig` | `getPoolConfig(publicClient, pool) → Promise` | 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` | The current withdrawal fee in basis points. | | `readReferralShareBps` | `readReferralShareBps(publicClient, pool) → Promise` | The base referral share, in basis points of the fee. | | `readBonusSigner` | `readBonusSigner(publicClient, pool) → Promise
` | The address whose attestations set bonuses. The zero address means none can be set. | | `readReferralBonus` | `readReferralBonus(publicClient, pool, referrer) → Promise` | A referrer's stored bonus, all zeros when none was set. | | `readReferralShareOf` | `readReferralShareOf(publicClient, pool, referrer) → Promise` | The share a deposit landing now would credit this referrer, base plus bonus. | | `readReferralCredit` | `readReferralCredit(publicClient, pool, referrer, asset) → Promise` | 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` | One receipt with its current status. | | `readObligation` | `readObligation(publicClient, pool, id) → Promise` | One obligation. | | `readAttempt` | `readAttempt(publicClient, pool, id) → Promise` | One attempt, with its wrapper claim id when it is a burn. | | `readObligationWithAttempts` | `readObligationWithAttempts(publicClient, pool, id) → Promise` | 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` | 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` | Obligations from events plus state, optionally only those paying `to`. | | `readClaim` | `readClaim(publicClient, wrapper, claimId) → Promise` | A wrapper claim: recipient, encrypted handle, decrypted amount and whether it was claimed. | | `parseTxEffects` | `parseTxEffects(receipt, pool) → TxEffects` | Commitments with leaf indices, obligations, attempts and a deposit request, from the receipt's own logs and never inferred. | | `assignIndicesFromReceipt` | `assignIndicesFromReceipt(effects, outputs) → Promise` | Sets each output note's leaf index 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](/sdk/transactions) describes the flow step by step. | Export | Signature | What it does | | - | - | - | | `transactWith` | `transactWith(publicClient, walletClient, params, prove) → Promise` | One join-split: a transfer or withdrawal, a TOKEN deposit when `attest` is set, or a finalization when `depositId` is set. `walletClient` may be null when relaying. | | `depositPublicWith` | `depositPublicWith(publicClient, walletClient, { pool, asset, amount, keypair, attest, referrer?, onStatus?, scan? }, prove) → Promise` | A one-step TOKEN deposit as a new note. | | `finalizeDepositWith` | `finalizeDepositWith(publicClient, walletClient, { pool, depositId, keypair, referrer?, onStatus?, scan? }, prove) → Promise` | Turns a `Verified` receipt into a note. Depositor only; safe to re-run after a failed proof. | | `withdrawWith` | `withdrawWith(publicClient, walletClient, params, prove) → Promise` | 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` | A private transfer to a `pp-addr:` address. Nothing crosses the boundary and no asset is named. | | `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 and mixed assets. | | `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` | 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`, `attest`, `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. ## 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](/concepts/token-formats) explains why a receipt alone proves nothing here. | Export | Signature | What it does | | - | - | - | | `requestDepositWith` | `requestDepositWith(publicClient, walletClient, { pool, asset, amount, attest, 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` | 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` | 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` | 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` | 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` | 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. | | `readConfidentialBalance` | `readConfidentialBalance(publicClient, client, { wrapper, owner }) → Promise` | 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` | 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` | 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 }`. ## 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](/operators/relayer) documents the service itself. | Export | Signature | What it does | | - | - | - | | `createRelayClient` | `createRelayClient(baseUrl, { chainId?, pool? }) → Promise` | Reads `GET /status` and refuses a relayer serving another chain or pool. | | `relay.quote` | `quote() → Promise` | `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` | `POST /relay`; the hash the transaction was sent under. | | `relay.txStatus` | `txStatus(nullifier) → Promise` | `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` | 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` | 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). `FEE_SLOT` is 2. ```ts theme={null} import { createRelayClient, transfer } from "@fluton/sdk"; const relay = await createRelayClient(relayerUrl, { chainId: 11155111, 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 Predicate attestation of the depositor. The SDK fetches it through the backend API client, renews it when it is close to expiry and replaces it once when the registry calls it stale. [Deposit screening](/concepts/deposit-screening) explains the policy side. | Export | Signature | What it does | | - | - | - | | `api.predicate.attest` | `attest(depositor) → Promise` | On an `ApiClient` (see below): a fresh attestation for `depositor`. Throws `ScreeningRefusedError` or `ScreeningUnavailableError`. | | `freshAttestation` | `freshAttestation(publicClient, attest, current?) → Promise` | `current` while it is valid for `ATTESTATION_MIN_REMAINING_S` past the chain's latest block, otherwise a new one. | | `simulateWithAttestation` | `simulateWithAttestation(attest, current, simulate) → Promise` | Simulates with `current`; if the registry calls it stale, once more with a new one. Returns the one that passed. | | `isStaleAttestation` | `isStaleAttestation(error) → boolean` | Whether a revert says the attestation expired or its uuid was used. | | `registryRevertReason` | `registryRevertReason(error) → string or null` | The registry's revert reason inside a viem error, or null. | | `parseAttestation` | `parseAttestation(json) → Attestation` | A well-formed attestation from untrusted JSON, or a throw. | | `attestationToJson` | `attestationToJson(attestation) → AttestationJson` | The JSON form, with the expiration as a decimal string. | | `depositStatement` | `depositStatement({ chainId, pool, depositor, policy, uuid, expiration }) → Statement` | The statement a deposit attestation certifies: who deposits, into which pool, under which policy. | | `statementHash` | `statementHash(statement) → Hex` | The hash an attester signs, as the registry computes it, with no EIP-191 prefix. | | `signDepositAttestation` | `signDepositAttestation(attester, params) → Promise` | An attester's signature over a deposit statement. In production Predicate's own attester signs. | | `verifyScreeningAnswer` | `verifyScreeningAnswer(body, { chainId, pool, depositor }) → Attestation` | Checks the API's answer is about this chain, pool and depositor, and turns a refusal into `ScreeningRefusedError`. | An `Attestation` is `uuid`, `expiration` (unix seconds), `attester` and `signature`; an `AttestFn` is any function returning a fresh one. `ScreeningRefusedError` carries the `depositor` and the policy's `code`, `reason` and `policyName` when given. `ATTESTATION_MIN_REMAINING_S` is 60. ```ts theme={null} import { createApiClient, depositPublic } from "@fluton/sdk"; const api = await createApiClient(apiUrl, { chainId: 11155111, pool }); const attest = () => api.predicate.attest(depositor); const { note } = await depositPublic(publicClient, walletClient, { pool, asset, amount: 40n, keypair, attest, wasm, zkey }); ``` ## Referrals and bonuses The pool credits a deposit's referrer by address. Short codes, the Discord and testnet-code bonuses and the screening endpoint 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](/wallet/invite-and-referrals) shows the wallet side. | Export | Signature | What it does | | - | - | - | | `createApiClient` | `createApiClient(baseUrl, { chainId, pool, timeoutMs? }) → Promise` | Checks `/health` names this chain and pool and returns a client. Default timeout 8000 ms. | | `api.referral.byCode` | `byCode(code) → Promise` | The verified record for a code, or null when no address holds it. | | `api.referral.byAddress` | `byAddress(address) → Promise` | The verified record of an address's code. | | `api.referral.claim` | `claim(claim, signature) → Promise` | Claims or changes a code. The API answers 409 when it is taken or a newer claim exists. | | `api.bonus.status` | `status(address) → Promise` | What the address has verified and the signed attestation it adds up to. | | `api.bonus.discordStartUrl` | `discordStartUrl(state) → Promise` | The Discord consent URL to open. | | `api.bonus.discordFinish` | `discordFinish(claim, signature) → Promise` | Attaches the account a ticket verified to the signing wallet. | | `api.bonus.redeemCode` | `redeemCode(claim, signature) → Promise` | Redeems a testnet 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` | Signs it. The wallet must be `claim.address`. | | `verifyReferralSignature` | `verifyReferralSignature(claim, signature) → Promise` | Checks an EOA signature over the claim message. | | `verifyReferralRecord` | `verifyReferralRecord(record, expect) → Promise` | 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` | The EIP-712 signature a bonus signer produces. | | `verifyReferralBonus` | `verifyReferralBonus(signer, domain, bonus, signature) → Promise` | Whether `signature` is `signer`'s. Pass the `bonusSigner` read from the pool. | | `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` | Sign them. | | `verifyBonusCodeSignature`, `verifyDiscordLinkSignature` | `(claim, signature) → Promise` | 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` and `BonusStatus`. 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` | 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`), `expired` and `pending`; the first four are final. `TransactionRevertedError` carries `functionName` and `hash`. ## ABIs and constants Both entry points export the ABIs the SDK calls through: `poolAbi`, `erc20Abi`, `confidentialWrapperAbi` and `predicateRegistryAbi`. 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` | 2500 | The most a bonus adds to the referral share | | `ATTESTATION_MIN_REMAINING_S` | 60 | Validity an attestation must still have when sent | | `FORMAT_CODE` | `confidential: 0`, `public: 1` | `PoolFormat` to `ExtData.format` | | `PREDICATE_REGISTRY` | `0xe15a8Ca5BD8464283818088c1760d8f23B6a216E` | Predicate's registry address on the chains it serves | | `PREDICATE_CHAINS` | chain id to Predicate's chain name | `11155111` is `sepolia` | The concept pages behind these numbers are [Notes and proofs](/concepts/notes-and-proofs), [Private transfers](/concepts/private-transfers) and [Fees and referrals](/concepts/fees). # Deposits, withdrawals and transfers Source: https://docs.fluton.io/sdk/transactions 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 `attest()` first, before the tree, the proof or the approval. **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 tree** `buildTreeFromChain` reproduces the pool's tree, which also resolves each input note's leaf index. See [Keys, notes and scanning](/sdk/keys-and-scanning). **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 indices, the `feeNote` when relayed, the `withdrawFee` the pool kept, and `effects`: the output commitments with the leaf index 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 Predicate **attestation**: a TOKEN deposit and `requestDeposit` carry one, and transfers, withdrawals and finalization need none. See [Deposit screening](/concepts/deposit-screening). ### TOKEN: one step ```ts theme={null} const { note, hash } = await depositPublic(publicClient, wallet, { pool, asset: USDC, amount: 40n, keypair: aliceKeys, attest, // () => Promise referrer, // optional, public like the deposit itself wasm, zkey, }); ``` `attest` is an `AttestFn`: a function that returns a fresh attestation for the depositor, normally by asking Fluton's backend API for one ([Deposit screening](/concepts/deposit-screening)). It is called before anything is spent, so a refused wallet raises `ScreeningRefusedError` having granted nothing, and `ScreeningUnavailableError` when screening cannot run at all. Just before sending, `freshAttestation` fetches a new one if the first expires within `ATTESTATION_MIN_REMAINING_S` (60) seconds, and `simulateWithAttestation` replaces it once more if the registry 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 `attest`, and refuses `attest` on anything that is not a TOKEN deposit. ### 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](/concepts/token-formats)): **1. requestDeposit** `requestDepositWith(publicClient, wallet, { pool, asset, amount, attest })` 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, { attest, 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](/concepts/fees) 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](/concepts/private-transfers)): ```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](/operators/relayer). ## 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 | | `expired` | The pool no longer knows its root and it has not run. Final | | `pending` | It has not run and still can: in the mempool, dropped, or never sent | 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](/sdk/overview) for the module map, the [Pool client reference](/sdk/reference) for every export, or [Notes and proofs](/concepts/notes-and-proofs) for what the circuit proves. # Invite and referrals Source: https://docs.fluton.io/wallet/invite-and-referrals Share an invite link or short code, see what it earns you, raise your share with the Discord and testnet-code bonuses, and claim your credits. Fluton Pool pays the wallet that invited a depositor a share of the fee that deposit will pay. The **Invite** page of the wallet gives the connected wallet its invite link and shows what the link has earned; the bonuses that raise your share live under **Settings** → **Boost your share**. Everything here is per wallet: rewards are credited to, and claimed by, the connected address. ## Your invite link The link is `/?prt=` followed by your short code, or by your wallet address when you have no code. Copy it with **Copy invite link**, tear the ticket stub, or hand it to the system share sheet with **Share**. The stub shows what the pool currently pays you, as a percentage of the fee. Opening that link as another account stores the invite in that browser and shows a **Referred by** row on the Shield form, naming the invite and what it does: *Your friend earns … of the platform fee on this amount. The deposit names them on-chain.* The invite stays until the user removes it, and every later shield names it again. A link that names nobody says so (*No one holds this invite code, so this deposit credits no one.*), and your own link earns you nothing (*This is your own invite link: your deposits don't earn you a reward.*). The pool itself knows nothing of links or codes. A deposit names a **referrer** address in its `ExtData`, and the pool credits that address: it keeps no record of who referred whom. ## Pick a short code Codes are kept by Fluton's backend API, so a deployment without one simply puts your address in the link: *This deployment runs no referral service, so your link names your wallet address. Short codes need one.* A code is 3–32 characters of `a-z`, `0-9`, `-` and `_`, starting with a letter or digit, lower-cased, and never something beginning with `0x`, so a link's parameter is never ambiguous between a code and an address. The form says *Use 3–32 letters, digits, - or \_, starting with a letter or digit.* Claiming one costs no gas: your wallet signs a message naming the code, your address, the chain, the pool and the time it was issued, and the API stores that signature with the record. Clients verify it, and that the record is the one they asked about, before they use the address, so the API can withhold a code but can never point it at an address whose wallet did not sign for it. The registry's rules: | Rule | What happens | | - | - | | One code per address, one address per code | A new code frees the old one, and links carrying it stop crediting you | | A code another address holds | Refused: *referral code is taken* | | An older claim for your address | Refused: *stale claim: this address has a newer one*, so a replayed signature cannot roll a change back | | A claim signed too long ago | Refused: sign it again | ## What you earn A referrer is credited a share of the fee the deposit's amount will pay when it is later unshielded. Deployments start at **25%** of that fee, and the pool's owner can raise or lower the base share. The depositor pays nothing extra: the reward comes out of the pool's own fee, not out of the deposit. [Fees and referrals](/concepts/fees) explains the fee itself. The credit is worked out when the deposit lands, at the rates in force then, and never changes afterwards. It is never more than the whole fee that a withdrawal of that amount pays. A referrer can only be named by a deposit, never by an unshield, so unshields stay as unlinkable as before; a cancelled pending deposit earns nothing. ## Bonuses Two verified facts raise a referrer's share above the base. Both are checked off-chain by the backend API, which signs an EIP-712 attestation that the referrer submits to the pool; the pool caps a bonus at 2500 basis points of the fee and accepts an attestation only from the signer its owner named. > [accordion] The encrypted role on Fluton's Discord > > Fluton's Discord server has a role named **encrypted**. Holding it is worth +**2000** basis points of the fee, valid **30 days** from the verification, and renewed by verifying again. Verification is the Discord application's own OAuth2 consent, in two legs so that a consent link can never bind someone else's account to another wallet: the callback only checks whether you hold the role and hands your browser a single-use ticket, and a wallet **signature** over that ticket attaches the account. One Discord account links to one wallet and one wallet to one account. In the wallet this is **Connect Discord**, then *Verified · sign to attach*. > [accordion] A testnet code > > Worth +**500** basis points of the fee, and permanent. Fluton hands out the codes; each is redeemed once, and one wallet can redeem one code. Your wallet signs the redemption, which moves no funds. Verifying a bonus does not yet change what the pool pays. The panel shows the base share, each bonus and whether it is *Active on-chain* or *Not yet on-chain*, and the referrer activates the attestation with **Activate on-chain**; the wallet verifies the attestation against the pool's own signer first, so a misbehaving API cannot get anything signed into the pool. The pool takes only an attestation issued strictly later than the one it stores, so a replay can never roll a bonus back, while a newer one that grants less (a lapsed role, a downgrade) still lands. A bonus applies to deposits that land after it is set; credits already given never change. ## Claim your credits **Your rewards** on the Invite page reads your credits straight from the pool, per token, never from the API. Every row with a credit carries a claim button per format, one for TOKEN and one for eTOKEN; either calls `claimReferral(asset, amount, to, format)`, which pays out exactly like an unshield, through a payout obligation, so the **Payout status** panel tracks the claim until the pool has confirmed it. Claims are public, like the deposits that earned them. A claim can only take what unshield fees have actually paid into the pool in that token. Until they have, the pool reverts with `InsufficientFees`, which the wallet shows as *Not enough platform fees have been paid in this token yet. Try again later.* When only part of a credit is covered, the row says how much is claimable now and that the rest follows as more fees in that token are paid. ## Known limits * Anyone can refer themselves from a second wallet, which amounts to a rebate of **25%** of the fee, or up to half of it with bonuses. * Credits are public per referrer address, and so are the link between a deposit and its referrer, and a referrer's bonus. * A credit that is never claimed stays reserved inside the pool's fees, where the owner cannot collect it. * A leaked API signing key can raise anyone's share by at most 25 percentage points of the fee, until the owner changes the signer and revokes the grants; the permanent part of a bonus stays until it is revoked. The rest of the wallet is described in [Using the wallet](/wallet/using-the-wallet). # Using the wallet Source: https://docs.fluton.io/wallet/using-the-wallet Connect, shield and unshield any listed token, pay a shielded address, resume a pending deposit, scan for your notes and share a view key. The Fluton Pool wallet is the web app at [app.fluton.io](https://app.fluton.io). It talks to the pool, the relayer, the indexer and the backend API, and everything secret stays on your device: proofs are built with snarkjs **in your browser**, and your keys never leave it. The wallet says **shield** and **unshield**. In the protocol, SDK and reference pages those are a *deposit* and a *withdrawal*, the same two operations under their contract names. ## Connect and unlock On Ethereum Sepolia you press **Connect Wallet** and sign with an injected wallet: **MetaMask** or another EIP-1193 wallet. The session is remembered and restored silently after a reload, without a prompt, until you press **Disconnect**. If the wallet sits on another chain, the app offers to switch before it signs anything. To get test tokens, open the **Faucet** (the test token faucet). It offers **Claim 100 TOKEN** and **Claim 100 as eTOKEN (mint + wrap)** for every openly mintable token in the deployment; a deployment of real tokens has nothing to offer there. Two signatures unlock the two kinds of balance: **1. Sign to unlock** One chain- and pool-bound message is hashed into your spend key. The same wallet therefore reproduces the same shielded wallet on any device, so there is nothing to back up beyond the wallet itself. **2. Unlock your encrypted balance** An eTOKEN balance is encrypted on-chain, so reading it needs one more signature (a self ACP for Fhenix CoFHE). The form says *Sign once to decrypt your eTOKEN balance. Nothing is sent.* ## Shield a token **Shield** moves tokens from your wallet into your private balance. Pick the token and the format in the **You deposit** selector: the plain ERC-20 (**TOKEN**) or its encrypted wrapper (**eTOKEN**). Both fields of the card hold the same amount, because shielding costs nothing beyond gas; the card shows **Platform fee (0%)**. See [TOKEN and eTOKEN](/concepts/token-formats) for what each route does on-chain. If you arrived through an invite link, a **Referred by** row names the invite this deposit credits, and you can remove it. See [Invite and referrals](/wallet/invite-and-referrals). Screening comes first. Every deposit needs a Predicate attestation for the wallet that sends it, so the button waits on the API (*Connecting to deposit screening…*) and blocks when it is unreachable (*Deposits unavailable: screening is offline*). The attestation is fetched before anything is approved or proved, so a refused wallet spends nothing and is shown the policy's answer rather than a failure. See [Deposit screening](/concepts/deposit-screening). **Review** freezes the amount, format and referrer; **Shield** then runs the wallet prompts. A TOKEN shield is one pull, plus an approval when the allowance is short. An eTOKEN shield is token-first: the tokens move into a receipt first and are credited once the pool has verified what it received. ## Unshield to your wallet **Unshield** pays your private balance out to the connected wallet. Paying any other public address is a **Transfer** instead. The amount in **You receive** is what the wallet receives. The pool's platform fee and, when one submits, the relayer's fee are spent *on top* of it from the same asset's private balance, and **You unshield** shows that total. Pick whether the payout arrives as eTOKEN or TOKEN in the **Receive as** selector. [Fees and referrals](/concepts/fees) explains both charges; the platform fee is the withdrawal fee described there. When a **relayer** is configured it submits the transaction and pays the gas, so your wallet never appears on-chain for the withdrawal. Without one, your wallet submits it and the card shows a **Network fee** instead. If the relayer fails, the app offers to send from your wallet, but only once it has established that the relayer never broadcast those notes; otherwise re-sending could land first and name you as the sender. A confirmation is a snapshot, and it closes rather than run on values that no longer hold: *Review the transaction again: the relayer fee rose with network gas prices*, *the platform fee changed*, *the asset changed*, *your wallet account changed*. The fee rate is re-read every minute and again right before the transaction runs. One transaction spends at most 2 notes, so a balance split over many small notes shows *Consolidate first by transferring to yourself*. A confidential transfer can silently move nothing, so the result screen keeps a **Payout status** panel open until the pool has verified the outcome on-chain: *awaiting confirmation* becomes *confirmed*, and a TOKEN payout also needs its wrapper claim. The relayer's keeper normally does this for you; **Confirm now**, **Retry** and **Claim TOKEN** let you do it yourself when no keeper is running. ## Pay a shielded address The **Transfer** page takes a shielded address (`pp-addr:`), a 0x address or an ENS name in its **To** field; the placeholder reads *0x, pp-addr:, or name.eth*. A shielded recipient is confirmed with *Private recipient · stays inside the pool*, and the payment never leaves the pool: no amount, no recipient and no token appear on-chain. A 0x or ENS recipient is a public payout, and pays the platform fee like an unshield. Your own shielded address is not refused. It consolidates: *Your own address: this consolidates your notes*. To be paid, share your shielded address from the **Receive** dialog, which also offers a QR code and a payment link (`/transfer?to=` plus the address) that opens the Transfer page with the recipient filled in. [What stays public](/concepts/privacy-model) sets out what each kind of transaction still exposes. ## Pending deposits An eTOKEN shield that stops half-way leaves its tokens in a receipt, listed under **Pending deposits** on the Shield page with its own state: *awaiting verification*, *ready to finalize*, *nothing received* or *refunding*. **Resume** authenticates the receipt and finalizes it into notes; **Cancel & refund** returns what the pool actually received, and that refund gets a payout status of its own. Only the depositor can do either, and the list is read from chain state, so it survives a reload or a move to another device. ## Scan for your notes Your balance is not stored anywhere. The wallet rebuilds it by trial-decrypting the pool's note ciphertexts with your key, so one key recovers every note you own: deposits, change and payments received, of every token. The **Refresh** control on the home screen and on the Notes tab rescans, and the wallet rescans by itself after every transaction it sends. When the deployment names an indexer, the scan reads it and verifies it against the pool before trusting it; otherwise it reads the chain in RPC-sized pages from the deployment block. An indexer cannot forge or steal a note, but it could hide one, which is why the scan verifies it against the pool and falls back to the chain when that check fails. ## View keys A **view key** (`pp-view:…`) gives read-only access: balance, history and which notes are spent, but no way to spend. Reveal yours under **Settings** → **Private wallet** → **Back up & share**, confirm the warning, and it is shown for a minute before it blurs again. The spend key sits beside it, with a download that writes a backup file naming the chain, the pool and your shielded address. **Use a different key** goes the other way. **Use a spend key** takes a `0x…` hex key and keeps it in this browser only. **Watch with a view key** opens the wallet watch-only; a pasted view key is never saved, so it is gone after a reload. [Keys and view keys](/concepts/keys-and-view-keys) explains the split between the two. ## History The **History** page has two tabs. **Activity** lists the transactions you made from this browser, filtered by **All**, **Shield**, **Unshield** or **Transfer**, 10, 20 or 50 to a page. **Notes** lists every note your key can decrypt, newest leaf first, each marked *Spendable* or *Spent*, with the spendable count and the private balance of each asset above them. When an asset's notes are fragmented it says how much of that token one transaction can spend and suggests transferring it to yourself to consolidate. Both tabs ask you to unlock first, with a wallet signature or a saved key. ## Settings The **Settings** page holds the **Private wallet** card: where the active key comes from (*Your wallet*, *Imported spend key* or *Imported view key*), whether it is *Unlocked*, *Locked* or *Watch-only*, your shielded address, and the keys panel described above. Below it, **Get more from Fluton** opens the **How Fluton works** tour and **Boost your share**, where referral bonuses are verified and activated.