Skip to main content
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.

Prerequisites

Before initializing the DriftClient, ensure you have:
  • A Solana RPC connection
  • A wallet/keypair
  • The Drift program ID

Basic Initialization

1

Import Required Dependencies

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 environment
const sdkConfig = initialize({ env: 'mainnet-beta' });
// or 'devnet' for testing

// Create connection to Solana RPC
const connection = new Connection(
  process.env.RPC_URL || 'https://api.mainnet-beta.solana.com',
  'confirmed'
);

// Load wallet from environment or create new one
const 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 efficiency
const 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 updates
await driftClient.subscribe();

Configuration Options

DriftClientConfig

connection
Connection
required
Solana web3.js Connection instance
wallet
IWallet
required
Wallet instance implementing the IWallet interface
programID
PublicKey
required
Drift program ID (use initialize() helper to get correct ID)
accountSubscription
object
required
Account subscription configuration
env
DriftEnv
Environment: ‘mainnet-beta’ or ‘devnet’ (default: ‘mainnet-beta’)
txSender
TxSender
Custom transaction sender (default: RetryTxSender)
opts
ConfirmOptions
Solana transaction confirmation options

Subscription Types

Polling Subscription

Best for most use cases. Efficiently batches account fetches.
const bulkAccountLoader = new BulkAccountLoader(
  connection,
  'confirmed',
  1000 // poll every 1 second
);

const driftClient = new DriftClient({
  // ... other config
  accountSubscription: {
    type: 'polling',
    accountLoader: bulkAccountLoader,
  },
});

WebSocket Subscription

Real-time updates with lower latency. Higher RPC load.
const driftClient = new DriftClient({
  // ... other config
  accountSubscription: {
    type: 'websocket',
    resubscriptionOptions: {
      resubscribe: true,
      resubTimeoutMs: 30000,
    },
  },
});

gRPC Subscription

Lowest latency, highest throughput. Requires gRPC infrastructure.
import { GrpcConfigs } from '@drift-labs/sdk';

const grpcConfig: GrpcConfigs = {
  endpoint: 'https://your-grpc-endpoint.com',
  token: process.env.GRPC_TOKEN,
};

const driftClient = new DriftClient({
  // ... other config
  accountSubscription: {
    type: 'grpc',
    grpcConfig,
  },
});

Environment Configuration

Use the initialize() helper to get correct addresses for each environment:
import { initialize } from '@drift-labs/sdk';

// Mainnet
const mainnetConfig = initialize({ env: 'mainnet-beta' });
console.log(mainnetConfig.DRIFT_PROGRAM_ID); // dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH

// Devnet
const devnetConfig = initialize({ env: 'devnet' });
The initialize() function returns configuration including:
  • DRIFT_PROGRAM_ID: Main Drift program address
  • USDC_MINT_ADDRESS: USDC token mint
  • Market configuration and oracles

Complete Example

import { Connection, Keypair } from '@solana/web3.js';
import { Wallet } from '@coral-xyz/anchor';
import {
  DriftClient,
  initialize,
  BulkAccountLoader,
} from '@drift-labs/sdk';

async function initializeDrift() {
  // Get config for environment
  const sdkConfig = initialize({ env: 'mainnet-beta' });

  // Set up connection
  const connection = new Connection(
    process.env.RPC_URL!,
    'confirmed'
  );

  // Load wallet
  const keypair = Keypair.fromSecretKey(
    Uint8Array.from(JSON.parse(process.env.PRIVATE_KEY!))
  );
  const wallet = new Wallet(keypair);

  // Create account loader
  const bulkAccountLoader = new BulkAccountLoader(
    connection,
    'confirmed',
    1000
  );

  // Initialize client
  const driftClient = new DriftClient({
    connection,
    wallet,
    programID: new PublicKey(sdkConfig.DRIFT_PROGRAM_ID),
    accountSubscription: {
      type: 'polling',
      accountLoader: bulkAccountLoader,
    },
  });

  // Subscribe to updates
  await driftClient.subscribe();
  console.log('DriftClient initialized and subscribed');

  // Get state
  const state = driftClient.getStateAccount();
  console.log('Exchange paused:', state.exchangeStatus);

  return driftClient;
}

// Run
initializeDrift()
  .then(client => {
    console.log('Ready to trade!');
  })
  .catch(err => {
    console.error('Initialization failed:', err);
  });

Best Practices

  • 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
// Always subscribe after creating client
await driftClient.subscribe();

// Unsubscribe when done to prevent memory leaks
await driftClient.unsubscribe();
try {
  await driftClient.subscribe();
} catch (error) {
  console.error('Failed to subscribe:', error);
  // Implement retry logic or fallback
}

// Listen for errors
driftClient.eventEmitter.on('error', (err) => {
  console.error('DriftClient error:', err);
});

Next Steps

Create User Account

Set up your trading account

Place Orders

Start trading on Drift

Account Subscriptions

Learn about subscription mechanisms

API Reference

Explore DriftClient methods

Build docs developers (and LLMs) love