⚠️ Infrastructure status: April 2026 incident
Please note: the Drift Protocol Mainnet smart contracts are currently frozen following a successful hack in April 2026. Any requests to RPC nodes, attempts to initialize a DriftClient or submit transactions to the main network will fail with a program error. This guide is provided for educational and research purposes — to analyze the protocol's architecture and for developers working in local simulations (Devnet/Localhost).
Architecture Overview: Solana RPC & Anchor
Unlike centralized exchanges (with REST/WS servers) or hybrid ZK-Rollups, Drift Protocol v2 was implemented entirely as a set of on-chain programs (smart contracts) on the Solana blockchain using the Anchor framework. Classic "API keys" were not used for programmatic trading. Interaction happened by sending signed transactions directly to the blockchain.
SDK Security: Keypair Management
Instead of an API key (Account ID / Secret), Solana developers need a Solana Keypair (Ed25519). This file (`id.json`) holds the private key that has full access to your funds.
Key security practices (Solana botting):
- Fund isolation: A dedicated wallet was used solely for the trading bot, topped up with the minimum amount of SOL needed to pay transaction fees.
- Delegated Keys (a Drift feature): Drift supported a system of "delegated keys", allowing you to grant a bot's hot key limited rights (trading only, no withdrawals).
- RPC protection: Using private RPC endpoints with hidden URLs to protect your bot from DDoS attacks.
SDK Use Cases: Network Participant Roles
Solana's high throughput (~400 ms block time) allowed developers to build complex HFT strategies and infrastructure bots that kept the protocol running:
- JIT Makers: Bots participating in 5-second auctions (Just-in-Time). They intercepted user market orders, providing zero slippage in exchange for fees.
- DLOB Keepers: Off-chain agents that maintained the decentralized limit order book (DLOB). They monitored the blockchain and called the contract to match orders when the oracle price (Pyth) reached a user's limit price.
- Liquidators: Bots tracking the health of cross-margin accounts (Health Factor) and liquidating losing positions, taking a percentage of the liquidation as a reward.
Environment Initialization: TypeScript SDK
The official development tool is the @drift-labs/sdk package. The connection process included the following steps:
- Provider setup: Creating an Anchor Provider bound to your RPC node (e.g., Helius) and wallet (Keypair).
- Account subscriptions (WebSockets): Initializing the
DriftClientwith WebSocket subscriptions. On Solana this is critical: the client must locally cache pool states (DAMM) and user accounts instead of querying them before every trade. - Building instructions: The SDK compiles your parameters (order size, leverage) into Solana instructions, signs them with your
Keypairand submits the transaction to the network.
Error Handling (Anchor Program Errors)
Since the logic was processed in smart contracts, error codes were represented as custom hexadecimal Anchor codes. The most common ones:
| Hex Code | Name / Cause | Solution (Bot Logic) |
|---|---|---|
| 0x1770 | InsufficientCollateral | Not enough margin to open a position. The bot must recalculate asset weights (Oracle Price × Margin Weight) before submitting. |
| 0x1774 | OrderDoesNotExist | An attempt to cancel or modify an order that has already been executed by a DLOB Keeper. State synchronization is required. |
| 0x178A | OracleStaleForMargin | The Pyth oracle price is stale in this block. Retry the transaction after 1-2 slots (400-800 ms). |
Code Example: Connecting and Placing an Order
TypeScript: Initializing DriftClient
An example using @drift-labs/sdk to connect to the protocol. Reminder: this code will not work on Mainnet until the consequences of the 2026 incident are fully resolved.
import { Connection, Keypair } from '@solana/web3.js';
import { Wallet, AnchorProvider } from '@coral-xyz/anchor';
import { DriftClient, PublicKey, PositionDirection, OrderType } from '@drift-labs/sdk';
async function initDriftBot() {
// 1. Инициализация RPC и кошелька
const connection = new Connection("https://ваша-rpc-нода.solana.com");
const keypair = Keypair.fromSecretKey(new Uint8Array([/* ВАШ ПРИВАТНЫЙ КЛЮЧ */]));
const wallet = new Wallet(keypair);
const provider = new AnchorProvider(connection, wallet, {});
// 2. Создание клиента Drift
// ВНИМАНИЕ: С апреля 2026 контракты заморожены!
const driftClient = new DriftClient({
connection,
wallet: provider.wallet,
programID: new PublicKey('dRiftyHA39MWEi3m9aunc5MzRF1JzxgPi1U1k864YkQ'), // Drift v2 Program ID
env: 'mainnet-beta',
});
await driftClient.subscribe();
console.log("Успешное подключение к состоянию Drift!");
// 3. Пример размещения лимитного ордера (Long SOL-PERP)
const marketIndex = 0; // Индекс для SOL-PERP
const txSig = await driftClient.placePerpOrder({
orderType: OrderType.LIMIT,
direction: PositionDirection.LONG,
marketIndex,
baseAssetAmount: driftClient.convertToPerpPrecision(10), // 10 SOL
price: driftClient.convertToPricePrecision(150.50), // $150.50
});
console.log("Транзакция отправлена:", txSig);
}
initDriftBot();
Python Integration: driftpy
For data scientists and developers specializing in statistical arbitrage, the community maintained the DriftPy library. It was built on top of solana-py and anchorpy.
The primary use case for Python bots was collecting historical funding rate data directly from the blockchain, computing machine-learning (ML) features and executing mean-reversion strategies on cross-margin accounts.
→ General principles of building Python bots for DEXs
Frequently Asked Questions (FAQ) about the Drift SDK
Why does the Drift Protocol API return timeout or service-unavailable errors?
In April 2026, Drift Protocol suffered a large-scale hack targeting its smart-contract logic. To rescue the remaining liquidity, the programs on the Solana blockchain were urgently frozen by the governing Council. At present, any on-chain interaction with the protocol is rejected at the blockchain level.
How does the Drift SDK differ from standard REST APIs (like Binance's)?
Drift is a non-custodial on-chain protocol. Developers do not talk to a centralized matching server (REST API). Instead, the SDK serializes the order parameters, signs them locally with your cryptographic key and broadcasts them as an RPC transaction directly to the Solana network validators.
How can I test bots while Mainnet is down?
Developers can use solana-test-validator to run a local fork of the blockchain up to the moment of the incident. The SDK lets you switch the environment parameter to devnet or local, making it possible to simulate trading, test DLOB keepers and prepare algorithms for a potential protocol restart (Drift v3).