Skip to main content
WebSocket subscribers use Solana’s native accountSubscribe RPC method to receive real-time account updates with minimal latency. They automatically handle reconnection and provide event-driven updates.

WebSocketUserAccountSubscriber

Subscribe to updates for a specific user account.

Constructor

Program
required
Anchor program instance for the Drift protocol
PublicKey
required
Public key of the user account to subscribe to
ResubOpts
Options for automatic resubscription on connection loss
Commitment
Solana commitment level (e.g., ‘confirmed’, ‘finalized’)

Methods

subscribe

Start subscribing to user account updates.
UserAccount
Optional initial user account data to set before subscribing

getUserAccountAndSlot

Get the current user account data with slot number.
Returns: DataAndSlot<UserAccount> Throws: NotSubscribedError if not subscribed

updateData

Manually update the user account data.

Example Usage

WebSocketDriftClientAccountSubscriber

Subscribe to Drift protocol state, markets, and oracle accounts.

Constructor

Program
required
Anchor program instance for the Drift protocol
number[]
required
Array of perpetual market indexes to subscribe to
number[]
required
Array of spot market indexes to subscribe to
OracleInfo[]
required
Array of oracle information to subscribe to
boolean
required
Whether to automatically discover and subscribe to all markets
DelistedMarketSetting
required
How to handle delisted markets: Unsubscribe, Subscribe, or Discard
ResubOpts
Options for automatic resubscription
Commitment
Solana commitment level

Methods

subscribe

Start subscribing to all configured accounts.

addPerpMarket

Dynamically add a perpetual market subscription.

addSpotMarket

Dynamically add a spot market subscription.

addOracle

Dynamically add an oracle subscription.

getStateAccountAndSlot

Get the Drift protocol state account.

getMarketAccountAndSlot

Get a perpetual market account by index.

getSpotMarketAccountAndSlot

Get a spot market account by index.

getOraclePriceDataAndSlot

Get oracle price data by oracle ID.

Example Usage

WebSocketProgramAccountSubscriber

Subscribe to all accounts owned by the Drift program.

Constructor

string
required
Name of the account type (e.g., ‘user’, ‘market’)
Program
required
Anchor program instance

Example Usage

Resubscription Options

WebSocket subscribers support automatic resubscription on connection loss:

Best Practices

  1. Always handle errors - Listen to the error event to handle connection issues
  2. Use appropriate commitment - Use confirmed for speed, finalized for safety
  3. Enable resubscription - Set resubTimeoutMs to handle network issues
  4. Clean up subscriptions - Always call unsubscribe() when done
  5. Monitor slot numbers - Use slot numbers to detect stale data

Common Issues

NotSubscribedError

Thrown when accessing data before subscribing:

Connection Loss

Handle reconnection with resubscription options: