Struct DriftClient

Source
pub struct DriftClient {
    pub context: Context,
    pub wallet: Wallet,
    /* private fields */
}
Expand description

DriftClient

It is cheaply clone-able and consumers are encouraged to do so. It is not recommended to create multiple instances with ::new() as this will not re-use underlying resources such as network connections or memory allocations

The client can be used as is to fetch data ad-hoc over RPC or subscribed to receive live updates (transparently)

let client = DriftClient::new(
    Context::MainNet,
    RpcClient::new("https://rpc.example.com"),
    key_pair.into()
).await.expect("initializes");

// queries over RPC
let sol_perp_price = client.oracle_price(MarketId::perp(0)).await;

// Subscribe to live program changes e.g oracle prices, spot/perp market changes, user accounts
let markets = [MarketId::perp(0), MarketId::spot(2)];
client.subscribe_markets(&markets).await.expect("subscribes");
client.subscribe_oracles(&markets).await.expect("subscribes");

// after subscribing, uses Ws-backed local storage
let sol_perp_price = client.oracle_price(MarketId::perp(0)).await;

client.unsubscribe();

Fields§

§context: Context§wallet: Wallet

Implementations§

Source§

impl DriftClient

Source

pub async fn new( context: Context, rpc_client: RpcClient, wallet: Wallet, ) -> SdkResult<Self>

Create a new DriftClient instance

  • context - devnet or mainnet
  • rpc_client - an RpcClient instance
  • wallet - wallet to use for tx signing convenience
Source

pub async fn subscribe_blockhashes(&self) -> SdkResult<()>

Starts background subscriptions for live blockhashes

This is a no-op if already subscribed

Source

pub async fn subscribe_markets(&self, markets: &[MarketId]) -> SdkResult<()>

Starts background subscriptions for live market account updates

  • markets - list of markets to subscribe

This is a no-op if already subscribed

Source

pub async fn subscribe_all_markets(&self) -> SdkResult<()>

Subscribe to all spot and perp markets

This is a no-op if already subscribed

Source

pub async fn subscribe_all_spot_markets(&self) -> SdkResult<()>

Subscribe to all spot markets

This is a no-op if already subscribed

Source

pub async fn subscribe_all_perp_markets(&self) -> SdkResult<()>

Subscribe to all perp markets

This is a no-op if already subscribed

Source

pub async fn subscribe_oracles(&self, markets: &[MarketId]) -> SdkResult<()>

Starts background subscriptions for live oracle account updates by market

  • markets - list of markets to subscribe for oracle updates

This is a no-op if already subscribed

Source

pub async fn subscribe_all_oracles(&self) -> SdkResult<()>

Subscribe to all oracles

This is a no-op if already subscribed

Source

pub async fn subscribe_all_spot_oracles(&self) -> SdkResult<()>

Subscribe to all spot market oracles

This is a no-op if already subscribed

Source

pub async fn subscribe_all_perp_oracles(&self) -> SdkResult<()>

Subscribe to all perp market oracles

This is a no-op if already subscribed

Source

pub async fn subscribe_swift_orders( &self, markets: &[MarketId], ) -> SdkResult<SwiftOrderStream>

Subscribe to swift order feed(s) for given markets

  • markets - list of markets to watch for swift orders

Returns a stream of swift orders

Source

pub fn get_all_spot_market_ids(&self) -> Vec<MarketId>

Returns the MarketIds for all active spot markets (ignores de-listed and settled markets)

Useful for iterating over all spot markets

Source

pub fn get_all_perp_market_ids(&self) -> Vec<MarketId>

Returns the MarketIds for all active perp markets (ignores de-listed and settled markets)

Useful for iterating over all perp markets

Source

pub fn get_all_market_ids(&self) -> Vec<MarketId>

Returns the MarketIds for all active markets (ignores de-listed and settled markets)

Useful for iterating over all markets

Source

pub async fn unsubscribe(&self) -> SdkResult<()>

Unsubscribe from network resources Subsequent queries will pull from the network ad-hoc

This is a no-op if not subscribed

Source

pub fn inner(&self) -> &RpcClient

👎Deprecated

Return a handle to the inner RPC client

Source

pub fn rpc(&self) -> Arc<RpcClient>

Return a handle to the inner RPC client

Source

pub fn ws(&self) -> Arc<PubsubClient>

Return a handle to the inner Ws client

Source

pub fn program_data(&self) -> &ProgramData

Return on-chain program metadata

Useful for inspecting market ids and config

Source

pub async fn get_order_by_id( &self, account: &Pubkey, order_id: u32, ) -> SdkResult<Option<Order>>

Get an account’s open order by id

  • account - the drift user PDA
  • order_id - order id to query

Returns the Order if it exists

Source

pub async fn get_order_by_user_id( &self, account: &Pubkey, user_order_id: u8, ) -> SdkResult<Option<Order>>

Get an account’s open order by user assigned id

  • account - the drift user PDA
  • user_order_id - user defined order id to query

Returns the Order if it exists

Source

pub async fn all_orders(&self, account: &Pubkey) -> SdkResult<Vec<Order>>

Get the account’s open orders

  • account - the drift user PDA

Returns the list of open orders

Source

pub async fn unsettled_positions( &self, account: &Pubkey, ) -> SdkResult<Vec<PerpPosition>>

Get the account’s unsettled positions

  • account - the drift user PDA

Returns the list of unsettled positions

Source

pub async fn all_positions( &self, account: &Pubkey, ) -> SdkResult<(Vec<SpotPosition>, Vec<PerpPosition>)>

Get all the account’s open positions

  • account - the drift user PDA
Source

pub async fn perp_position( &self, account: &Pubkey, market_index: u16, ) -> SdkResult<Option<PerpPosition>>

Get a perp position by market

  • account - the drift user PDA

Returns the position if it exists

Source

pub async fn spot_position( &self, account: &Pubkey, market_index: u16, ) -> SdkResult<Option<SpotPosition>>

Get a spot position by market

  • account - the drift user PDA

Returns the position if it exists

Source

pub fn wallet(&self) -> &Wallet

Return the DriftClient’s wallet

Source

pub async fn get_user_account(&self, account: &Pubkey) -> SdkResult<User>

Get the user account data Uses cached value if subscribed, falls back to network query

  • account - the drift user PDA (subaccount)

Returns the deserialized account data (User)

Source

pub async fn get_user_stats(&self, authority: &Pubkey) -> SdkResult<UserStats>

Get a stats account

Returns the deserialized account data (UserStats)

Source

pub async fn get_latest_blockhash(&self) -> SdkResult<Hash>

Get the latest recent_block_hash uses latest cached if subscribed, otherwise falls back to network query

Source

pub async fn get_account_value<T: AccountDeserialize>( &self, account: &Pubkey, ) -> SdkResult<T>

Get some account value deserialized as T Uses cached value if subscribed, falls back to network query

  • account - any onchain account

Returns the deserialized account data (User)

Source

pub fn try_get_account<T: AccountDeserialize>( &self, account: &Pubkey, ) -> SdkResult<T>

Try to get account as T using latest local value

requires account was previously subscribed too. like get_account_value without async/network fallback

Source

pub fn state_account(&self) -> SdkResult<State>

Try get the Drift State config account It contains various exchange level config parameters

Source

pub async fn sign_and_send(&self, tx: VersionedMessage) -> SdkResult<Signature>

Sign and send a tx to the network

Returns the signature on success

Source

pub async fn sign_and_send_with_config( &self, tx: VersionedMessage, recent_block_hash: Option<Hash>, config: RpcSendTransactionConfig, ) -> SdkResult<Signature>

Sign and send a tx to the network

  • recent_block_hash - some block hash to use for tx signing, if not provided it will be automatically set
  • config - custom RPC config to use when submitting the tx

Returns the signature on success

Source

pub async fn get_spot_market_account( &self, market_index: u16, ) -> SdkResult<SpotMarket>

Get spot market account

  • market_index - spot market index

uses latest cached value if subscribed, otherwise falls back to network query

Source

pub async fn get_perp_market_account( &self, market_index: u16, ) -> SdkResult<PerpMarket>

Get perp market account

  • market_index - perp market index

uses latest cached value if subscribed, otherwise falls back to network query

Source

pub fn try_get_spot_market_account( &self, market_index: u16, ) -> SdkResult<SpotMarket>

Try to spot market account from cache

  • market_index - spot market index

Returns error if not subscribed

Source

pub fn try_get_perp_market_account( &self, market_index: u16, ) -> SdkResult<PerpMarket>

Try to get perp market account from cache

  • market_index - spot market index

Returns error if not subscribed

Source

pub fn market_lookup(&self, symbol: &str) -> Option<MarketId>

Lookup a market by symbol

This operation is not free so lookups should be reused/cached by the caller

Returns None if symbol does not map to any known market

Source

pub async fn oracle_price(&self, market: MarketId) -> SdkResult<i64>

Get live oracle price for market uses latest cached if subscribed, otherwise falls back to network query

Source

pub async fn init_tx( &self, account: &Pubkey, delegated: bool, ) -> SdkResult<TransactionBuilder<'_>>

Initialize a transaction given a (sub)account address

let tx = client
    .init_tx(&wallet.sub_account(3), false)
    .cancel_all_orders()
    .place_orders(...)
    .build();

Returns a TransactionBuilder for composing the tx

Source

pub async fn get_recent_priority_fees( &self, writable_markets: &[MarketId], window: Option<usize>, ) -> SdkResult<Vec<u64>>

Source

pub fn try_get_oracle_price_data_and_slot( &self, market: MarketId, ) -> Option<Oracle>

Try get the latest oracle data for market

If only the price is required use oracle_price instead

Source

pub async fn get_oracle_price_data_and_slot( &self, market: MarketId, ) -> SdkResult<Oracle>

Get the latest oracle data for market

If only the price is required use oracle_price instead

Source

pub async fn subscribe_account(&self, account: &Pubkey) -> SdkResult<()>

Subscribe to live WebSocket updates for some account

The latest value may be retrieved with client.get_account(..)

let subaccount = Wallet::derive_user_account(authority, 1);
client.subscribe_account(&subaccount).await;
let subaccount_data = client.get_account::<User>(&subaccount);
Source

pub async fn subscribe_account_polled( &self, account: &Pubkey, interval: Duration, ) -> SdkResult<()>

Same as subscribe_account but uses RPC polling

Source

pub fn unsubscribe_account(&self, account: &Pubkey) -> SdkResult<()>

Unsubscribe from updates for account

Source

pub fn check_libs() -> SdkResult<()>

Check IDL and libdrift_ffi_sys version

panics if there’s a mismatch

Source

pub async fn grpc_subscribe( &self, endpoint: String, x_token: String, opts: GrpcSubscribeOpts, ) -> SdkResult<()>

Subscribe to all: markets, oracles, users, and slot updates over gRPC

Updates are transparently handled by the DriftClient and calls to get User accounts, markets, oracles, etc. will utilize the latest cached updates from the gRPC subscription.

use opts to control what is cached by the client. The gRPC connection will always subscribe to all drift accounts regardless.

  • endpoint - the gRPC endpoint
  • x_token - gRPC authentication X token
  • opts - configure callbacks and caching
Source

pub fn grpc_unsubscribe(&self)

Unsubscribe the gRPC connection

Trait Implementations§

Source§

impl Clone for DriftClient

Source§

fn clone(&self) -> DriftClient

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl UserMargin for DriftClient

Source§

fn calculate_perp_buying_power( &self, user: &User, market: &PerpMarket, oracle_price: i64, collateral_buffer: u64, ) -> SdkResult<u128>

Calculate buying power = free collateral / initial margin ratio

Returns buying power in QUOTE_PRECISION units

Source§

fn calculate_margin_info(&self, user: &User) -> SdkResult<MarginCalculation>

Calculate the user’s live margin information
Source§

fn max_trade_size( &self, user: &Pubkey, market: MarketId, trade_side: PositionDirection, ) -> SdkResult<u64>

Calculate user’s max. trade size in USDC for a given market and direction Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> AlignerFor<1> for T

Source§

type Aligner = AlignTo1<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<1024> for T

Source§

type Aligner = AlignTo1024<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<128> for T

Source§

type Aligner = AlignTo128<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<16> for T

Source§

type Aligner = AlignTo16<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<16384> for T

Source§

type Aligner = AlignTo16384<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<2> for T

Source§

type Aligner = AlignTo2<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<2048> for T

Source§

type Aligner = AlignTo2048<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<256> for T

Source§

type Aligner = AlignTo256<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<32> for T

Source§

type Aligner = AlignTo32<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<32768> for T

Source§

type Aligner = AlignTo32768<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<4> for T

Source§

type Aligner = AlignTo4<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<4096> for T

Source§

type Aligner = AlignTo4096<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<512> for T

Source§

type Aligner = AlignTo512<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<64> for T

Source§

type Aligner = AlignTo64<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<8> for T

Source§

type Aligner = AlignTo8<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> AlignerFor<8192> for T

Source§

type Aligner = AlignTo8192<T>

The AlignTo* type which aligns Self to ALIGNMENT.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<'a, T> RCowCompatibleRef<'a> for T
where T: Clone + 'a,

Source§

type RefC = &'a T

The (preferably) ffi-safe equivalent of &Self.
Source§

type ROwned = T

The owned version of Self::RefC.
Source§

fn as_c_ref(from: &'a T) -> <T as RCowCompatibleRef<'a>>::RefC

Converts a reference to an FFI-safe type
Source§

fn as_rust_ref(from: <T as RCowCompatibleRef<'a>>::RefC) -> &'a T

Converts an FFI-safe type to a reference
Source§

impl<S> ROExtAcc for S

Source§

fn f_get<F>(&self, offset: FieldOffset<S, F, Aligned>) -> &F

Gets a reference to a field, determined by offset. Read more
Source§

fn f_get_mut<F>(&mut self, offset: FieldOffset<S, F, Aligned>) -> &mut F

Gets a muatble reference to a field, determined by offset. Read more
Source§

fn f_get_ptr<F, A>(&self, offset: FieldOffset<S, F, A>) -> *const F

Gets a const pointer to a field, the field is determined by offset. Read more
Source§

fn f_get_mut_ptr<F, A>(&mut self, offset: FieldOffset<S, F, A>) -> *mut F

Gets a mutable pointer to a field, determined by offset. Read more
Source§

impl<S> ROExtOps<Aligned> for S

Source§

fn f_replace<F>(&mut self, offset: FieldOffset<S, F, Aligned>, value: F) -> F

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more
Source§

fn f_swap<F>(&mut self, offset: FieldOffset<S, F, Aligned>, right: &mut S)

Swaps a field (determined by offset) with the same field in right. Read more
Source§

fn f_get_copy<F>(&self, offset: FieldOffset<S, F, Aligned>) -> F
where F: Copy,

Gets a copy of a field (determined by offset). The field is determined by offset. Read more
Source§

impl<S> ROExtOps<Unaligned> for S

Source§

fn f_replace<F>(&mut self, offset: FieldOffset<S, F, Unaligned>, value: F) -> F

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more
Source§

fn f_swap<F>(&mut self, offset: FieldOffset<S, F, Unaligned>, right: &mut S)

Swaps a field (determined by offset) with the same field in right. Read more
Source§

fn f_get_copy<F>(&self, offset: FieldOffset<S, F, Unaligned>) -> F
where F: Copy,

Gets a copy of a field (determined by offset). The field is determined by offset. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SelfOps for T
where T: ?Sized,

Source§

fn eq_id(&self, other: &Self) -> bool

Compares the address of self with the address of other. Read more
Source§

fn piped<F, U>(self, f: F) -> U
where F: FnOnce(Self) -> U, Self: Sized,

Emulates the pipeline operator, allowing method syntax in more places. Read more
Source§

fn piped_ref<'a, F, U>(&'a self, f: F) -> U
where F: FnOnce(&'a Self) -> U,

The same as piped except that the function takes &Self Useful for functions that take &Self instead of Self. Read more
Source§

fn piped_mut<'a, F, U>(&'a mut self, f: F) -> U
where F: FnOnce(&'a mut Self) -> U,

The same as piped, except that the function takes &mut Self. Useful for functions that take &mut Self instead of Self.
Source§

fn mutated<F>(self, f: F) -> Self
where F: FnOnce(&mut Self), Self: Sized,

Mutates self using a closure taking self by mutable reference, passing it along the method chain. Read more
Source§

fn observe<F>(self, f: F) -> Self
where F: FnOnce(&Self), Self: Sized,

Observes the value of self, passing it along unmodified. Useful in long method chains. Read more
Source§

fn into_<T>(self) -> T
where Self: Into<T>,

Performs a conversion with Into. using the turbofish .into_::<_>() syntax. Read more
Source§

fn as_ref_<T>(&self) -> &T
where Self: AsRef<T>, T: ?Sized,

Performs a reference to reference conversion with AsRef, using the turbofish .as_ref_::<_>() syntax. Read more
Source§

fn as_mut_<T>(&mut self) -> &mut T
where Self: AsMut<T>, T: ?Sized,

Performs a mutable reference to mutable reference conversion with AsMut, using the turbofish .as_mut_::<_>() syntax. Read more
Source§

fn drop_(self)
where Self: Sized,

Drops self using method notation. Alternative to std::mem::drop. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<This> TransmuteElement for This
where This: ?Sized,

Source§

unsafe fn transmute_element<T>(self) -> Self::TransmutedPtr
where Self: CanTransmuteElement<T>,

Transmutes the element type of this pointer.. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeIdentity for T
where T: ?Sized,

Source§

type Type = T

This is always Self.
Source§

fn into_type(self) -> Self::Type
where Self: Sized, Self::Type: Sized,

Converts a value back to the original type.
Source§

fn as_type(&self) -> &Self::Type

Converts a reference back to the original type.
Source§

fn as_type_mut(&mut self) -> &mut Self::Type

Converts a mutable reference back to the original type.
Source§

fn into_type_box(self: Box<Self>) -> Box<Self::Type>

Converts a box back to the original type.
Source§

fn into_type_arc(this: Arc<Self>) -> Arc<Self::Type>

Converts an Arc back to the original type. Read more
Source§

fn into_type_rc(this: Rc<Self>) -> Rc<Self::Type>

Converts an Rc back to the original type. Read more
Source§

fn from_type(this: Self::Type) -> Self
where Self: Sized, Self::Type: Sized,

Converts a value back to the original type.
Source§

fn from_type_ref(this: &Self::Type) -> &Self

Converts a reference back to the original type.
Source§

fn from_type_mut(this: &mut Self::Type) -> &mut Self

Converts a mutable reference back to the original type.
Source§

fn from_type_box(this: Box<Self::Type>) -> Box<Self>

Converts a box back to the original type.
Source§

fn from_type_arc(this: Arc<Self::Type>) -> Arc<Self>

Converts an Arc back to the original type.
Source§

fn from_type_rc(this: Rc<Self::Type>) -> Rc<Self>

Converts an Rc back to the original type.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,