Skip to main content

RiskEngine

Struct RiskEngine 

Source
#[repr(C)]
pub struct RiskEngine {
Show 45 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 used: [u64; 64], pub num_used_accounts: u16, pub next_account_id: u64, pub free_head: u16, pub next_free: [u16; 4096], pub accounts: [Account; 4096],
}
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)

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

Implementations§

Source§

impl RiskEngine

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 effective_pos_q(&self, idx: usize) -> i128

Compute effective position quantity for account idx.

Source

pub fn accrue_market_to( &mut self, now_slot: u64, oracle_price: u64, ) -> 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_not_atomic (e.g. the resolved-market settlement crank) must invoke this before returning.

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

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 touch_account_full_not_atomic( &mut self, idx: usize, oracle_price: u64, now_slot: u64, ) -> Result<()>

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_not_atomic( &mut self, idx: u16, amount: u128, oracle_price: u64, now_slot: u64, funding_rate: i64, ) -> Result<()>

Source

pub fn settle_account_not_atomic( &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_not_atomic( &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_not_atomic( &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_not_atomic( &mut self, now_slot: u64, oracle_price: u64, ordered_candidates: &[(u16, Option<LiquidationPolicy>)], max_revalidations: u16, funding_rate: i64, ) -> Result<CrankOutcome>

keeper_crank_not_atomic (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 convert_released_pnl_not_atomic( &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_not_atomic( &mut self, idx: u16, now_slot: u64, oracle_price: u64, funding_rate: i64, ) -> Result<u128>

Source

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

Force-close an account on a resolved market.

resolved_slot is the market resolution boundary slot, used to anchor current_slot and realize maintenance fees through that slot.

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.

Source

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

reclaim_empty_account_not_atomic(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 top_up_insurance_fund( &mut self, amount: u128, now_slot: u64, ) -> Result<bool>

Source

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

Withdraw protocol revenue from insurance fund. Enforces: post-withdrawal balance >= params.insurance_floor. Decrements both insurance_fund.balance and vault (tokens leave SPL vault).

Source

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

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