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

# 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, and one confidential wrapper per listed token. 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](https://docs.fluton.io/reference/deployments.md) for the addresses and
[what stays public](https://docs.fluton.io/concepts/privacy-model.md) 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
```

Value enters only through `deposit` (TOKEN) and `requestDeposit` (eTOKEN), and each takes a signed
screening 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](https://docs.fluton.io/concepts/token-formats.md) 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, name the screening signer, 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 |
| `screeningSigner` | An address the owner names with `setScreeningSigner` | Sign the EIP-712 screenings that `deposit` and `requestDeposit` require |

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 _screeningSigner,
    address _owner
) external initializer;
```

`_screeningSigner` is required: the zero address reverts with `InvalidScreeningSigner`, so a pool
cannot be deployed without deposit screening.

### 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,
    DepositScreening calldata _screening
) external;
function requestDeposit(uint32 _asset, uint64 _amount, DepositScreening calldata _screening)
    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 `DepositRequiresScreening` on any `extAmount > 0`, so relayed jobs never carry a screening |
| `deposit` | The depositor (`msg.sender`) | One-step TOKEN deposit. The pool checks and spends the screening 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 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](https://docs.fluton.io/concepts/fees.md).

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, at the rate in force now:
`(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, and takes the fee at the lowest rate a withdrawal can pay from now
on: the rate in force, or a lower one that is already scheduled or still within its grace.

## 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 setScreeningSigner(address _signer) 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` schedules a rate rather than applying it. The new rate takes effect
`WITHDRAW_FEE_DELAY` (two days) after the call, which emits
`WithdrawFeeChanged(oldBps, newBps, effectiveAt)`; until then `withdrawFeeBps()` keeps returning the
rate in force, and `nextWithdrawFeeBps()` and `withdrawFeeChangesAt()` announce the change. For
`WITHDRAW_FEE_GRACE` (one hour) after a rate takes effect, the pool still accepts a withdrawal that
bound the rate before it. A rate that is not yet in force can be replaced, which restarts the delay;
one that is in force can be replaced only once its grace is over, and an earlier call reverts with
`WithdrawFeeChangeTooSoon`. The pool therefore never accepts more than two rates at once.

`setReferralShareBps` changes the share for deposits that land after it; credits already given
never change. `setBonusSigner` with the zero address disables
`setReferralBonus` while leaving bonuses already set in place.

`setScreeningSigner` names the address whose screenings the pool takes. Screening cannot be switched
off: the signer may never be the zero address, and a new signer refuses every screening the old one
signed. [Deposit screening](https://docs.fluton.io/concepts/deposit-screening.md) explains what the pool 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 |
| `nextWithdrawFeeBps()`, `withdrawFeeChangesAt()` | The scheduled withdrawal fee rate and the time it takes effect. Once that time has passed, the two describe the rate in force |
| `screeningSigner()`, `screeningUsed(bytes32)` | The address whose screenings deposits need, and whether a nonce has been spent |
| `getLastRoot()`, `isKnownRoot(bytes32)`, `nextIndex()`, `treeNumber()`, `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](https://docs.fluton.io/concepts/token-formats.md#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% |
| `WITHDRAW_FEE_DELAY` | 2 days | How long after it is set a new withdrawal fee rate takes effect |
| `WITHDRAW_FEE_GRACE` | 1 hour | How long after a change the rate before it is still accepted |
| `MAX_REFERRAL_SHARE_BPS` | 10000 | A referrer's share can reach the whole fee, never more |
| `MAX_REFERRAL_BONUS_BPS` | 5000 | Cap on one referrer's bonus above the base share |
| `MAX_SCREENING_TTL` | 1 hour | The furthest ahead a screening may expire; one issued for longer is refused |
| `TREE_LEVELS` | 20 | The depth both circuits are compiled for; `initialize` accepts no other |
| `ROOT_HISTORY_SIZE` | 30 | Size of the ring of latest roots behind `getLastRoot()` (from `MerkleTreeWithHistory`). It does not limit the roots a proof may use |
| `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 the withdrawal fee rate (0 to `MAX_WITHDRAW_FEE_BPS`), `referralShareBps`
(0 to `MAX_REFERRAL_SHARE_BPS`), `bonusSigner` and `screeningSigner`. `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. Five are absent from that ABI: `initialize`'s own `InvalidWrapperCodehash`, and the
tree's `InvalidLevels`, `NodeOutOfField`, `NoLeaves` and `TreeIsFull`. It carries the errors the
pool's bases raise instead: `OwnableUnauthorizedAccount` and `ReentrancyGuardReentrantCall`.

### Routing and `ExtData`

| Error | When it fires |
| - | - |
| `DepositRequiresScreening` | `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 a root any of the pool's trees has had |
| `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`, `TreeIsFull`, `NoLeaves`, `NodeOutOfField` | Tree configuration or capacity problems: `InvalidLevels` from `initialize` when the depth is not `TREE_LEVELS`, 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, nor, within `WITHDRAW_FEE_GRACE` of a change, the fee at the rate before it. The notes stay unspent, so you re-prove at the rate in force |
| `ZeroPayout` | The fee would take the whole withdrawal, leaving the recipient nothing |
| `WithdrawFeeTooHigh` | `setWithdrawFeeBps` or `initialize` above `MAX_WITHDRAW_FEE_BPS` |
| `WithdrawFeeChangeTooSoon` | `setWithdrawFeeBps` within `WITHDRAW_FEE_GRACE` of the last change taking effect |
| `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` |
| `ScreeningSignerUnset` | A deposit while the pool names no screening signer, as a pool upgraded from code without screening does |
| `ScreeningExpired` | The screening has expired, or expires more than `MAX_SCREENING_TTL` from now |
| `ScreeningUsed` | The screening's nonce has already been spent |
| `InvalidScreeningSignature` | The signature does not recover to `screeningSigner` for this depositor, pool and chain, or it is not 65 canonical bytes |
| `InvalidScreeningSigner` | `setScreeningSigner` or `initialize` was given the zero address |
| `InvalidAsset`, `DuplicateAsset`, `WrongWrapperCode`, `TooManyAssets` | `addAsset` rejected the wrapper |
| `InvalidWrapperCodehash` | `initialize` was given a zero or empty-account code hash |

A deposit that reverts after its screening passed leaves the nonce unspent, so the same screening
can be used again.

## MerkleTreeWithHistory

`MerkleTreeWithHistory.sol` holds the append-only Poseidon trees the pool inherits.

```solidity theme={null}
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. `isKnownRoot` answers for every root any tree has ever had: none
expires, because the trees are append-only, so an old root only proves leaves that are still there,
and the nullifiers alone stop a note from being spent twice. `getLastRoot()` is the latest root.

When the current tree cannot take a whole batch, the next tree starts at index 0, and the leaves of
the full one stay provable against its final root. `treeNumber()` is the current tree and
`nextIndex()` the next free index in it. A leaf's position, the `index` that `NewCommitment` logs,
is its tree's number above the low `levels` bits and its index in that tree below them, so the
positions of the first tree are plain leaf indices. `TreeIsFull` is left for the case that
positions run out of 32 bits.

`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](https://docs.fluton.io/concepts/notes-and-proofs.md).

## 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](https://docs.fluton.io/reference/circuits.md).

```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](https://docs.fluton.io/reference/circuits.md).

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

## Deposit screening

The pool checks screenings itself; no other contract is involved.

```solidity theme={null}
struct DepositScreening {
    bytes32 nonce;
    uint64 expiresAt;
    bytes signature;
}
```

`signature` is `screeningSigner`'s EIP-712 signature of
`DepositScreening(address depositor,bytes32 nonce,uint64 expiresAt)` in the pool's domain
(`PrivacyPool`, version `1`, this chain id, the pool's address — the domain referral bonuses use,
under another type), with `msg.sender` as the `depositor`. `deposit` and `requestDeposit` check it
before the proof is checked or anything is pulled, spend the nonce and emit
`DepositScreened(depositor, nonce)`. [Deposit screening](https://docs.fluton.io/concepts/deposit-screening.md) explains the
flow.


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