# drift-labs/protocol-v2 architecture

> Architecture diagram of the GitHub repository drift-labs/protocol-v2, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-11). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/drift-labs/protocol-v2
- Repository: https://github.com/drift-labs/protocol-v2

## Overview

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: [`programs/drift`](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift) (Drift program), [`sdk/src/driftClient.ts`](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/driftClient.ts) (Drift client), [`programs/drift/src/instructions`](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/instructions) (Instructions), [`programs/drift/src/controller`](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/controller) (Controller)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_onchain["On-chain programs"]
  node_drift_program["Drift program<br/>anchor protocol"]
  node_drift_instructions["Instructions<br/>entrypoints"]
  node_drift_controller["Controller<br/>business logic"]
  node_drift_math["Math<br/>calculation layer"]
  node_drift_state[("State<br/>account models")]
  node_drift_validation["Validation<br/>rule checks"]
end

subgraph group_sdk["Off-chain SDK"]
  node_sdk_client["Drift client<br/>ts client<br/>[driftClient.ts]"]
  node_sdk_subscribers["Subscribers<br/>sync layer"]
  node_sdk_state[("Local state<br/>mirrored models")]
  node_sdk_dlob["DLOB<br/>off-chain book"]
  node_sdk_math["Risk math<br/>off-chain calc"]
  node_sdk_tx["Tx sender<br/>execution"]
  node_sdk_oracles["Oracle clients<br/>market adapters"]
end

subgraph group_ops["Ops and tests"]
  node_cli_tool["CLI<br/>operator tool<br/>[cli.ts]"]
  node_deploy_scripts["Deploy scripts<br/>ops scripts"]
  node_tests_suite["Integration tests<br/>validation harness"]
  node_sdk_tests["SDK tests<br/>validation harness"]
end

subgraph group_external["External venues"]
  node_pyth_program["Pyth<br/>oracle program"]
  node_pyth_lazer_program["Pyth Lazer<br/>oracle program"]
  node_switchboard_program["Switchboard<br/>oracle program"]
  node_switchboard_od_program["SB On-Demand<br/>oracle program"]
  node_openbook_program["OpenBook v2<br/>venue program"]
  node_token_faucet_program["Token faucet<br/>support program"]
end

node_drift_program -->|"dispatches"| node_drift_instructions
node_drift_instructions -->|"gates by"| node_drift_validation
node_drift_instructions -->|"calls"| node_drift_controller
node_drift_controller -->|"computes with"| node_drift_math
node_drift_controller -->|"mutates"| node_drift_state
node_drift_math -->|"reads models"| node_drift_state
node_drift_program -.->|"reads prices"| node_pyth_program
node_drift_program -.->|"reads prices"| node_pyth_lazer_program
node_drift_program -.->|"reads prices"| node_switchboard_program
node_drift_program -.->|"reads prices"| node_switchboard_od_program
node_drift_program -.->|"fulfills via"| node_openbook_program
node_sdk_client -->|"syncs through"| node_sdk_subscribers
node_sdk_subscribers -->|"decodes into"| node_sdk_state
node_sdk_state -->|"feeds"| node_sdk_dlob
node_sdk_state -->|"evaluates"| node_sdk_math
node_sdk_math -->|"guides"| node_sdk_tx
node_sdk_oracles -->|"normalizes into"| node_sdk_math
node_sdk_dlob -->|"produces actions"| node_sdk_tx
node_sdk_client -->|"submits to"| node_drift_program
node_sdk_client -->|"consults"| node_sdk_oracles
node_cli_tool -->|"wraps"| node_sdk_client
node_deploy_scripts -.->|"deploys"| node_drift_program
node_tests_suite -.->|"exercises"| node_drift_program
node_sdk_tests -.->|"verifies"| node_sdk_client
node_sdk_tests -.->|"verifies"| node_sdk_subscribers

click node_drift_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift"
click node_drift_instructions "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/instructions"
click node_drift_controller "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/controller"
click node_drift_math "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/math"
click node_drift_state "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/state"
click node_drift_validation "https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/validation"
click node_pyth_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/pyth"
click node_pyth_lazer_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/pyth-lazer"
click node_switchboard_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/switchboard"
click node_switchboard_od_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/switchboard-on-demand"
click node_openbook_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/openbook_v2"
click node_token_faucet_program "https://github.com/drift-labs/protocol-v2/tree/master/programs/token_faucet"
click node_sdk_client "https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/driftClient.ts"
click node_sdk_subscribers "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/accounts"
click node_sdk_state "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/userMap"
click node_sdk_dlob "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/dlob"
click node_sdk_math "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/math"
click node_sdk_tx "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/tx"
click node_sdk_oracles "https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/oracles"
click node_cli_tool "https://github.com/drift-labs/protocol-v2/blob/master/cli/cli.ts"
click node_deploy_scripts "https://github.com/drift-labs/protocol-v2/tree/master/deploy-scripts"
click node_tests_suite "https://github.com/drift-labs/protocol-v2/tree/master/tests"
click node_sdk_tests "https://github.com/drift-labs/protocol-v2/tree/master/sdk/tests"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_drift_program,node_drift_instructions,node_drift_controller,node_drift_math,node_drift_state,node_drift_validation toneBlue
class node_sdk_client,node_sdk_subscribers,node_sdk_state,node_sdk_dlob,node_sdk_math,node_sdk_tx,node_sdk_oracles toneAmber
class node_cli_tool,node_deploy_scripts,node_tests_suite,node_sdk_tests toneMint
class node_pyth_program,node_pyth_lazer_program,node_switchboard_program,node_switchboard_od_program,node_openbook_program,node_token_faucet_program toneRose
```

## Components

### On-chain programs

Anchor protocol and supporting Solana programs

- [Drift program](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift): anchor protocol · Core Solana program for protocol state and instructions · `programs/drift`
- [Instructions](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/instructions): entrypoints · Account validation and instruction handlers for admin, user, keeper, and LP flows · `programs/drift/src/instructions`
- [Controller](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/controller): business logic · Orchestrates AMM, orders, liquidation, PnL, spot balance, and insurance flows · `programs/drift/src/controller`
- [Math](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/math): calculation layer · Pure pricing, margin, funding, liquidation, fee, swap, and matching calculations · `programs/drift/src/math`
- [State](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/state): account models · Persistent protocol accounts, configs, maps, and caches · `programs/drift/src/state`
- [Validation](https://github.com/drift-labs/protocol-v2/tree/master/programs/drift/src/validation): rule checks · 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](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/driftClient.ts): ts client · Main TypeScript client boundary for applications and bots · `sdk/src/driftClient.ts`
- [Subscribers](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/accounts): sync layer · WebSocket, gRPC, polling, and bulk loaders that mirror on-chain state · `sdk/src/accounts`
- [Local state](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/userMap): mirrored models · Decoded accounts, user maps, event caches, and live protocol views · `sdk/src/userMap`
- [DLOB](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/dlob): off-chain book · Local order book and auction/order subscription machinery · `sdk/src/dlob`
- [Risk math](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/math): off-chain calc · Margin, liquidation, funding, pricing, and state reconstruction utilities · `sdk/src/math`
- [Tx sender](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/tx): execution · Transaction assembly, retries, blockhash handling, and confirmation · `sdk/src/tx`
- [Oracle clients](https://github.com/drift-labs/protocol-v2/tree/master/sdk/src/oracles): market adapters · Client-side normalization for Pyth, Switchboard, and quote asset prices · `sdk/src/oracles`

### Ops and tests

CLI, deploy scripts, and validation harnesses

- [CLI](https://github.com/drift-labs/protocol-v2/blob/master/cli/cli.ts): operator tool · Command-line wrapper around SDK capabilities · `cli/cli.ts`
- [Deploy scripts](https://github.com/drift-labs/protocol-v2/tree/master/deploy-scripts): ops scripts · Devnet build and deployment automation · `deploy-scripts`
- [Integration tests](https://github.com/drift-labs/protocol-v2/tree/master/tests): validation harness · End-to-end protocol and SDK behavior tests · `tests`
- [SDK tests](https://github.com/drift-labs/protocol-v2/tree/master/sdk/tests): validation harness · Unit and integration coverage for client logic and subscribers · `sdk/tests`

### External venues

Oracle and venue programs integrated by the protocol

- [Pyth](https://github.com/drift-labs/protocol-v2/tree/master/programs/pyth): oracle program · Oracle price source used by the protocol · `programs/pyth`
- [Pyth Lazer](https://github.com/drift-labs/protocol-v2/tree/master/programs/pyth-lazer): oracle program · Low-latency Pyth oracle integration · `programs/pyth-lazer`
- [Switchboard](https://github.com/drift-labs/protocol-v2/tree/master/programs/switchboard): oracle program · Oracle price feed integration · `programs/switchboard`
- [SB On-Demand](https://github.com/drift-labs/protocol-v2/tree/master/programs/switchboard-on-demand): oracle program · On-demand Switchboard oracle integration · `programs/switchboard-on-demand`
- [OpenBook v2](https://github.com/drift-labs/protocol-v2/tree/master/programs/openbook_v2): venue program · External order book venue used for fulfillment and testing · `programs/openbook_v2`
- [Token faucet](https://github.com/drift-labs/protocol-v2/tree/master/programs/token_faucet): support program · Token minting and funding helper for test and dev flows · `programs/token_faucet`

## Connections

- 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
