How drift-labs/protocol-v2 works
1. Overall shape
- This repo is a Solana protocol monorepo centered on Drift Protocol v2.
- It has two major execution domains:
- On-chain Rust programs under programs/
- Off-chain TypeScript tooling and SDK under sdk/ and cli/
- The main architectural boundary is therefore Solana program state and instructions versus client-side state reconstruction, trading logic, and automation.
2. Primary on-chain program: programs/drift
- programs/drift is the core Anchor-based protocol program.
- Its internal structure is intentionally layered:
- instructions/ = entrypoints and account validation for admin, user, keeper, LP, and oracle-related actions
- controller/ = business logic orchestration for AMM, orders, liquidation, pnl, spot balances, insurance, etc.
- math/ = pure calculation layer for pricing, margin, funding, liquidation, fees, and swap logic
- state/ = persistent account models and config objects
- validation/ = rule checks for orders, users, markets, signatures, and margin safety
- This split is important for the diagram: instruction handlers call controller logic, which depends on math and state, while validation gates mutation.
3. Core protocol data model
- The main on-chain entities are represented in state/:
- global protocol state
- perp and spot market accounts
- user accounts and user maps
- oracle/account cache structures
- LP pools, insurance fund stakes, revenue share, pause/mode configs
- These are the persistent data boundaries that the SDK and tests read/write against.
- The protocol appears to support both perpetual futures and spot markets, with shared user and risk machinery.
4. Matching, pricing, and risk management
- The math/ and controller/ layers show the core runtime concerns:
- AMM pricing and re-peg logic
- order matching and fulfillment
- funding and pnl settlement
- liquidation and bankruptcy handling
- margin and exposure calculations
- insurance fund and fee distribution
- For architecture diagrams, these should be shown as the decision engine inside the program, transforming market and user state into fills, liquidations, fee accrual, and settlement outcomes.
5. External market and oracle integrations
- Drift integrates with several external on-chain services and market venues through separate programs and adapters:
- programs/pyth, programs/pyth-lazer
- programs/switchboard, programs/switchboard-on-demand
- programs/openbook_v2
- programs/token_faucet
- The SDK also contains adapters for Phoenix, Serum/OpenBook, Pyth, Switchboard, and Jupiter.
- In the architecture, these are upstream data/price sources and downstream fulfillment venues feeding the Drift engine.
6. Off-chain SDK as the integration layer
- sdk/ is a large TypeScript client library that mirrors on-chain state and exposes trading, account, oracle, and transaction primitives.
- It is not just a thin wrapper: it contains substantial off-chain logic for:
- decoding accounts and events
- maintaining live subscriptions
- computing order books and margin/risk estimates
- constructing and sending transactions
- oracle normalization and priority fee selection
- This SDK is the main boundary between applications/bots and the on-chain program.
7. Real-time state sync and subscription subsystem
- A major SDK subsystem is the family of account and event subscribers:
- WebSocket subscribers
- polling subscribers
- gRPC subscribers
- bulk loaders and one-shot fetchers
- These feed driftClient, userMap, orderSubscriber, dlob, and event caches.
- The data flow is: Solana account changes / logs → SDK subscriber layer → decoded local models → trading/risk logic.
8. Off-chain order and execution logic
- The SDK contains execution-oriented components such as:
- dlob/ for a local order book representation
- orderSubscriber/ and auctionSubscriber/
- tx/ for transaction sending, retries, blockhash management, and confirmation
- priorityFee/ for fee strategy selection
- swap/, jupiter/, swift/, and venue-specific fulfillment helpers
- This indicates that bots and clients are expected to make decisions off-chain, then submit transactions to the protocol and related venues.
- In a diagram, this is the agent/executor layer outside the chain.
9. CLI and operational scripts
- cli/ is a TypeScript command-line package, likely wrapping SDK capabilities for operator or automation tasks.
- deploy-scripts/ and test-scripts/ provide environment-specific workflows for devnet deployment, verified builds, and test execution.
- These are operational boundaries rather than core protocol logic, but they matter for diagramming how the system is built and exercised.
10. Integration and test strategy
- The repo contains extensive integration tests in top-level tests/ and SDK tests in sdk/tests/.
- The tests cover protocol behaviors like:
- liquidation
- spot/perp trading
- oracle switching
- LP pools
- insurance fund flows
- signed message / Swift flows
- specific venue fulfillments such as OpenBook, Phoenix, Serum, and Pyth variants
- This suggests the architecture is validated end-to-end against local validator or test harnesses, not only through unit tests.
11. Build and runtime environment
- The repository is organized as a Rust workspace + Anchor program suite + TypeScript package suite.
- Anchor.toml, Cargo manifests, and the devcontainer indicate Solana/Anchor is the primary runtime.
- The .github workflows, audit files, and verified build scripts indicate security-sensitive build/release controls, which are important for a protocol handling funds.
12. How to draw the architecture
- A good diagram should place programs/drift at the center.
- Surround it with:
- Oracle/venue programs as external on-chain dependencies
- SDK clients and bots as off-chain consumers and executors
- Subscribers / DLOB / tx sender / risk calculators as the SDK’s internal pipeline
- Tests and deploy tooling as supporting operational layers
- The clearest data flow is:
- market/oracle inputs into the program,
- protocol state updates on-chain,
- events/accounts out to the SDK,
- off-chain logic reconstructs state and submits new transactions back to Solana.
Main entry points: drift Drift program · driftClient.ts Drift client · instructions Instructions · controller Controller
Components 23
On-chain programs
Anchor protocol and supporting Solana programs
- Drift program · Core Solana program for protocol state and instructions
programs/drift - Instructions · Account validation and instruction handlers for admin, user, keeper, and LP flows
programs/drift/src/instructions - Controller · Orchestrates AMM, orders, liquidation, PnL, spot balance, and insurance flows
programs/drift/src/controller - Math · Pure pricing, margin, funding, liquidation, fee, swap, and matching calculations
programs/drift/src/math - State · Persistent protocol accounts, configs, maps, and caches
programs/drift/src/state - Validation · Safety and policy checks for orders, users, markets, signatures, and margin
programs/drift/src/validation
Off-chain SDK
Client library, live state sync, and execution logic
- Drift client · Main TypeScript client boundary for applications and bots
sdk/src/driftClient.ts - Subscribers · WebSocket, gRPC, polling, and bulk loaders that mirror on-chain state
sdk/src/accounts - Local state · Decoded accounts, user maps, event caches, and live protocol views
sdk/src/userMap - DLOB · Local order book and auction/order subscription machinery
sdk/src/dlob - Risk math · Margin, liquidation, funding, pricing, and state reconstruction utilities
sdk/src/math - Tx sender · Transaction assembly, retries, blockhash handling, and confirmation
sdk/src/tx - Oracle clients · Client-side normalization for Pyth, Switchboard, and quote asset prices
sdk/src/oracles
Ops and tests
CLI, deploy scripts, and validation harnesses
- CLI · Command-line wrapper around SDK capabilities
cli/cli.ts - Deploy scripts · Devnet build and deployment automation
deploy-scripts - Integration tests · End-to-end protocol and SDK behavior tests
tests - SDK tests · Unit and integration coverage for client logic and subscribers
sdk/tests
External venues
Oracle and venue programs integrated by the protocol
- Pyth · Oracle price source used by the protocol
programs/pyth - Pyth Lazer · Low-latency Pyth oracle integration
programs/pyth-lazer - Switchboard · Oracle price feed integration
programs/switchboard - SB On-Demand · On-demand Switchboard oracle integration
programs/switchboard-on-demand - OpenBook v2 · External order book venue used for fulfillment and testing
programs/openbook_v2 - Token faucet · Token minting and funding helper for test and dev flows
programs/token_faucet
Connections 25
- Drift program → Instructions: dispatches · Program entrypoints route requests into instruction handlers
- Instructions → Validation: gates by · Handlers apply rule checks before mutation
- Instructions → Controller: calls · Validated instructions invoke controller workflows
- Controller → Math: computes with · Controller logic depends on pure protocol calculations
- Controller → State: mutates · Controller updates persistent protocol accounts
- Math → State: reads models · Calculations interpret on-chain account state
- Drift program → Pyth: reads prices · Protocol consumes oracle data from Pyth
- Drift program → Pyth Lazer: reads prices · Protocol consumes low-latency Pyth updates
- Drift program → Switchboard: reads prices · Protocol consumes Switchboard oracle feeds
- Drift program → SB On-Demand: reads prices · Protocol consumes on-demand Switchboard feeds
- Drift program → OpenBook v2: fulfills via · External venue used for order fulfillment and integration
- Drift client → Subscribers: syncs through · Client builds a live view from account and log subscribers
- Subscribers → Local state: decodes into · Subscriber layer populates local mirrored models and caches
- Local state → DLOB: feeds · Reconstructed state powers local order book logic
- Local state → Risk math: evaluates · Local models support margin and risk estimation
- Risk math → Tx sender: guides · Risk and pricing outputs shape transaction construction
- Oracle clients → Risk math: normalizes into · Oracle clients provide prices for client-side calculations
- DLOB → Tx sender: produces actions · Local book decisions become executable transactions
- Drift client → Drift program: submits to · Client sends transactions back to the on-chain program
- Drift client → Oracle clients: consults · Client fetches and normalizes oracle prices
- CLI → Drift client: wraps · CLI exposes SDK operations for operators and automation
- Deploy scripts → Drift program: deploys · Scripts build and deploy the on-chain suite
- Integration tests → Drift program: exercises · Repository tests validate protocol behavior end to end
- SDK tests → Drift client: verifies · SDK tests cover client logic, subscribers, and execution flows
- SDK tests → Subscribers: verifies · Tests cover live account and log subscription paths