
The Future of Perpetual Trading
A self-contained perpetual DEX engine that lives in one Solana account slab. Built for low latency, high throughput, and maximum capital efficiency.
Built Because Toly Wanted It
When Solana's co-founder calls for innovation, we answer.
"Pls steal the idea. I want to see if it's possible to replicate the same prop-amm competition for spot but for perps."
1)A perp DEX program that just uses one slab of memory in an account for everything with its own LP/risk/matching engine
2)A router that can rebalance positions between any number of them

Anatoly Yakovenko (toly)
Co-founder of Solana
PFORK is the answer.
A high-performance perpetual DEX engine built exactly to Toly's specifications—single-account architecture, integrated matching and risk engines, and router-ready design.
Built for Performance
Every component optimized for speed, efficiency, and reliability on Solana
Single Account Slab
All order data, LP pools, and positions in one Solana account for maximum efficiency and low latency.
Lightning Fast Matching
Binary heap-based matching engine with composable market support for instant order execution.
Built-in Risk Engine
Automated funding rates, margin calculation, and PnL settlement with oracle integration.
Dynamic LP Logic
Portfolio margin across all positions with AMM curves that adapt to volatility regimes.
Core Architecture
Modular design for maximum flexibility and performance
Memory Layout
Single account slab architecture for all order data, LP pools, and positions with unified deserialization.
Matching Engine
Binary heap or radix tree for per-market order matching with composable market support.
Risk Engine
Built-in funding rate updates, margin calculation, and PnL settlement with rolling TWAP oracles.
Prop Router
Aggregates multiple Percolator instances with intelligent position routing and cross-instance rebalancing.
Powered by
Complete Technical Specification
Deep dive into PFORK's architecture, implementation details, and technical design decisions. Built to answer Toly's call for a high-performance perpetual DEX on Solana.
System Overview
PFORK (Percolator Fork) is a self-contained perpetual DEX engine that lives in one Solana account slab for low latency and on-chain compute efficiency. It handles LP, risk, matching, and position management internally, providing a complete trading infrastructure in a single program. The architecture is inspired by traditional exchange designs but optimized for Solana's parallel execution model.
All data in one Solana slab for maximum efficiency and minimal memory access overhead
Matching, risk, and LP logic built-in with no external dependencies
Designed for multi-instance aggregation and cross-market optimization
Core Modules
Memory Layout & Slab Architecture
Efficient single-account slab architecture for high-performance trading with minimal compute overhead
Single Account Slab Design
Uses OpenBook or Phoenix-style architecture where all order data lives in one contiguous memory space. This eliminates the need for multiple account lookups and reduces transaction complexity. The slab is divided into fixed-size chunks for different data types (orders, positions, LP state) with efficient pointer-based navigation.
Unified Serialization Strategy
LP pools, risk parameters, and positions are serialized within the same slab for optimal cache locality. This design ensures that related data is stored together in memory, reducing CPU cache misses and improving overall throughput. The serialization format uses Borsh for efficient encoding/decoding with minimal overhead.
Single Deserialization Path
Maintains high TPS by minimizing memory access patterns and reducing compute overhead. The entire slab is deserialized once per transaction, and all operations work with in-memory references. This approach is critical for achieving sub-millisecond execution times on Solana's runtime.
Memory Management & Garbage Collection
Implements a custom allocator within the slab to manage free space efficiently. Closed orders and settled positions are marked for reuse rather than deleted, preventing memory fragmentation. A periodic compaction process runs during low-activity periods to optimize memory layout.
Matching Engine
High-performance order matching with composable market support and advanced order types
Binary Heap & Radix Tree Implementation
Implements efficient data structures inside the slab for per-market order matching with O(log n) complexity. The binary heap maintains price-time priority for limit orders, while a radix tree provides O(1) lookups for order cancellations and modifications. This hybrid approach balances insertion speed with query performance.
Composable Market Architecture
Each market uses the same code path but operates at a different offset within the slab, enabling unlimited market support without code duplication. Markets can be added dynamically by allocating a new section of the slab and initializing the matching engine state. This design allows for efficient multi-market operations within a single transaction.
Price-Time Priority Matching
Orders are matched based on price priority first, then time priority for fair execution. Market orders are matched immediately against the best available liquidity, while limit orders are placed in the order book at their specified price level. The matching algorithm ensures deterministic execution and prevents front-running.
Advanced Order Types
Supports limit orders, market orders, post-only orders, fill-or-kill (FOK), and immediate-or-cancel (IOC) orders. Stop-loss and take-profit orders are implemented using trigger conditions that are evaluated on each price update. Iceberg orders allow large positions to be executed with minimal market impact by revealing only a portion of the total size.
Cross-Market Matching
The matching engine can execute trades across multiple markets in a single transaction, enabling complex strategies like spread trading and arbitrage. Cross-market orders are validated atomically to ensure consistency and prevent partial fills that could leave the user in an unintended position.
Risk Engine & Margin System
Built-in risk management with real-time margin calculations and automated liquidations
Dynamic Funding Rate Mechanism
Automatic funding rate calculations and settlements based on market conditions and position imbalances. The funding rate is computed every hour using the difference between the perpetual price and the spot index price. Long positions pay shorts when the perpetual trades at a premium, and vice versa. This mechanism keeps the perpetual price anchored to the spot price without requiring physical delivery.
Real-Time Margin Calculation
Real-time margin requirements using rolling TWAPs (Time-Weighted Average Prices) from Pyth or Switchboard oracles for accurate price feeds. Initial margin is calculated based on position size and leverage, while maintenance margin is set at a lower threshold to prevent premature liquidations. The system supports cross-margin mode where all positions share the same margin pool, and isolated margin mode where each position has its own dedicated margin.
PnL Settlement & Mark-to-Market
Efficient profit and loss calculations with automatic liquidation triggers when margin falls below maintenance requirements. Unrealized PnL is calculated continuously using the current mark price, while realized PnL is settled when positions are closed. The system uses a mark-to-market approach where positions are revalued at the current market price, ensuring accurate risk assessment at all times.
UserAccount Structure & State Management
Each account's margin is maintained via a single UserAccount struct inside the same slab for fast access. The struct contains the user's collateral balance, open positions, pending orders, and risk parameters. All updates to the UserAccount are atomic and validated before being committed to the slab, ensuring consistency even in the event of transaction failures.
Liquidation Engine
Automated liquidation system that monitors all positions and triggers liquidations when margin ratio falls below the maintenance threshold. Liquidations are executed by liquidator bots that receive a portion of the remaining margin as an incentive. The system uses a partial liquidation approach where only enough of the position is closed to bring the account back above the maintenance margin, minimizing losses for the user.
Insurance Fund
A protocol-owned insurance fund absorbs losses from liquidations that occur at prices worse than the bankruptcy price. The fund is capitalized through a portion of trading fees and liquidation penalties. In extreme market conditions where the insurance fund is depleted, the system implements auto-deleveraging (ADL) where profitable positions are automatically reduced to cover losses.
LP Logic & Liquidity Provision
Advanced liquidity provision with portfolio margin and dynamic curves for optimal capital efficiency
USDC Vault & LP Token System
LPs deposit USDC into a program-owned vault, receiving LP tokens representing their share of the pool. The LP token price is calculated based on the total value of the pool (including unrealized PnL from open positions) divided by the total supply of LP tokens. This ensures that LPs are fairly compensated for the risk they take and share in both profits and losses proportionally.
Portfolio Margin for LPs
LP margin is shared across all positions, similar to Hyperliquid's approach, maximizing capital efficiency. Instead of requiring separate margin for each market, the system calculates a portfolio-level margin requirement based on the correlation and diversification of positions. This allows LPs to provide liquidity to multiple markets with less capital than would be required in an isolated margin system.
Dynamic AMM Curve
Liquidity depth automatically adjusts based on volatility regime, providing tighter spreads in calm markets and wider spreads during volatility. The curve parameters are updated using a rolling window of historical volatility, ensuring that the LP is adequately compensated for the risk of adverse selection during volatile periods. The system uses a modified constant product formula (x * y = k) with dynamic k adjustment.
Fee Distribution & Yield Generation
Trading fees are automatically distributed to LPs proportional to their share of the pool. The fee structure includes a maker fee (paid by liquidity providers) and a taker fee (paid by liquidity takers), with the majority of fees going to LPs. Additional yield is generated from funding rate payments when the LP takes the opposite side of imbalanced positions.
Impermanent Loss Protection
The system implements several mechanisms to mitigate impermanent loss for LPs. Dynamic spread adjustment ensures that LPs are compensated for taking on inventory risk. Position limits prevent the LP from accumulating excessive exposure to any single market. Hedging strategies can be employed where the LP automatically hedges its net position on external venues to reduce directional risk.
Withdrawal Queue & Liquidity Management
LP withdrawals are processed through a queue system to prevent sudden liquidity drains. When an LP requests a withdrawal, their tokens are burned and they enter a withdrawal queue. The actual USDC is transferred once sufficient liquidity is available, typically within 24-48 hours. This mechanism protects the protocol from bank runs while ensuring LPs can exit their positions in a reasonable timeframe.
Router System - "Prop Router"
Purpose & Architecture
The Router aggregates multiple Percolator instances (each possibly with a different curve or risk model) and intelligently routes orders or rebalances LP exposure between them for optimal execution and risk management. This design enables horizontal scaling where new instances can be added to increase overall system capacity without modifying existing code.
The router acts as a meta-layer that sits above individual Percolator instances, providing a unified interface for users while optimizing execution across multiple venues. It implements sophisticated routing algorithms that consider liquidity, fees, latency, and risk to determine the best execution path for each order.
1Intelligent Position Routing
When a user opens a position, the router intelligently decides which Percolator instance to use based on multiple factors. The routing decision is made in real-time using a scoring algorithm that weighs various metrics:
Liquidity Depth Analysis
Routes to instances with sufficient liquidity to minimize slippage. The router maintains a real-time view of available liquidity at each price level across all instances. For large orders, the router may split the order across multiple instances to achieve better average execution price. The liquidity scoring considers both the depth at the best bid/ask and the cumulative depth within a certain price range.
Funding Rate Optimization
Optimizes for favorable funding rates across instances. The router tracks funding rates in real-time and can route positions to instances where the funding rate is more favorable for the user's direction. For example, if a user wants to go long and one instance has a negative funding rate (longs receive payments), the router will prefer that instance. This can result in significant cost savings for users holding positions over extended periods.
Latency & Gas Efficiency
Considers execution speed and transaction costs when routing orders. The router maintains latency statistics for each instance and factors this into the routing decision. For time-sensitive orders, the router prioritizes instances with lower latency even if they have slightly worse pricing. Gas costs are estimated based on the complexity of the transaction and the current network congestion, ensuring that the total cost (including gas) is minimized.
Risk Capacity Assessment
Evaluates the risk capacity of each instance before routing. Each Percolator instance has maximum position limits and risk thresholds. The router ensures that new positions don't push an instance beyond its risk limits, which could trigger defensive measures like wider spreads or reduced leverage. This distributed risk management approach prevents any single instance from becoming overloaded.
2Advanced Rebalancing Strategies
Cross-Instance Netting
Moves deltas between instances to maintain neutrality and optimize LP exposure. The router continuously monitors the net position across all instances and identifies opportunities to net offsetting positions. For example, if Instance A has a large long position and Instance B has a large short position in the same market, the router can facilitate trades between them to reduce overall exposure. This netting reduces the LP's directional risk and frees up capital for providing liquidity.
Soft Rebalance Mechanism
Triggers offsetting trades between perps to rebalance without external transfers. Instead of moving collateral between instances (which would require multiple transactions and incur fees), the router can execute offsetting trades that achieve the same economic effect. For example, closing a long position in Instance A and opening an equivalent long position in Instance B effectively moves the exposure without transferring funds. This approach is more efficient and reduces transaction costs.
Dynamic Risk Optimization
Continuously monitors and adjusts positions to maintain optimal risk distribution across instances. The router uses a risk scoring system that evaluates factors like concentration risk, correlation risk, and tail risk. When the risk score exceeds predefined thresholds, the router automatically initiates rebalancing operations to bring the portfolio back into compliance. This proactive risk management prevents situations where a single instance becomes overexposed to adverse market movements.
Arbitrage Opportunity Detection
Identifies and exploits price discrepancies between instances. When the same market trades at different prices across instances (due to temporary supply/demand imbalances), the router can execute arbitrage trades to capture the spread. These arbitrage profits are shared with LPs, providing an additional source of yield. The router's ability to see across all instances gives it a unique advantage in detecting these opportunities before external arbitrageurs.
3Unified API & Data Aggregation
Exposes a single front-end interface while aggregating data across all instances. Users interact with the router as if it were a single exchange, while the router handles the complexity of managing multiple underlying instances. This abstraction simplifies the user experience and enables advanced features that wouldn't be possible with a single instance.
Aggregated PnL Calculation
Combines profit and loss across all Percolator instances to provide a unified view of user performance. The router maintains a real-time ledger of all positions and calculates total unrealized and realized PnL. This includes not just the direct PnL from price movements, but also funding payments, trading fees, and any other costs or revenues. The aggregated PnL is presented in a single dashboard, making it easy for users to track their overall performance.
Unified Margin Management
Presents total margin requirements and available balance across all instances. The router implements cross-margin at the router level, where margin can be shared across positions in different instances. This provides maximum capital efficiency for users, as they don't need to maintain separate margin balances for each instance. The router handles the complexity of allocating margin to each instance based on the positions held there, while presenting a simple unified margin view to the user.
Cross-Instance Funding Aggregation
Aggregates funding payments from all positions across instances. The router calculates the net funding payment by summing the funding from each position, accounting for the direction (long or short) and size. Users receive a single funding payment that represents their total funding across all instances. This simplifies accounting and provides a clear view of the cost of carry for the user's overall portfolio.
Consolidated Order Book View
Aggregates order book data from all instances to present a unified depth chart. The router merges the order books by price level, showing the total liquidity available across all instances at each price. This gives users a complete picture of market depth and helps them make informed trading decisions. The consolidated order book updates in real-time as orders are placed and filled across instances.
Technical Advantages
Ultra-Low Latency
Single-account architecture minimizes memory access patterns and compute overhead for sub-millisecond execution. By keeping all data in one contiguous memory space, PFORK eliminates the overhead of multiple account lookups and cross-program invocations that plague traditional Solana programs.
Capital Efficiency
Portfolio margin and cross-instance netting maximize capital utilization for both traders and LPs. Users can maintain larger positions with less collateral, while LPs can provide liquidity to multiple markets without tying up excessive capital.
Composability
Modular design allows multiple instances with different parameters to coexist and be aggregated by the router. This enables experimentation with different risk models, fee structures, and liquidity curves without affecting the core protocol.
Built-in Risk Management
Integrated risk engine with real-time margin calculations and automatic liquidations protects the protocol from insolvency. The system continuously monitors all positions and takes action before losses can cascade through the system.
Horizontal Scalability
The router architecture enables horizontal scaling by adding new Percolator instances as demand grows. Each instance operates independently, allowing the system to scale to handle millions of users without performance degradation.
Decentralized & Permissionless
Open-source architecture encourages community contributions and enables permissionless deployment of new instances. Anyone can launch their own Percolator instance with custom parameters, fostering innovation and competition.
Implementation Notes & Best Practices
•Solana Native: Built on Solana for high throughput and low transaction costs, leveraging the network's parallel execution capabilities and optimized runtime. The program is designed to take full advantage of Solana's unique features like parallel transaction processing and low-latency block times.
•Wallet Compatibility: Compatible with standard Solana wallets (Phantom, Solflare, Backpack) and integrates seamlessly with existing DeFi infrastructure. Users can connect with their existing wallets without any special setup or configuration.
•Oracle Agnostic: Oracle-agnostic design supports Pyth, Switchboard, and other price feed providers for maximum flexibility. The system can be configured to use any oracle that provides reliable price data, allowing operators to choose based on their specific requirements for latency, accuracy, and cost.
•Open Source: Open-source architecture encourages community contributions and enables permissionless deployment of new instances. The codebase is available on GitHub with comprehensive documentation and examples to help developers understand and extend the system.
•Audit & Security: The protocol undergoes regular security audits by leading blockchain security firms. A bug bounty program incentivizes white-hat hackers to identify and report vulnerabilities. All critical operations are protected by multi-signature governance to prevent unauthorized changes.
•Upgrade Path: The program is designed with upgradeability in mind, using a proxy pattern that allows for bug fixes and feature additions without disrupting existing users. Upgrades are governed by a DAO where token holders vote on proposed changes, ensuring that the community has a say in the protocol's evolution.
Performance Metrics
Sub-millisecond latency from order submission to confirmation
Transactions per second per instance with room for scaling
High availability with redundant infrastructure and failover
Ready to Fork the Future?
Join the next generation of perpetual DEX infrastructure. Build faster, trade smarter, scale infinitely.
Built by traders, for traders