Expand description
Formally Verified Risk Engine for Perpetual DEX — v12.1.0
Implements the v12.1.0 spec: Native 128-bit Architecture.
This module implements a formally verified risk engine that guarantees:
- Protected principal for flat accounts
- PNL warmup prevents instant withdrawal of manipulated profits
- ADL via lazy A/K side indices on the opposing OI side
- Conservation of funds across all operations (V >= C_tot + I)
- No hidden protocol MM — bankruptcy socialization through explicit A/K state only
§Atomicity Model
Public functions suffixed with _not_atomic can return Err after partial
state mutation. Callers MUST abort the entire transaction on Err —
they must not retry, suppress, or continue with mutated state.
On Solana SVM, any Err return from an instruction aborts the transaction
and rolls back all account state automatically. This is the expected
deployment model.
Public functions WITHOUT the suffix (deposit, top_up_insurance_fund,
deposit_fee_credits, accrue_market_to) use validate-then-mutate:
Err means no state was changed.
Internal helpers (enqueue_adl, liquidate_at_oracle_internal, etc.)
are not individually atomic — they rely on the calling _not_atomic
method to propagate Err to the transaction boundary.
Re-exports§
Modules§
Structs§
- Account
- Unified account (spec §2.1)
- Crank
Outcome - Outcome of a keeper crank operation
- Instruction
Context - Instruction context for deferred reset scheduling (spec §5.7-5.8)
- Insurance
Fund - Insurance fund state
- Risk
Engine - Main risk engine state (spec §2.2)
- Risk
Params - Risk engine parameters
Enums§
- Liquidation
Policy - Liquidation policy (spec §10.6)
- Risk
Error - Side
- Determine which side a signed position is on. Positive = long, negative = short.
- Side
Mode - Side mode for OI sides (spec §2.4)
Constants§
- ACCOUNTS_
PER_ CRANK - ADL_ONE
- ADL_ONE = 1_000_000 (spec §1.3)
- BITMAP_
WORDS - GC_
CLOSE_ BUDGET - LIQ_
BUDGET_ PER_ CRANK - MAX_
ABS_ FUNDING_ BPS_ PER_ SLOT - MAX_ABS_FUNDING_BPS_PER_SLOT = 10000 (spec §1.4)
- MAX_
ACCOUNTS - MAX_
ACCOUNT_ NOTIONAL - MAX_
ACCOUNT_ POSITIVE_ PNL - MAX_
FUNDING_ DT - MAX_FUNDING_DT = 65535 (spec §1.4)
- MAX_
LIQUIDATION_ FEE_ BPS - MAX_
MAINTENANCE_ FEE_ PER_ SLOT - MAX_
MARGIN_ BPS - MAX_
MATERIALIZED_ ACCOUNTS - MAX_
OI_ SIDE_ Q - MAX_
ORACLE_ PRICE - MAX_ORACLE_PRICE = 1_000_000_000_000 (spec §1.4)
- MAX_
PNL_ POS_ TOT - MAX_
POSITION_ ABS_ Q - MAX_
PROTOCOL_ FEE_ ABS - MAX_
ROUNDING_ SLACK - MAX_
TRADE_ SIZE_ Q - MAX_
TRADING_ FEE_ BPS - MAX_
VAULT_ TVL - MIN_
A_ SIDE - MIN_A_SIDE = 1_000 (spec §1.4)
- POS_
SCALE - POS_SCALE = 1_000_000 (spec §1.2)
Functions§
- checked_
u128_ mul_ i128 - Multiply a u128 by an i128 returning i128 (checked). Computes u128 * i128 → i128. Used for A_side * delta_p in accrue_market_to.
- compute_
trade_ pnl - Compute trade PnL: floor_div_signed_conservative(size_q * price_diff, POS_SCALE) Uses native i128 arithmetic (spec §1.5.1 shows trade slippage fits in i128).