Skip to main content

RiskEngine

Struct RiskEngine 

Source
#[repr(C)]
pub struct RiskEngine {
Show 46 fields pub vault: U128, pub insurance_fund: InsuranceFund, pub params: RiskParams, pub current_slot: u64, pub funding_rate_bps_per_slot_last: i64, pub last_crank_slot: u64, pub max_crank_staleness_slots: u64, pub c_tot: U128, pub pnl_pos_tot: u128, pub pnl_matured_pos_tot: u128, pub liq_cursor: u16, pub gc_cursor: u16, pub last_full_sweep_start_slot: u64, pub last_full_sweep_completed_slot: u64, pub crank_cursor: u16, pub sweep_start_idx: u16, pub lifetime_liquidations: u64, pub adl_mult_long: u128, pub adl_mult_short: u128, pub adl_coeff_long: i128, pub adl_coeff_short: i128, pub adl_epoch_long: u64, pub adl_epoch_short: u64, pub adl_epoch_start_k_long: i128, pub adl_epoch_start_k_short: i128, pub oi_eff_long_q: u128, pub oi_eff_short_q: u128, pub side_mode_long: SideMode, pub side_mode_short: SideMode, pub stored_pos_count_long: u64, pub stored_pos_count_short: u64, pub stale_account_count_long: u64, pub stale_account_count_short: u64, pub phantom_dust_bound_long_q: u128, pub phantom_dust_bound_short_q: u128, pub materialized_account_count: u64, pub last_oracle_price: u64, pub last_market_slot: u64, pub funding_price_sample_last: u64, pub insurance_floor: u128, pub used: [u64; 1], pub num_used_accounts: u16, pub next_account_id: u64, pub free_head: u16, pub next_free: [u16; 64], pub accounts: [Account; 64],
}
Expand description

Main risk engine state (spec §2.2)

Fields§

§vault: U128§insurance_fund: InsuranceFund§params: RiskParams§current_slot: u64§funding_rate_bps_per_slot_last: i64

Stored funding rate for anti-retroactivity

§last_crank_slot: u64§max_crank_staleness_slots: u64§c_tot: U128§pnl_pos_tot: u128§pnl_matured_pos_tot: u128§liq_cursor: u16§gc_cursor: u16§last_full_sweep_start_slot: u64§last_full_sweep_completed_slot: u64§crank_cursor: u16§sweep_start_idx: u16§lifetime_liquidations: u64§adl_mult_long: u128§adl_mult_short: u128§adl_coeff_long: i128§adl_coeff_short: i128§adl_epoch_long: u64§adl_epoch_short: u64§adl_epoch_start_k_long: i128§adl_epoch_start_k_short: i128§oi_eff_long_q: u128§oi_eff_short_q: u128§side_mode_long: SideMode§side_mode_short: SideMode§stored_pos_count_long: u64§stored_pos_count_short: u64§stale_account_count_long: u64§stale_account_count_short: u64§phantom_dust_bound_long_q: u128

Dynamic phantom dust bounds (spec §4.6, §5.7)

§phantom_dust_bound_short_q: u128§materialized_account_count: u64

Materialized account count (spec §2.2)

§last_oracle_price: u64

Last oracle price used in accrue_market_to

§last_market_slot: u64

Last slot used in accrue_market_to

§funding_price_sample_last: u64

Funding price sample (for anti-retroactivity)

§insurance_floor: u128

Insurance floor (spec §4.7)

§used: [u64; 1]§num_used_accounts: u16§next_account_id: u64§free_head: u16§next_free: [u16; 64]§accounts: [Account; 64]

Implementations§

Source§

impl RiskEngine

Source

pub fn new(params: RiskParams) -> Self

Create a new risk engine for testing. Initializes with init_oracle_price = 1 (spec §2.7 compliant).

Source

pub fn new_with_market( params: RiskParams, init_slot: u64, init_oracle_price: u64, ) -> Self

Create a new risk engine with explicit market initialization (spec §2.7). Requires 0 < init_oracle_price <= MAX_ORACLE_PRICE per spec §1.2.

Source

pub fn init_in_place( &mut self, params: RiskParams, init_slot: u64, init_oracle_price: u64, )

Initialize in place (for Solana BPF zero-copy, spec §2.7). Fully canonicalizes all state — safe even on non-zeroed memory.

Source

pub fn is_used(&self, idx: usize) -> bool

Source

pub fn free_slot(&mut self, idx: u16)

Source

pub fn set_pnl(&mut self, idx: usize, new_pnl: i128)

Source

pub fn set_reserved_pnl(&mut self, idx: usize, new_r: u128)

Source

pub fn consume_released_pnl(&mut self, idx: usize, x: u128)

Source

pub fn set_capital(&mut self, idx: usize, new_capital: u128)

Source

pub fn set_position_basis_q(&mut self, idx: usize, new_basis: i128)

Source

pub fn attach_effective_position(&mut self, idx: usize, new_eff_pos_q: i128)

Source

pub fn effective_pos_q(&self, idx: usize) -> i128

Compute effective position quantity for account idx.

Source

pub fn settle_side_effects(&mut self, idx: usize) -> Result<()>

Source

pub fn accrue_market_to( &mut self, now_slot: u64, oracle_price: u64, ) -> Result<()>

Source

pub fn recompute_r_last_from_final_state( &mut self, externally_computed_rate: i64, ) -> Result<()>

Source

pub fn run_end_of_instruction_lifecycle( &mut self, ctx: &mut InstructionContext, funding_rate: i64, ) -> Result<()>

Public entry-point for the end-of-instruction lifecycle (spec §10.0 steps 4-7 / §10.8 steps 9-12).

Runs schedule_end_of_instruction_resets, finalize, and recompute_r_last_from_final_state in the canonical order. Callers that bypass keeper_crank (e.g. the resolved-market settlement crank) must invoke this before returning.

Source

pub fn absorb_protocol_loss(&mut self, loss: u128)

Source

pub fn enqueue_adl( &mut self, ctx: &mut InstructionContext, liq_side: Side, q_close_q: u128, d: u128, ) -> Result<()>

Source

pub fn begin_full_drain_reset(&mut self, side: Side)

Source

pub fn finalize_side_reset(&mut self, side: Side) -> Result<()>

Source

pub fn schedule_end_of_instruction_resets( &mut self, ctx: &mut InstructionContext, ) -> Result<()>

Source

pub fn finalize_end_of_instruction_resets(&mut self, ctx: &InstructionContext)

Source

pub fn haircut_ratio(&self) -> (u128, u128)

Compute haircut ratio (h_num, h_den) as u128 pair (spec §3.3) Uses pnl_matured_pos_tot as denominator per v12.0.2.

Source

pub fn effective_matured_pnl(&self, idx: usize) -> u128

PNL_eff_matured_i (spec §3.3): haircutted matured released positive PnL

Source

pub fn account_equity_maint_raw(&self, account: &Account) -> i128

Eq_maint_raw_i (spec §3.4): C_i + PNL_i - FeeDebt_i in exact widened signed domain. For maintenance margin and one-sided health checks. Uses full local PNL_i. Returns i128. Negative overflow is projected to i128::MIN + 1 per §3.4 (safe for one-sided checks against nonneg thresholds). For strict before/after buffer comparisons, use account_equity_maint_raw_wide.

Source

pub fn account_equity_maint_raw_wide(&self, account: &Account) -> I256

Eq_maint_raw_i in exact I256 (spec §3.4 “transient widened signed type”). MUST be used for strict before/after raw maintenance-buffer comparisons (§10.5 step 29). No saturation or clamping.

Source

pub fn account_equity_net(&self, account: &Account, _oracle_price: u64) -> i128

Eq_net_i (spec §3.4): max(0, Eq_maint_raw_i). For maintenance margin checks.

Source

pub fn account_equity_init_raw(&self, account: &Account, idx: usize) -> i128

Eq_init_raw_i (spec §3.4): C_i + min(PNL_i, 0) + PNL_eff_matured_i - FeeDebt_i For initial margin and withdrawal checks. Uses haircutted matured PnL only. Returns i128. Negative overflow projected to i128::MIN + 1 per §3.4.

Source

pub fn account_equity_init_net(&self, account: &Account, idx: usize) -> i128

Eq_init_net_i (spec §3.4): max(0, Eq_init_raw_i). For IM/withdrawal checks.

Source

pub fn notional(&self, idx: usize, oracle_price: u64) -> u128

notional (spec §9.1): floor(|effective_pos_q| * oracle_price / POS_SCALE)

Source

pub fn is_above_maintenance_margin( &self, account: &Account, idx: usize, oracle_price: u64, ) -> bool

is_above_maintenance_margin (spec §9.1): Eq_net_i > MM_req_i Per spec §9.1: if eff == 0 then MM_req = 0; else MM_req = max(proportional, MIN_NONZERO_MM_REQ)

Source

pub fn is_above_initial_margin( &self, account: &Account, idx: usize, oracle_price: u64, ) -> bool

is_above_initial_margin (spec §9.1): exact Eq_init_raw_i >= IM_req_i Per spec §9.1: if eff == 0 then IM_req = 0; else IM_req = max(proportional, MIN_NONZERO_IM_REQ) Per spec §3.4: MUST use exact raw equity, not clamped Eq_init_net_i, so negative raw equity is distinguishable from zero.

Source

pub fn check_conservation(&self) -> bool

Source

pub fn released_pos(&self, idx: usize) -> u128

released_pos (spec §2.1): ReleasedPos_i = max(PNL_i, 0) - R_i

Source

pub fn restart_warmup_after_reserve_increase(&mut self, idx: usize)

Source

pub fn advance_profit_warmup(&mut self, idx: usize)

Source

pub fn fee_debt_sweep(&mut self, idx: usize)

Source

pub fn touch_account_full( &mut self, idx: usize, oracle_price: u64, now_slot: u64, ) -> Result<()>

Source

pub fn add_user(&mut self, fee_payment: u128) -> Result<u16>

Source

pub fn add_lp( &mut self, matching_engine_program: [u8; 32], matching_engine_context: [u8; 32], fee_payment: u128, ) -> Result<u16>

Source

pub fn set_owner(&mut self, idx: u16, owner: [u8; 32]) -> Result<()>

Source

pub fn deposit( &mut self, idx: u16, amount: u128, _oracle_price: u64, now_slot: u64, ) -> Result<()>

Source

pub fn withdraw( &mut self, idx: u16, amount: u128, oracle_price: u64, now_slot: u64, funding_rate: i64, ) -> Result<()>

Source

pub fn settle_account( &mut self, idx: u16, oracle_price: u64, now_slot: u64, funding_rate: i64, ) -> Result<()>

Top-level settle wrapper per spec §10.7. If settlement is exposed as a standalone instruction, this wrapper MUST be used.

Source

pub fn execute_trade( &mut self, a: u16, b: u16, oracle_price: u64, now_slot: u64, size_q: i128, exec_price: u64, funding_rate: i64, ) -> Result<()>

Source

pub fn liquidate_at_oracle( &mut self, idx: u16, now_slot: u64, oracle_price: u64, policy: LiquidationPolicy, funding_rate: i64, ) -> Result<bool>

Top-level liquidation: creates its own InstructionContext and finalizes resets. Accepts LiquidationPolicy per spec §10.6.

Source

pub fn keeper_crank( &mut self, now_slot: u64, oracle_price: u64, ordered_candidates: &[(u16, Option<LiquidationPolicy>)], max_revalidations: u16, funding_rate: i64, ) -> Result<CrankOutcome>

keeper_crank (spec §10.8): Minimal on-chain permissionless shortlist processor. Candidate discovery is performed off-chain. ordered_candidates[] is untrusted. Each candidate is (account_idx, optional liquidation policy hint).

Source

pub fn validate_keeper_hint( &self, idx: u16, eff: i128, hint: &Option<LiquidationPolicy>, oracle_price: u64, ) -> Option<LiquidationPolicy>

Source

pub fn convert_released_pnl( &mut self, idx: u16, x_req: u128, oracle_price: u64, now_slot: u64, funding_rate: i64, ) -> Result<()>

Explicit voluntary conversion of matured released positive PnL for open-position accounts.

Source

pub fn close_account( &mut self, idx: u16, now_slot: u64, oracle_price: u64, funding_rate: i64, ) -> Result<u128>

Source

pub fn force_close_resolved(&mut self, idx: u16) -> Result<u128>

Force-close an account on a resolved market.

Settles K-pair PnL, zeros position, settles losses, absorbs from insurance, converts profit (bypassing warmup), sweeps fee debt, forgives remainder, returns capital, frees slot.

Skips accrue_market_to (market is frozen). Handles both same-epoch and epoch-mismatch accounts. For epoch-mismatch where the normal settle_side_effects would reject due to side mode, falls back to manual K-pair settlement using the same wide arithmetic.

Source

pub fn reclaim_empty_account(&mut self, idx: u16, now_slot: u64) -> Result<()>

reclaim_empty_account(i, now_slot) — permissionless O(1) empty/dust-account recycling. Spec §10.7: MUST NOT call accrue_market_to, MUST NOT mutate side state, MUST NOT materialize any account. Realizes recurring maintenance fees on the already-flat state before checking final reclaim eligibility.

Source

pub fn garbage_collect_dust(&mut self) -> u32

Source

pub fn top_up_insurance_fund( &mut self, amount: u128, now_slot: u64, ) -> Result<bool>

Source

pub fn deposit_fee_credits( &mut self, idx: u16, amount: u128, now_slot: u64, ) -> Result<()>

Source

pub fn add_fee_credits(&mut self, idx: u16, amount: u128) -> Result<()>

Source

pub fn recompute_aggregates(&mut self)

Source

pub fn advance_slot(&mut self, slots: u64)

Source

pub fn count_used(&self) -> u64

Trait Implementations§

Source§

impl Clone for RiskEngine

Source§

fn clone(&self) -> RiskEngine

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RiskEngine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for RiskEngine

Source§

fn eq(&self, other: &RiskEngine) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for RiskEngine

Source§

impl StructuralPartialEq for RiskEngine

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.