Skip to main content
Kimia relies on two Rust crates for on-chain math: perps-math (perps engine) and kimia-math (everything else). Both use 9-decimal fixed-point internally and always round down.

Constants

perps-math

funding

  • calculate_funding_rate(mark_twap, oracle_twap, oracle_price) → i128
  • calculate_funding_payment(base, funding_delta) → i64
  • update_twap(twap, price, elapsed, period) → u64

margin

  • calculate_margin_requirement(base, price, margin_ratio) → u64
  • calculate_health(collateral, pnl, maint_req) → i64
  • has_sufficient_initial_margin(...)
  • max_position_size(collateral, price, initial_margin_ratio) → u64
  • calculate_liquidation_price(base, entry, collateral, maint_margin_ratio) → u64

pnl

  • calculate_unrealized_pnl(base, mark, quote_entry) → i64
  • settle_close(base, quote_entry, close_amount, close_price) → (realized_pnl, new_base, new_quote)

safe_math

All returning Option<T>, no panics:
  • mul_div_down / mul_div_up
  • apply_bps_down / apply_bps_up
  • base_to_quote(base, price)
  • normalize_pyth_price(pyth_price, pyth_expo, target_expo)

kimia-math

Fixed-point

  • mul_fp(a, b) = a · b / ONE, u128 intermediate
  • div_fp(a, b) = a · ONE / b
  • ONE = 1_000_000_000
  • signed_delta(new, old), for yield deltas (negative means no yield)

exp / ln (exp_ln.rs)

  • ln_fp(x), range-reduced to [0.5, 2.0) via Taylor on z = (x-1)/(x+1)
  • exp_fp(x), range-reduced via powers of 2
  • pow_frac(base, exponent), exp(exponent · ln(base)) for exponent ∈ [0, ONE]
Validated precision: < 0.05% error across the full yield-AMM operating range.

insurance

  • process_positive_funding(funding, skim_bps) → (insurance_skim, vault_yield)
  • process_negative_funding(fund_balance, loss) → (new_balance, uncovered_loss)