A decentralized perpetual futures exchange built on Solana using Anchor framework. This system enables users to trade perpetual futures with leverage, featuring an order book and AMM-based liquidity.
Perp-DEX is a sophisticated perpetual futures trading platform that combines traditional order book mechanics with automated market maker (AMM) liquidity. The system supports leveraged trading, multiple markets, and real-time price feeds through oracles.
The system consists of several key components:
- State Management: Global state and configuration
- Market Management: Individual perpetual futures markets
- User Management: User accounts and positions
- Order Management: Order placement, matching, and execution
- AMM Integration: Automated market maker for liquidity provision
User → Initialize User Account → Deposit Collateral → Ready to Trade
User → Place Order → Order Validation → Order Storage → Order Book Update
Order Types Supported:
- Market Orders: Execute immediately at best available price
- Limit Orders: Execute only at specified price or better
- Direction: Long (buy) or Short (sell)
- Leverage: Configurable leverage up to maximum allowed
Order Matching → Fill Order → Position Update → Collateral Adjustment → Order Status Update
Execution Methods:
- Order Matching: Direct matching with opposite orders
- AMM Liquidity: Filling remaining orders through AMM
- Hybrid: Combination of both methods for optimal execution
Position Creation → Collateral Management → Leverage Control → Risk Management
- Purpose: Initializes the global state of the system
- Parameters:
perp_fee: Fee percentage for perpetual trading
- What it does: Sets up the foundational system parameters and fee structure
- Purpose: Creates a new perpetual futures market
- Parameters: Market configuration including reserves, leverage limits, and margin requirements
- What it does:
- Creates market account with AMM configuration
- Sets up market vault for token storage
- Configures maximum leverage and margin ratios
- Initializes AMM with base and quote asset reserves
- Purpose: Creates a new user account for trading
- Parameters:
account_id: Unique identifier for the user account
- What it does:
- Creates user account with order management capabilities
- Initializes order tracking and position management
- Sets up user authority and account structure
- Purpose: Places a new trading order
- Parameters: Order details including price, amount, direction, leverage, and market
- What it does:
- Validates order parameters (amount, leverage, price limits)
- Creates order record in user's order book
- Updates user's position tracking
- Manages order ID generation and status
- Purpose: Executes order matching and filling
- Parameters:
order_id: Specific order to fill (optional, defaults to last order)
- What it does:
- Identifies matching orders across users
- Executes trades through order matching or AMM
- Updates positions and collateral balances
- Manages order status and fill amounts
- Purpose: Deposits collateral into a specific market
- Parameters:
market_index: Target market identifieramount: Token amount to deposit
- What it does:
- Transfers tokens to market vault
- Updates user's collateral balance
- Creates or updates market position
- Purpose: Withdraws collateral from a market position
- Parameters:
market_index: Source market identifieramount: Token amount to withdraw
- What it does:
- Validates withdrawal eligibility
- Transfers tokens from vault to user
- Updates collateral balances and positions
- Purpose: Sets up price oracle for a market
- What it does: Configures price feed with confidence intervals and deviation limits
- Purpose: Updates current market price from oracle
- What it does: Refreshes price data and triggers AMM price updates
The Automated Market Maker (AMM) provides continuous liquidity for the perpetual futures markets:
Key Features:
- Constant Product Formula: Uses x * y = k formula for price discovery
- Oracle Price Weighting: Combines AMM pricing with oracle feeds for stability
- Dynamic Reserves: Automatically adjusts base and quote asset reserves
- Price Impact Calculation: Determines price impact based on trade size
- Funding Rate Mechanism: Implements funding rate calculations for perpetual markets
AMM Functions:
calculate_quote_for_base_with_limit: Calculates quote amount with price limitscalculate_quote_for_base_no_limit: Calculates quote amount without price limitsexecute_trade: Executes trades and updates reservesget_bid_price/get_ask_price: Provides current bid/ask prices
The system intelligently chooses between:
- Direct Order Matching: When better prices exist in the order book
- AMM Liquidity: For remaining unfilled amounts or when AMM provides better pricing
- Hybrid Approach: Optimal combination of both methods
The get_types_of_filling function determines the optimal execution strategy for each order by analyzing available liquidity sources:
Function Purpose: Analyzes order book and AMM to determine the best execution path Parameters:
order: The order to be filledmaker_id_index_price: Available maker orders with pricesamm: Current AMM state and pricinglimit_price: Optional price limit for the taker
Execution Strategy:
- Maker Order Analysis: Evaluates each available maker order for price improvement
- Price Comparison: Compares maker prices against AMM pricing
- Crossing Logic: Determines if orders can cross (taker willing to pay maker's price)
- Priority Ranking: Orders execution methods by price priority (best first)
- AMM Fallback: Uses AMM liquidity for remaining unfilled amounts
Return Value: Vector of FullfillmentMethod enum values:
AMM(Option<u64>): AMM execution with optional price limitMatch(Pubkey, u16, u64): Direct order matching with maker details
Purpose: Executes order filling through the Automated Market Maker Parameters:
user: User account with the orderorder_index: Index of the order to filllimit_price: Optional maximum price for the fillmarket: Market account with AMM configuration
What it does:
- Amount Calculation: Determines base asset amount to fill
- Quote Calculation: Computes required quote asset amount based on AMM pricing
- Price Validation: Ensures fill price meets limit requirements
- AMM Execution: Executes the trade through the AMM algorithm
- Order Update: Updates order status and fill amounts
- Position Tracking: Maintains accurate position records
Return Value: Tuple of (base_asset_amount_filled, quote_asset_amount_filled)
fill_with_match(taker, taker_order_index, taker_limit_price, maker, maker_order_index, maker_price, maker_fill_map)
Purpose: Executes direct order matching between taker and maker orders Parameters:
taker: User placing the order to be filledtaker_order_index: Index of taker's ordertaker_limit_price: Maximum price taker is willing to paymaker: User with the opposite ordermaker_order_index: Index of maker's ordermaker_price: Price of maker's ordermaker_fill_map: Tracking map for maker fills
What it does:
- Direction Validation: Ensures orders are in opposite directions (long vs short)
- Crossing Check: Verifies if orders can cross at maker's price
- Fill Calculation: Determines fillable amounts for both orders
- Order Updates: Updates both taker and maker order status
- Fill Tracking: Maintains maker fill map for position calculations
- Status Management: Updates order status to filled when complete
Return Value: Tuple of (base_asset_amount_filled, quote_asset_amount_filled)
Purpose: Updates order status and fill amounts after execution What it does:
- Increments filled amounts for base and quote assets
- Updates order status to "Filled" when completely filled
- Maintains accurate order tracking
Purpose: Calculates the actual fillable amounts between two orders What it does:
- Determines the minimum fillable amount between maker and taker
- Calculates corresponding quote asset amount based on maker's price
- Ensures no over-filling occurs
Purpose: Determines if an order can cross at the given price Logic:
- Long Orders: Cross when taker's limit price > maker's ask price
- Short Orders: Cross when taker's limit price < maker's bid price
- Order Analysis:
get_types_of_fillinganalyzes available liquidity - Method Selection: Chooses optimal execution path (matching vs AMM)
- Order Execution:
- Direct matching via
fill_with_match - AMM liquidity via
fill_with_amm
- Direct matching via
- Status Updates: Updates order status and fill amounts
- Position Tracking: Maintains accurate position records
- Orders are filled based on price priority (best price first)
- Market orders execute immediately at best available prices
- Limit orders only execute when price conditions are met
- Solana Native: Built on Solana blockchain for high performance
- Anchor Framework: Leverages Anchor for secure smart contract development
- Token Standards: SPL token integration for asset management
- Account Management: PDA-based account structure for security
- Error Handling: Comprehensive error management and validation
- Setup Environment: Install Solana CLI and Anchor
- Build:
anchor build - Deploy:
anchor deploy - Initialize: Set up state, markets, and oracles
- Trade: Start placing and filling orders
- Authority Validation: Strict user authority checks
- Parameter Validation: Comprehensive input validation
- Arithmetic Safety: Overflow protection and safe math operations
- Access Control: Restricted access to administrative functions
This system provides a robust foundation for decentralized perpetual futures trading with advanced order management, risk controls, and liquidity provision mechanisms.