CADkgTubACk5yQ8xmqXduEmhDuvLTwvim3Ark2jsXzpump
5 months in the making since @toly tweeted
Inspired by @perps — Solana's answer to Hyperliquid

The Future of
Perpetual Trading

A self-contained perpetual DEX engine that lives in a single Solana account slab. Built for low latency, high throughput, and maximum capital efficiency.

<1ms
Latency
50K+ TPS
Throughput
Markets
99.9%
Efficiency
The Origin

Built Because Toly Wanted It

When Solana's co-founder calls for innovation, we answer.

Toly's profile picture

Anatoly Yakovenko

@aeyakovenko · Co-founder of Solana

“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

Toly's tweet about building a perp DEX on Solana
This tweet started it allView Tweet

PFORK is the answer.

Single-account architecture, integrated matching and risk engines, and router-ready design. Exactly what Toly asked for.

Core Features

Built for Performance

Every component optimized for speed, efficiency, and reliability on Solana.

Architecture

Single Account Slab

All order data, LP pools, and positions stored in one contiguous Solana account. Zero cross-program invocations, minimal compute overhead.

Learn more
Performance

Lightning Fast Matching

Binary heap-based matching engine with O(log n) complexity. Supports limit, market, IOC, FOK, and post-only order types natively.

Learn more
Safety

Integrated Risk Engine

Real-time margin calculations using rolling TWAPs from Pyth and Switchboard. Automated funding rates and liquidation triggers built-in.

Learn more
Liquidity

Dynamic LP Logic

Portfolio margin across all positions with AMM curves that adapt to volatility. LPs earn from trading fees and funding rate payments.

Learn more
Routing

Prop Router

Aggregates multiple Percolator instances with intelligent position routing. Cross-instance netting and rebalancing for optimal execution.

Learn more
Security

Insurance Fund & ADL

Protocol-owned insurance fund absorbs bad debt. Auto-deleveraging ensures system solvency even during black swan events.

Learn more
How It Works

Core Architecture

Four tightly integrated modules that form a complete perpetual DEX engine.

Memory Layout

Single Account Slab

All data lives in one contiguous memory space using OpenBook/Phoenix-style architecture. Eliminates multi-account lookups and reduces transaction complexity.

Unified serialization with BorshCustom allocator for space reuseSingle deserialization path per tx

Matching Engine

Binary Heap + Radix Tree

Hybrid data structure approach: binary heap for price-time priority, radix tree for O(1) cancellations. Each market operates at a different slab offset.

Price-time priority matchingFOK, IOC, post-only supportCross-market atomic execution

Risk Engine

Real-Time Margin & Liquidation

Continuous margin calculations using rolling TWAPs from Pyth/Switchboard. Automated funding rates, partial liquidations, and insurance fund management.

Cross & isolated margin modesHourly funding rate settlementAuto-deleveraging fallback

Prop Router

Multi-Instance Aggregation

Aggregates multiple Percolator instances with intelligent routing. Considers liquidity depth, funding rates, latency, and risk capacity for optimal execution.

Smart order routingCross-instance nettingSoft rebalancing via offsets
Powered by
SolanaPythSwitchboard
Documentation

Technical Specification

Deep dive into PFORK's architecture, implementation, and design decisions.

01

System Overview

PFORK (Percolator Fork) is a self-contained perpetual DEX engine that lives in one Solana account slab. It handles LP, risk, matching, and position management internally, providing complete trading infrastructure in a single program optimized for Solana's parallel execution model.

Single Account

All data in one contiguous slab for minimal compute overhead

Integrated

Matching, risk, and LP logic built-in with zero external deps

Router Ready

Multi-instance aggregation with cross-market optimization

02

Memory Layout & Slab Architecture

Efficient single-account slab architecture using OpenBook/Phoenix-style design where all order data lives in one contiguous memory space.

Single Account Slab Design

Uses OpenBook or Phoenix-style architecture where all order data lives in one contiguous memory space. Eliminates multiple account lookups, 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. Related data is stored together in memory, reducing CPU cache misses and improving throughput. Uses Borsh for efficient encoding/decoding with minimal overhead.

Single Deserialization Path

The entire slab is deserialized once per transaction. All operations work with in-memory references. Critical for achieving sub-millisecond execution times on Solana's runtime by minimizing memory access patterns.

Memory Management & Garbage Collection

Custom allocator manages free space efficiently. Closed orders and settled positions are marked for reuse rather than deleted, preventing fragmentation. Periodic compaction runs during low-activity periods to optimize memory layout.

03

Matching Engine

High-performance order matching with composable market support and advanced order types. Hybrid data structure approach for optimal speed.

Binary Heap & Radix Tree Implementation

Binary heap maintains price-time priority for limit orders with O(log n) complexity. 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. Markets can be added dynamically by allocating a new section and initializing the matching engine state. Enables unlimited market support without code duplication.

Price-Time Priority Matching

Orders matched by price priority first, then time priority. Market orders execute immediately against best available liquidity. Limit orders placed in the order book at specified price level. Deterministic execution prevents front-running.

Advanced Order Types

Supports limit, market, post-only, fill-or-kill (FOK), and immediate-or-cancel (IOC) orders. Stop-loss and take-profit via trigger conditions on each price update. Iceberg orders reveal only a portion of total size to minimize market impact.

Cross-Market Matching

Execute trades across multiple markets in a single transaction for spread trading and arbitrage. Cross-market orders validated atomically to ensure consistency and prevent partial fills that could leave users in unintended positions.

04

Risk Engine & Margin System

Built-in risk management with real-time margin calculations, automated liquidations, and insurance fund management.

Dynamic Funding Rate Mechanism

Funding rate computed hourly using the difference between perpetual price and spot index price. Longs pay shorts when perpetual trades at a premium, and vice versa. Keeps the perpetual price anchored to spot without requiring physical delivery.

Real-Time Margin Calculation

Uses rolling TWAPs from Pyth or Switchboard oracles for accurate price feeds. Supports cross-margin mode (all positions share margin pool) and isolated margin mode (dedicated margin per position). Initial margin based on position size and leverage; maintenance margin set lower to prevent premature liquidations.

PnL Settlement & Mark-to-Market

Unrealized PnL calculated continuously using current mark price. Realized PnL settled when positions close. Mark-to-market approach revalues positions at current market price for accurate risk assessment at all times.

UserAccount Structure

Each account's margin maintained via a single UserAccount struct inside the same slab. Contains collateral balance, open positions, pending orders, and risk parameters. All updates are atomic and validated before commit.

Liquidation Engine

Automated monitoring triggers liquidations when margin ratio falls below maintenance threshold. Liquidator bots receive a portion of remaining margin as incentive. Partial liquidation approach closes only enough to restore margin, minimizing user losses.

Insurance Fund & ADL

Protocol-owned insurance fund absorbs losses from underwater liquidations. Capitalized through trading fees and liquidation penalties. In extreme conditions, auto-deleveraging (ADL) automatically reduces profitable positions to cover losses.

05

LP Logic & Liquidity Provision

Advanced liquidity provision with portfolio margin, dynamic AMM curves, and comprehensive yield generation for LPs.

USDC Vault & LP Token System

LPs deposit USDC into a program-owned vault, receiving LP tokens representing pool share. LP token price calculated based on total pool value (including unrealized PnL) divided by total supply. Fair compensation proportional to risk taken.

Portfolio Margin for LPs

LP margin shared across all positions, similar to Hyperliquid's approach. Portfolio-level margin requirement based on correlation and diversification. Provide liquidity to multiple markets with less capital than isolated margin systems.

Dynamic AMM Curve

Liquidity depth adjusts based on volatility regime: tighter spreads in calm markets, wider during volatility. Parameters updated using rolling window of historical volatility. Modified constant product formula (x * y = k) with dynamic k adjustment.

Fee Distribution & Yield Generation

Trading fees automatically distributed to LPs proportional to pool share. Maker/taker fee structure with majority going to LPs. Additional yield from funding rate payments when LP takes opposite side of imbalanced positions.

Impermanent Loss Protection

Dynamic spread adjustment compensates LPs for inventory risk. Position limits prevent excessive exposure to any single market. Optional auto-hedging on external venues to reduce directional risk.

Withdrawal Queue & Liquidity Management

Withdrawals processed through a queue to prevent sudden liquidity drains. LP tokens burned on request, USDC transferred when sufficient liquidity available (typically 24-48 hours). Protects protocol from bank runs while ensuring reasonable exit timeframes.

06

Router System — "Prop Router"

Aggregates multiple Percolator instances with intelligent routing, cross-instance netting, and a unified API layer.

1Intelligent Position Routing

When a user opens a position, the router decides which Percolator instance to use based on a real-time scoring algorithm.

Liquidity Depth Analysis

Routes to instances with sufficient liquidity to minimize slippage. Maintains real-time view of available liquidity at each price level across all instances. For large orders, splits across multiple instances for better average execution price.

Funding Rate Optimization

Tracks funding rates in real-time and routes to instances with favorable rates for user's direction. A user going long benefits from instances with negative funding rates (longs receive payments). Significant cost savings for extended holds.

Latency & Gas Efficiency

Maintains latency statistics per instance. Prioritizes lower-latency instances for time-sensitive orders. Gas costs estimated based on transaction complexity and network congestion to minimize total cost.

Risk Capacity Assessment

Evaluates risk capacity before routing. Each instance has maximum position limits and risk thresholds. Prevents any single instance from becoming overloaded by distributing risk across the network.

2Advanced Rebalancing Strategies

Cross-Instance Netting

Monitors net position across all instances and identifies opportunities to net offsetting positions. If Instance A has a large long and Instance B has a large short, the router facilitates trades between them to reduce overall exposure and free up capital.

Soft Rebalance Mechanism

Executes offsetting trades between perps to rebalance without external transfers. Closing a long in Instance A and opening equivalent in Instance B moves exposure without transferring funds. More efficient and reduces transaction costs.

Dynamic Risk Optimization

Uses a risk scoring system evaluating concentration risk, correlation risk, and tail risk. When scores exceed thresholds, automatically initiates rebalancing operations to bring the portfolio back into compliance.

Arbitrage Opportunity Detection

Identifies and exploits price discrepancies between instances. Executes arbitrage trades to capture spreads when the same market trades at different prices across instances. Profits shared with LPs as additional yield.

3Unified API & Data Aggregation

Single front-end interface aggregating data across all instances. Users interact as if it were a single exchange.

Aggregated PnL Calculation

Combines profit and loss across all instances for a unified performance view. Real-time ledger tracks total unrealized and realized PnL including funding payments, trading fees, and all other costs/revenues in a single dashboard.

Unified Margin Management

Cross-margin at the router level: margin shared across positions in different instances. Maximum capital efficiency without maintaining separate margin balances per instance. Router allocates margin to each instance based on positions held.

Cross-Instance Funding Aggregation

Aggregates funding payments from all positions. Net funding calculated by summing each position's funding (direction and size). Users receive a single payment representing total funding across all instances.

Consolidated Order Book View

Merges order book data by price level across all instances for a unified depth chart. Shows total liquidity available at each price. Updates in real-time as orders are placed and filled across instances.

07

Technical Advantages

Ultra-Low Latency

Single-account architecture minimizes memory access patterns and compute overhead. No cross-program invocations for sub-millisecond execution.

Capital Efficiency

Portfolio margin and cross-instance netting maximize capital utilization. Larger positions with less collateral for both traders and LPs.

Composability

Modular design allows multiple instances with different parameters to coexist. Experiment with risk models, fee structures, and liquidity curves.

Risk Management

Integrated risk engine with real-time margin calculations and automatic liquidations. Continuous monitoring prevents cascading losses.

Horizontal Scalability

Router architecture enables scaling by adding new Percolator instances as demand grows. Each operates independently without performance degradation.

Permissionless

Open-source architecture. Anyone can launch their own Percolator instance with custom parameters, fostering innovation and competition.

08

Implementation Notes

Solana Native

Built on Solana for high throughput and low transaction costs, leveraging parallel execution and optimized runtime.

Wallet Compatibility

Compatible with Phantom, Solflare, Backpack, and other standard Solana wallets. No special setup required.

Oracle Agnostic

Supports Pyth, Switchboard, and other price feed providers. Operators choose based on latency, accuracy, and cost requirements.

Audit & Security

Regular security audits by leading firms. Bug bounty program for vulnerability disclosure. Multi-sig governance for critical operations.

Upgrade Path

Proxy pattern for bug fixes and feature additions without disrupting users. DAO-governed upgrades with community voting.

<1ms
Order Execution
Sub-millisecond latency
50K+
TPS Capacity
Orders per second
100+
Concurrent Markets
Per instance
99.99%
Uptime Target
High availability

Ready to Fork the Future?

Join the next generation of perpetual DEX infrastructure on Solana.

Built by traders, for traders.