Balance Management
The BalanceManager contract handles all fund custody, balance tracking, and settlement within the CLOB system.Balance States
Funds in the CLOB system exist in two states:| State | Description |
|---|---|
| Available | Funds deposited but not committed to orders |
| Locked | Funds committed to open orders |
Deposit Flow
Token Deposits
ETH Deposits
For native ETH, the system wraps to WETH:Withdrawal Flow
Important: Only available (unlocked) funds can be withdrawn. To withdraw locked funds, cancel the associated orders first.Lock/Unlock Mechanism
Locking Funds
When an order is placed, funds are moved from available to locked:Unlocking Funds
When an order is cancelled, funds return to available:Trade Settlement
When orders match, locked funds are transferred between parties:Fee Structure
Fee Types
| Fee Type | When Applied | Typical Rate |
|---|---|---|
| Maker Fee | Order adds liquidity (resting) | Lower |
| Taker Fee | Order removes liquidity (crossing) | Higher |
Fee Calculation
FEE_UNIT is the fee denominator (e.g., 1,000,000 for basis point precision).
Fee Collection Flow
Fees are deducted atomically during settlement:- Maker receives:
tradeAmount - makerFee - Taker receives:
tradeAmount - takerFee - Fee receiver accumulates both fees
Balance Queries
Available Balance
Locked Balance
Total Balance
A user’s total funds = available + sum(locked across all pools)Security Model
Fund Isolation
- Each user’s funds are tracked separately
- Locked funds are isolated per OrderBook
- No cross-user fund access
Authorization
| Operation | Authorized Callers |
|---|---|
deposit | CLOBRouter |
withdraw | CLOBRouter |
lock | OrderBook (via Router) |
unlock | OrderBook |
transferLockedFrom | OrderBook |
Invariants
The BalanceManager maintains critical invariants:-
Token Balance Invariant
-
User Balance Invariant
-
No Negative Balances
- All balance operations check for sufficient funds
- Underflow-protected arithmetic
Error Handling
| Error | Cause | Resolution |
|---|---|---|
InsufficientBalance | Not enough available funds | Deposit more or cancel orders |
ZeroAmount | Attempted zero-value operation | Use non-zero amount |
UnauthorizedCaller | Caller not in authorized list | Use authorized entry point |
UnauthorizedOperator | Operator not authorized for user | Check operator permissions |
TransferError | Token transfer failed | Check token approval/balance |
NativeTransferFailed | ETH transfer failed | Check recipient can receive ETH |
Events
| Event | Parameters | Description |
|---|---|---|
Deposit | user, currency, amount | Funds deposited |
Withdrawal | user, currency, amount | Funds withdrawn |
Lock | user, currency, amount | Funds locked for order |
Unlock | user, currency, amount | Funds unlocked |
TransferFrom | operator, sender, receiver, currency, amount, fee | Settlement transfer |
TransferLockedFrom | operator, sender, receiver, currency, amount, fee | Locked fund transfer |