Skip to main content
kimia-perp is the core derivatives program. It owns the orderbook, tracks all positions and funding, validates Pyth Hermes oracle posts, and runs the spot pool that delta-vault hedges against.

Accounts

ExchangeConfig

Singleton. ["exchange_config"].
FieldTypeNotes
adminPubkeyCurrent admin
pending_adminPubkeyTwo-step transfer target
exchange_pausedboolGlobal pause
bumpu8

Market

One per market. ["market", market_index_le].
FieldTypeNotes
adminPubkey
market_indexu160 = SOL-PERP (V1)
statusMarketStatusInitialized, Active, Paused, Settlement
oraclePubkeyPyth PriceUpdateV2 feed account
oracle_staleness_thresholdi64seconds
oracle_confidence_max_bpsu16bps
initial_margin_ratiou32bps of MARGIN_PRECISION (10k)
maintenance_margin_ratiou32bps
taker_fee_bps, maker_fee_bps, liquidation_fee_bpsu16
funding_periodi64default 3600s
last_funding_updatei64
cumulative_funding_rate_longi128
cumulative_funding_rate_shorti128
mark_twap, oracle_twapu646-decimal
total_long_base, total_short_base, open_interestu649-decimal
collateral_vault, insurance_vault, fee_vaultPubkeySPL token accounts
collateral_mintPubkeyUSDC mint
insurance_fund_balance, total_fees_collectedu64
tick_sizeu64orderbook price increment

UserAccount

["user", authority].
FieldTypeNotes
authorityPubkeyOwner
delegatePubkeyOptional trading delegate (cannot withdraw)
collateralu64USDC, 6-decimal
market_indexu16
base_amounti64signed, 9-decimal
quote_entryi646-decimal
last_cumulative_funding_ratei128for lazy settlement
realized_pnl, total_fees_paid, total_reserved_margin

Orderbook

Zero-copy. ["orderbook", market_index_le].
  • Max 32 bids (sorted descending) and 32 asks (sorted ascending).
  • FIFO within price.
  • Order { owner, order_id, price, base_remaining, reserved_margin, direction, is_active }.

SpotPool

["spot_pool", base_mint, quote_mint]. Simple oracle-priced wSOL/USDC pool used by delta-vault. Swaps at oracle ± spread_bps; no curve.

Instructions

InstructionWhoPurpose
initialize_exchangefirst adminOne-time setup
propose_admin / accept_adminadmin / new_adminTwo-step transfer
initialize_marketadminCreate market and its vaults
update_market_paramsadminAdjust fees, margin, oracle thresholds (not oracle account)
pause_market / resume_marketadminLifecycle
set_delegateuserAllow a vault / keeper to trade on user’s behalf
initialize_user_accountuserCreate position account
deposit_collateraluser or delegateAdd USDC
withdraw_collateraluser onlyRemove USDC, checks margin post-op
initialize_orderbookadminEmpty book
place_orderuser or delegateReserve margin → match (up to 4 fills) → insert resting order
cancel_order / cancel_all_ordersuser or delegateRemove, refund margin
update_funding_rateanyoneKeeper crank; TWAPs + funding delta
settle_fundinganyoneLazy settlement for a user
liquidateanyoneClose an underwater position, cancel orders, split fee
initialize_spot_pool / seed_spot_pooladminSet up wSOL/USDC pool
spot_swapanyoneOracle-priced swap (± spread)

place_order

PlaceOrderParams { price, base_amount, direction, post_only, is_market, max_slippage_bps }.
  1. Validate oracle and clamp mark price to oracle ± 10%.
  2. Reserve notional × initial_margin_ratio out of free_collateral().
  3. If is_market, walk the book up to 4 fills:
    • skip self-trades
    • apply taker fee (to fee_vault)
    • adjust both counterparties’ base_amount and quote_entry
    • emit OrderFilled
  4. Any remainder becomes a resting order (if not post_only and not market).

liquidate

  1. Validate oracle.
  2. health ≤ 0 check (NotLiquidatable otherwise).
  3. Cancel all resting orders, their reserved margin goes to insurance_vault.
  4. Close the full position at oracle price.
  5. Charge 5% liquidation fee: 2.5% to liquidator, 2.5% to insurance.
  6. If collateral insufficient, drain insurance fund. If still insufficient, emit BadDebtDetected and pause the market.

Events

MarketInitialized, PositionOpened, PositionClosed, FundingRateUpdated, FundingSettled, CollateralDeposited, CollateralWithdrawn, Liquidated, OrderPlaced, OrderFilled, OrderCancelled, MarkPriceUpdated, SelfTradeSkipped, BadDebtDetected, SpotPoolInitialized, SpotSwapped.

Error codes

See errors reference. The main buckets: 6000..6002 oracle, 6010..6012 market, 6020..6022 margin, 6030..6033 position, 6040..6041 funding, 6050..6051 liquidation, 6110..6117 orderbook.

Funding rate concept

Formula, clamp, and settlement.

Trade a perpetual

Walkthrough.