Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
solana-and-the-rise-of-high-performance-chains
Blog

Why Cross-Program Invocations Enable Trustless On-Chain Order Books

Atomic Cross-Program Invocations (CPIs) are Solana's architectural superpower. They enable complex, multi-step order matching and settlement within a single transaction, making trustless, high-performance Central Limit Order Books (CLOBs) finally viable on-chain.

introduction
THE ARCHITECTURAL SHIFT

Introduction

Cross-Program Invocations (CPIs) are the atomic transaction primitive that makes on-chain order books viable by eliminating custodial risk.

On-chain order books failed because they required users to deposit assets into a central, vulnerable contract. This custodial model created a single point of failure, as seen in the FTX collapse, and imposed prohibitive gas costs for frequent order updates.

Cross-Program Invocations solve custody. A CPI is a Solana primitive that allows one program to call another while preserving the atomicity of the transaction. This lets an order book program execute trades directly against user wallets, never taking custody of assets.

This mirrors Uniswap's trustlessness. Just as a Uniswap swap moves tokens from A to B in one atomic step, a CPI-based order book matches and settles in one step. The matching engine and settlement are unified, removing the settlement layer risk inherent in traditional finance and early DEXs.

Evidence: Solana's Phoenix DEX processes over $100M daily volume using CPIs. Its limit orders execute in ~400ms with sub-cent fees, proving the model scales.

thesis-statement
THE ARCHITECTURAL SHIFT

Thesis Statement

Cross-Program Invocations (CPIs) enable trustless on-chain order books by decomposing monolithic exchange logic into composable, atomic settlement primitives.

CPIs enable atomic composition of independent programs, allowing a single transaction to execute a trade, transfer assets, and update a shared order book state without intermediary trust. This atomicity is the prerequisite for a trustless settlement layer.

Monolithic DEXs like Uniswap V3 are state machines; CPIs transform the exchange into a network of stateful programs. An order book becomes a shared ledger, a matching engine becomes a separate program, and settlement executes via CPI to a token program.

This architecture mirrors off-chain intent systems like UniswapX and CowSwap, but executes fully on-chain. The shared global state of an order book ledger, updated atomically via CPIs, eliminates the need for a centralized sequencer or operator.

Solana's Sealevel runtime proves the model, where projects like Phoenix and OpenBook process millions of CPI-based orders daily. Their throughput demonstrates that decomposed, CPI-driven logic scales beyond monolithic contract designs.

market-context
THE INCUMBENT

Market Context: The AMM Monopoly and Its Cost

Automated Market Makers (AMMs) dominate on-chain liquidity but impose a hidden tax on users through inefficiency.

AMMs create guaranteed losses for liquidity providers and traders. The constant product formula (x*y=k) forces trades to move the price, creating slippage and impermanent loss. This is a structural inefficiency, not a market inefficiency.

The monopoly cost is MEV extraction. AMMs' predictable pricing creates a multi-billion dollar arbitrage opportunity for searchers. This 'liquidity tax' is paid by LPs and users via sandwich attacks and frontrunning, enriching block builders.

Order books solve this with price-time priority. They match orders directly, eliminating the need for a constant liquidity pool. This reduces slippage for large orders and captures true market price discovery, but requires a trusted operator.

Cross-Program Invocations (CPIs) enable trustless on-chain order books. By allowing programs to call each other, a Solana order book program can delegate trade settlement to a separate, audited token program. This removes the single-entity custodian risk that plagued older models like Serum.

deep-dive
THE MECHANISM

Deep Dive: How Atomic CPIs Unlock the CLOB

Atomic Cross-Program Invocations (CPIs) enable trustless, composable state transitions that are the prerequisite for a functional Central Limit Order Book (CLOB) on-chain.

Atomic execution guarantees settlement. A CLOB's core function is matching orders and moving assets. Without atomicity, a maker's sell instruction and a taker's buy instruction execute in separate transactions. This creates settlement risk where one side fails, breaking the trade. Atomic CPIs bundle these actions into a single, all-or-nothing transaction.

Composability enables complex logic. An order book is not one program. It is a matching engine, a token vault, and a fee handler. Solana's Sealevel runtime allows these programs to call each other within the same transaction. This is how Drift and OpenBook execute fills, transfer USDC, and distribute fees without intermediate, trust-laden custody.

Contrast with EVM's message-passing. EVM calls are synchronous but not natively atomic across contracts; failed sub-calls revert the entire state. This is sufficient but less granular. Solana's model treats programs as stateless libraries, pushing state accounts as parameters. This design minimizes re-decentralization risk and enables parallel execution, a requirement for high-frequency CLOB throughput.

Evidence: Drift v2's performance. Drift processes over 20% of Solana's non-vote transactions. Its architecture relies on CPIs for its conditional order types and perpetual swaps. The matching engine CPI-calls the clearing house to update positions and the insurance fund in one atomic step, a pattern impossible with asynchronous, multi-transaction designs.

ON-CHAIN EXECUTION

Architectural Showdown: CLOB vs. AMM

A first-principles comparison of Central Limit Order Book and Automated Market Maker designs, focusing on the composability that enables trustless CLOB execution via Cross-Program Invocations (CPIs).

Architectural FeatureOn-Chain CLOB (via CPIs)Standard AMM (Uniswap v2/v3)Hybrid AMM (UniswapX, CowSwap)

Execution Finality

Atomic (1 transaction)

Atomic (1 transaction)

Multi-step (Intent, Fill, Settlement)

Settlement Latency

< 400ms (Solana)

~12 sec (Ethereum L1)

~1-5 min (Solver Network)

Composability Layer

Cross-Program Invocation (CPI)

Direct Pool Interaction

Off-chain Auction + On-chain Settlement

Trust Assumption for Matching

None (On-chain verifiable)

None (Constant Product Formula)

Solver Network (1-of-N honest)

Liquidity Fragmentation

High (Per-market order books)

Low (Concentrated in pools)

Very Low (Aggregates all liquidity)

Typical Fee for Taker

0.1% - 0.4%

0.05% - 0.3% + Gas

0.0% - 0.1% (Gas subsidized)

MEV Resistance

Low (Front-running possible)

Medium (Sandwich attacks)

High (Batch auctions via CoW)

Required Infrastructure

High-Performance L1/L2 (Solana, Sui)

Any EVM-compatible chain

Solver Network + Settlement Layer (Across, Socket)

protocol-spotlight
TRUSTLESS COMPOSABILITY

Protocol Spotlight: Builders Leveraging the CPI Primitive

Cross-Program Invocation (CPI) transforms Solana's state into a globally accessible, atomic database, enabling a new class of on-chain applications that were previously impossible or custodial.

01

The Problem: Fragmented, Custodial Order Books

Traditional on-chain order books like Serum required a central, privileged crank to match orders, creating a single point of failure and censorship. This reintroduced trust and limited innovation to a single program's logic.

  • Centralized Crank: A single actor controls trade execution.
  • Siloed Liquidity: Orders and logic trapped within one program.
  • High Integration Cost: Building atop it required fragile, permissioned hooks.
1
Central Crank
Siloed
Liquidity
02

The Solution: OpenBook's Permissionless Crank

OpenBook forked Serum and, critically, made its matching engine permissionless via CPI. Any actor can invoke the matching function, turning order execution into a public good and enabling trustless, competitive cranking.

  • Decentralized Execution: Anyone can run the crank, collecting fees.
  • Atomic CPI Bundles: Trades settle in a single transaction with no intermediate state risk.
  • Composable Liquidity: The order book becomes a primitive for derivatives, AMMs, and DAOs.
Permissionless
Crank
Atomic
Settlement
03

The Application: Drift Protocol's Hybrid Liquidity

Drift V2 uses CPI to create a hybrid liquidity model, merging OpenBook's limit orders with its own AMM and just-in-time auctions. This is the power of CPI: creating a superior product by composing best-in-class primitives atomically.

  • Best Execution: Taps OpenBook for spot, Phoenix for perps, and JIT liquidity in one tx.
  • Zero Slippage: Limit orders fill at exact prices, impossible in pure AMMs.
  • ~$1B+ TVL: Scale proving the model's viability for institutional DeFi.
Hybrid
Liquidity
$1B+
TVL
04

The Frontier: Jito's MEV-Aware Bundles

CPI enables sophisticated MEV extraction to become a public utility. Jito's searchers and bundlers use CPI to atomically arb across OpenBook, Orca, Raydium, capturing value that previously leaked to private bots, and redistributing it via JTO staking rewards.

  • Atomic Arbitrage: Extract cross-DEX arb in one transaction via CPI.
  • Revenue Redistribution: MEV profits fund network security and stakers.
  • ~$500M+: Value captured and redistributed by the Jito ecosystem.
Atomic Arb
Enabled
$500M+
Value Captured
counter-argument
THE LATENCY PROBLEM

Counter-Argument: But What About Rollups and Parallel EVMs?

Rollup fragmentation and parallel execution create a latency wall that trustless on-chain order books, powered by cross-program invocations, are designed to solve.

Rollups fragment liquidity. Each L2 is a sovereign state with its own mempool and block time, making atomic cross-rollup execution impossible without a trusted third-party sequencer or a slow, expensive bridge like Across or Stargate.

Parallel EVMs exacerbate the issue. Chains like Monad or Sei optimize for internal throughput but create a harder coordination problem for external, multi-chain state. A fast order book requires a global state machine, not isolated ones.

Cross-program invocations are the primitive. They enable a single, unified execution layer where programs on different virtual machines can compose atomically within a single block, eliminating the inter-blockchain latency that breaks order matching.

Evidence: The 12-second block time of Ethereum L1 and the 2-3 second finality of leading L2s like Arbitrum and Optimism are too slow for high-frequency trading. CPI-based systems target sub-second finality for the entire transaction graph.

risk-analysis
ARCHITECTURAL FRAGILITY

Risk Analysis: What Could Derail the On-Chain CLOB?

On-chain CLOBs promise a new DeFi primitive, but their reliance on cross-program invocations (CPIs) introduces systemic risks that could stall adoption.

01

The Atomicity Trap

CPIs require atomic execution; a single revert in a dependent program (e.g., a price oracle or token program) cascades, causing the entire order match to fail. This creates unpredictable slippage and failed trades.

  • Key Risk: Non-atomic settlement destroys the core CLOB value proposition of guaranteed execution.
  • Example: A Solana CLOB interacting with Pyth for price data fails if the oracle update CPI reverts, even if the order book logic is sound.
100%
Fail Rate on Revert
~100ms
Atomic Window
02

The MEV & Frontrunning Vector

The predictable, sequential nature of CPIs within a transaction exposes intent. Bots can simulate the transaction path and frontrun critical state changes, like order placement or cancellation.

  • Key Risk: CPIs turn the order book's public state into a real-time exploit map, extracting value from retail orders.
  • Contrast: This is worse than AMM MEV; CLOB order queues are explicit targets. Solutions like Jito's bundles become attack tools, not just mitigations.
>90%
Tx Visibility
1-2 Blocks
Arb Window
03

The State Contention Bottleneck

High-frequency trading on a CLOB requires parallel execution. CPIs that touch the same central limit order book program state create lock contention, serializing trades and capping throughput.

  • Key Risk: The CLOB becomes its own bottleneck, unable to scale beyond the single program's processing limit, negating the advantage of parallel chains like Solana or Sui.
  • Data: This is why EVM-based CLOBs struggle; the architecture fights the base layer's design.
<10k TPS
Theoretical Max
1 Program
Contention Point
04

The Oracle Dependency Death Spiral

Trustless cross-margining and liquidation require price feeds. CPI calls to oracles (Pyth, Chainlink) introduce latency, cost, and a critical external failure point. During volatility, oracle congestion can paralyze the entire CLOB.

  • Key Risk: The CLOB's integrity is outsourced. A delayed or stale price feed leads to mass mispricing or failed liquidations, risking protocol insolvency.
  • Example: This is a sharper version of the risk seen in Aave or Compound, but with sub-second execution demands.
300-400ms
Oracle Latency
1 Source
Single Point of Fail
05

The Composability Illusion

While CPIs enable modularity, they force the CLOB to trust the security and liveness of every integrated program. A bug or pause in a token-2022 program or staking contract can freeze assets in the order book.

  • Key Risk: The CLOB's security is the weakest link in a chain of CPIs. This is the opposite of Uniswap v4's hook model, which isolates risk to specific pools.
  • Result: Systemic risk increases with each integration, creating fragile financial networks.
N+1 Programs
Attack Surface
0 Downtime
Required Liveness
06

The Economic Model Challenge

CPIs incur separate compute unit (CU) fees. A complex trade involving multiple CPIs (oracle, token transfer, fee collection) can have unpredictable and high gas costs, making tight spreads and low fees economically impossible.

  • Key Risk: Fee unpredictability destroys the quantitative models market makers rely on, forcing them to widen spreads or abandon the venue.
  • Contrast: This is a fundamental disadvantage versus batch-processed AMMs or intent-based systems like UniswapX, which abstract gas complexity.
+200-500%
Fee Variance
Unpredictable
MM Cost Basis
future-outlook
THE EXECUTION LAYER

Future Outlook: The Composable Trading Stack

Cross-program invocations are the atomic unit that will enable trustless, on-chain order books by decomposing trading into specialized, composable modules.

Cross-program invocations (CPIs) are the atomic unit of composable trading. They allow one program to call another on-chain, creating a permissionless mesh of specialized logic. This enables the decomposition of a monolithic order book into discrete modules for matching, settlement, and risk.

Trustless order books require state synchronization. A traditional central limit order book (CLOB) is a single stateful contract, a bottleneck. A CPI-based CLOB separates the matching engine from the settlement layer, enabling parallel execution and eliminating the need for a trusted operator to manage the entire stack.

The counter-intuitive insight is that fragmentation creates efficiency. Unlike the unified model of dYdX or Hyperliquid, a CPI stack lets the best-in-class modules compete. A matching engine on Solana can settle via Wormhole to an AMM on Arbitrum, with intent-based routing from UniswapX filling the cross-chain leg.

Evidence is in adoption metrics. Jupiter's LFG Launchpad uses CPIs to bundle token launches with market making on Phoenix. This pattern—orchestrating independent, auditable programs—proves the model for complex, multi-venue order flow that no single protocol could feasibly manage.

takeaways
TRUSTLESS STATE SYNCHRONIZATION

Key Takeaways

Cross-Program Invocations (CPIs) solve the atomic composability problem, enabling on-chain order books to function without centralized sequencers or custodians.

01

The Problem: Fragmented State & MEV

Traditional DEX architectures force users to submit orders to a single, centralized sequencer or rely on off-chain matching engines, creating custodial risk and MEV extraction points.

  • State is siloed between matching and settlement layers
  • Users cede control, enabling front-running and sandwich attacks
  • Introduces a single point of failure and censorship
~$1.3B
MEV Extracted (2023)
02

The Solution: Atomic Cross-Program Invocations

CPIs allow a single transaction to execute instructions across multiple on-chain programs atomically. This is the core primitive for a trustless order book.

  • Atomic Settlement: Matching logic and token transfers succeed or fail together
  • No Intermediary Custody: Funds move directly between user wallets via the program
  • Enables Complex Logic: Conditional orders, TWAPs, and batch auctions become native
~400ms
Solana Slot Time
0
Custodial Risk
03

The Blueprint: OpenBook & Phoenix

Solana's leading on-chain order books (OpenBook, Phoenix) demonstrate the CPI model, processing $10B+ in volume without a central operator.

  • Matching Engine is On-Chain: Order logic lives in a verifiable program
  • CPIs Handle Settlement: The book invokes the Token Program to move assets
  • Composable Liquidity: Enables DEX Aggregators (Jupiter) and Perps Protocols (Drift) to build on top
10,000+
TPS Capacity
$0.001
Avg. Trade Cost
04

The Limitation: Congestion & State Bloat

CPIs are not free. Every invocation consumes compute units (CU) and must fit within a transaction's size/execution limits, creating scaling trade-offs.

  • Network Congestion can cause CPI failures and failed transactions
  • Large State Accounts (order books) increase rent costs and access latency
  • Requires careful compute budgeting to avoid out-of-gas scenarios mid-trade
1.4M
CU Limit/Tx
~1232
Bytes/Order
ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team
Why Cross-Program Invocations Enable Trustless On-Chain Order Books | ChainScore Blog