Skip to content

Add perpetual futures exchange example in Anchor and Quasar#47

Open
mikemaccana wants to merge 1 commit into
mainfrom
claude/perpetual-futures-solana-PqgNj
Open

Add perpetual futures exchange example in Anchor and Quasar#47
mikemaccana wants to merge 1 commit into
mainfrom
claude/perpetual-futures-solana-PqgNj

Conversation

@mikemaccana

Copy link
Copy Markdown
Collaborator

Summary

This PR adds a complete perpetual futures exchange implementation as a teaching example, provided in two parallel implementations: one using Anchor and one using Quasar. The exchange allows users to make leveraged bets on asset prices without owning the underlying asset, with liquidity providers funding the pool and serving as counterparties to traders.

Key Changes

Core Program Implementation (Anchor)

  • perpetual-futures program: Full exchange implementation with pool creation, liquidity provision, position management, funding accrual, and liquidation
  • mock-switchboard program: Test-only oracle feed for price data
  • Comprehensive LiteSVM-based test suite (1000+ lines) covering all major operations

Core Program Implementation (Quasar)

  • Parallel quasar-perpetual-futures implementation with identical design and behavior to the Anchor version
  • Quasar-specific test suite using quasar-svm

Instructions (both implementations)

  • initialize_pool: Create a market for a collateral token priced by an oracle feed
  • add_liquidity / remove_liquidity: Liquidity provider operations
  • open_position / close_position: Trader leverage operations
  • liquidate_position: Liquidation of unhealthy positions
  • collect_fees: Protocol fee collection

Shared Logic

  • Oracle price reading with staleness and confidence validation
  • Position profit/loss and funding calculations
  • Basis-point fee computation
  • Liquidity provider AUM calculations

Documentation

  • Comprehensive README explaining the design, oracle integration, and key concepts
  • Terminology guide for perpetual futures concepts
  • Solana-Anchor coding skill guide with Rust, TypeScript, and general guidelines

Notable Implementation Details

  • No decimals assumption: The pool works with raw base units; transfer_checked carries decimal information through all CPIs
  • Fixed-point math: All calculations use checked arithmetic with multiply-before-divide ordering to prevent precision loss
  • Funding mechanism: Per-slot funding accrual charged to the heavier side (long or short)
  • Liquidation: Positions become liquidatable when equity falls below maintenance margin; liquidators receive a fee
  • Oracle validation: Prices are validated for freshness (staleness), positivity, and confidence band width
  • Parallel implementations: Anchor and Quasar versions share identical design and behavior, enabling comparison of different Solana frameworks

The implementation serves as a reference for building oracle-priced, LP-pool perpetual futures exchanges on Solana, following the design patterns used by Jupiter Perpetuals and GMX.

https://claude.ai/code/session_01YNkQe8eneL4FxCu96kmjVr

…r + Quasar)

Adds a perpetual-futures exchange example under finance/perpetual-futures/,
modelled on the oracle-priced, pool-collateralized design used by Jupiter
Perpetuals and GMX (and the open-source solana-labs/perpetuals reference that
Adrena and Flash Trade fork). Liquidity providers fund a shared pool and are the
counterparty to every trade; traders open leveraged long or short positions
priced at a Switchboard oracle, pay open/close and funding fees, and are
liquidated permissionlessly once their equity falls below the maintenance
margin.

Both framework implementations expose the same seven instruction handlers —
initialize_pool, add_liquidity, remove_liquidity, open_position,
close_position, liquidate_position, collect_fees — and share the same design:

- Liquidity-provider shares priced against mark-to-market assets-under-management
  derived from per-side open-interest accumulators, so an exiting provider
  cannot dodge an in-flight trader profit.
- Reserved-liquidity solvency model: each open position reserves its notional
  size, an open is allowed only while the reserve stays backed by liquidity
  (which also caps open interest), recoverable profit is capped at the reserve so
  a winner can always be paid, and liquidity-provider withdrawals can take only
  the unreserved remainder.
- A cumulative funding index in which the heavier open-interest side pays the
  pool over time.
- Oracle reads validated for staleness (by slot), positivity, scale, and a
  confidence band that must stay within a per-pool maximum.
- All money math in u128 with checked arithmetic, multiply-before-divide,
  rounding toward the protocol; transfer_checked; checks-effects-interactions;
  slippage bounds on every state-changing handler.

Anchor (finance/perpetual-futures/anchor): a perpetual-futures program plus a
mock-switchboard companion program that supplies a deterministic price+confidence
feed for tests and documents the swap-in point for a real Switchboard On-Demand
feed. Covered by 22 LiteSVM integration tests.

Quasar (finance/perpetual-futures/quasar): a port with 12 quasar-svm tests. It
keeps one position per (pool, owner) because Quasar's address constraint can
reference account inputs but not instruction arguments, so the side is stored in
the position rather than used as a seed; the oracle feed is supplied directly in
tests rather than via a companion program.

Docs: a finance-oriented README following the repository's program-flow format
(participants, sample USDC/NVDAx tokens, per-step instruction and account
tables) with concept links, a terminology glossary, design notes relating the
example to percolator and solana-labs/perpetuals, and a Financial Software entry
in the root README.

Also commits the QuickNode Solana coding skill under .claude/skills/ (with a
tracked .gitignore exception) so it is available in Claude Code web sessions.

https://claude.ai/code/session_01YNkQe8eneL4FxCu96kmjVr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants