The DriftClient is the main entry point for interacting with Drift Protocol. It manages connections to the Solana blockchain, handles account subscriptions, and provides methods for trading and account management.
import { Connection, Keypair, PublicKey } from '@solana/web3.js';import { Wallet, AnchorProvider } from '@coral-xyz/anchor';import { DriftClient, initialize, BulkAccountLoader,} from '@drift-labs/sdk';
2
Set Up Connection and Wallet
// Initialize SDK config for your environmentconst sdkConfig = initialize({ env: 'mainnet-beta' });// or 'devnet' for testing// Create connection to Solana RPCconst connection = new Connection( process.env.RPC_URL || 'https://api.mainnet-beta.solana.com', 'confirmed');// Load wallet from environment or create new oneconst keypair = Keypair.fromSecretKey( Uint8Array.from(JSON.parse(process.env.PRIVATE_KEY)));const wallet = new Wallet(keypair);
3
Create Account Loader
// BulkAccountLoader batches account fetches for efficiencyconst bulkAccountLoader = new BulkAccountLoader( connection, 'confirmed', 1000 // polling frequency in ms);
4
Initialize DriftClient
const driftClient = new DriftClient({ connection, wallet, programID: new PublicKey(sdkConfig.DRIFT_PROGRAM_ID), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, },});// Subscribe to account updatesawait driftClient.subscribe();
Polling: Default choice, good balance of performance and simplicity
WebSocket: When you need real-time updates and can handle reconnection logic
gRPC: For professional market makers and high-frequency trading
Handle subscription lifecycle
// Always subscribe after creating clientawait driftClient.subscribe();// Unsubscribe when done to prevent memory leaksawait driftClient.unsubscribe();
Error handling
try { await driftClient.subscribe();} catch (error) { console.error('Failed to subscribe:', error); // Implement retry logic or fallback}// Listen for errorsdriftClient.eventEmitter.on('error', (err) => { console.error('DriftClient error:', err);});