### Install @drift-labs/sdk Source: https://drift-labs.github.io/protocol-v2/sdk/index.html Install the Drift Protocol SDK using npm. This is the first step to using the SDK in your project. ```bash npm i @drift-labs/sdk ``` -------------------------------- ### start Method Source: https://drift-labs.github.io/protocol-v2/sdk/classes/pyth.PythConnection.html Initiates the process of receiving price updates. Registered callbacks will be invoked upon Pyth price account updates. ```APIDOC ### start - **start(): Promise** #### Returns Promise ``` -------------------------------- ### startPolling Source: https://drift-labs.github.io/protocol-v2/sdk/classes/BulkAccountLoader.html Starts the background polling mechanism to fetch account updates at the configured frequency. ```APIDOC ## startPolling ### Description Activates the polling mechanism to periodically fetch updates for the accounts being monitored. ``` -------------------------------- ### get Method Source: https://drift-labs.github.io/protocol-v2/sdk/classes/OpenbookV2FulfillmentConfigMap.html Retrieves an Openbook V2 market fulfillment configuration by its market index. ```APIDOC ## get(marketIndex: number) ### Description Retrieves the Openbook V2 fulfillment configuration associated with the given market index. ### Parameters * **marketIndex** (number) - The index of the market for which to retrieve the configuration. ### Returns * OpenbookV2FulfillmentConfigAccount - The fulfillment configuration account for the specified market index. ``` -------------------------------- ### updateSpotMarketScaleInitialAssetWeightStart Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Updates the starting weight for scaling the initial asset in a spot market. This parameter is crucial for risk management and position sizing calculations. ```APIDOC ## updateSpotMarketScaleInitialAssetWeightStart ### Description Updates the starting weight for scaling the initial asset in a spot market. ### Method (Not specified, assumed to be a client method call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Parameters * **spotMarketIndex** (number) - Required - The index of the spot market to update. * **scaleInitialAssetWeightStart** (BN) - Required - The new starting weight for scaling the initial asset. ### Returns Promise ``` -------------------------------- ### getUpdateSpotMarketScaleInitialAssetWeightStartIx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Generates a transaction instruction to update the initial asset weight start for scaling in a specific spot market. ```APIDOC ## getUpdateSpotMarketScaleInitialAssetWeightStartIx ### Description Generates a transaction instruction to update the initial asset weight start for scaling in a specific spot market. ### Method N/A (SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **TransactionInstruction**: The generated transaction instruction. #### Response Example None ``` -------------------------------- ### initialize Source: https://drift-labs.github.io/protocol-v2/sdk/classes/TokenFaucet.html Initializes the faucet. ```APIDOC ## initialize ### Description Initializes the faucet. ### Returns Promise - A promise that resolves to the transaction signature for the initialization. ``` -------------------------------- ### PollingTokenAccountSubscriber.didSubscriptionSucceed Source: https://drift-labs.github.io/protocol-v2/sdk/classes/PollingTokenAccountSubscriber.html Checks if the subscription has successfully started. ```APIDOC ## didSubscriptionSucceed ### Description Checks if the subscription has successfully started. ### Returns * boolean - True if the subscription succeeded, false otherwise. ``` -------------------------------- ### Initialize Drift SDK, Wallet, and User Account Source: https://drift-labs.github.io/protocol-v2/sdk/index.html Sets up the Drift SDK configuration, establishes a wallet and provider connection, and initializes a user account by depositing collateral. Ensure ANCHOR_WALLET and ANCHOR_PROVIDER_URL environment variables are set. ```typescript import * as anchor from '@coral-xyz/anchor'; import { AnchorProvider } from '@coral-xyz/anchor'; import { getAssociatedTokenAddress, TOKEN_PROGRAM_ID } from '@solana/spl-token'; import { Connection, Keypair, PublicKey } from '@solana/web3.js'; import { calculateReservePrice, DriftClient, User, initialize, PositionDirection, convertToNumber, calculateTradeSlippage, PRICE_PRECISION, QUOTE_PRECISION, Wallet, PerpMarkets, BASE_PRECISION, getMarketOrderParams, BulkAccountLoader, BN, calculateBidAskPrice, getMarketsAndOraclesForSubscription, calculateEstimatedPerpEntryPrice, } from '../sdk'; export const getTokenAddress = ( mintAddress: string, userPubKey: string ): Promise => { return getAssociatedTokenAddress( new PublicKey(mintAddress), new PublicKey(userPubKey) ); }; const main = async () => { const env = 'devnet'; // const env = 'mainnet-beta'; // Initialize Drift SDK const sdkConfig = initialize({ env }); // Set up the Wallet and Provider if (!process.env.ANCHOR_WALLET) { throw new Error('ANCHOR_WALLET env var must be set.'); } if (!process.env.ANCHOR_PROVIDER_URL) { throw new Error('ANCHOR_PROVIDER_URL env var must be set.'); } const provider = anchor.AnchorProvider.local( process.env.ANCHOR_PROVIDER_URL, { preflightCommitment: 'confirmed', skipPreflight: false, commitment: 'confirmed', } ); // Check SOL Balance const lamportsBalance = await provider.connection.getBalance( provider.wallet.publicKey ); console.log( provider.wallet.publicKey.toString(), env, 'SOL balance:', lamportsBalance / 10 ** 9 ); // Misc. other things to set up const usdcTokenAddress = await getTokenAddress( sdkConfig.USDC_MINT_ADDRESS, provider.wallet.publicKey.toString() ); // Set up the Drift Client const driftPublicKey = new PublicKey(sdkConfig.DRIFT_PROGRAM_ID); const bulkAccountLoader = new BulkAccountLoader( provider.connection, 'confirmed', 1000 ); const driftClient = new DriftClient({ connection: provider.connection, wallet: provider.wallet, programID: driftPublicKey, accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); await driftClient.subscribe(); console.log('subscribed to driftClient'); // Set up user client const user = new User({ driftClient: driftClient, userAccountPublicKey: await driftClient.getUserAccountPublicKey(), accountSubscription: { type: 'polling', accountLoader: bulkAccountLoader, }, }); //// Check if user account exists for the current wallet const userAccountExists = await user.exists(); if (!userAccountExists) { console.log( 'initializing to', env, ' drift account for', provider.wallet.publicKey.toString() ); //// Create a Drift V2 account by Depositing some USDC ($10,000 in this case) const depositAmount = new BN(10000).mul(QUOTE_PRECISION); await driftClient.initializeUserAccountAndDepositCollateral( depositAmount, await getTokenAddress( usdcTokenAddress.toString(), provider.wallet.publicKey.toString() ) ); } await user.subscribe(); // Get current price const solMarketInfo = PerpMarkets[env].find( (market) => market.baseAssetSymbol === 'SOL' ); const marketIndex = solMarketInfo.marketIndex; // Get vAMM bid and ask price const [bid, ask] = calculateBidAskPrice( driftClient.getPerpMarketAccount(marketIndex).amm, driftClient.getOracleDataForPerpMarket(marketIndex) ); const formattedBidPrice = convertToNumber(bid, PRICE_PRECISION); const formattedAskPrice = convertToNumber(ask, PRICE_PRECISION); console.log( env, `vAMM bid: $${formattedBidPrice} and ask: $${formattedAskPrice}` ); const solMarketAccount = driftClient.getPerpMarketAccount( solMarketInfo.marketIndex ); console.log(env, `Placing a 1 SOL-PERP LONG order`); const txSig = await driftClient.placePerpOrder( getMarketOrderParams({ baseAssetAmount: new BN(1).mul(BASE_PRECISION), direction: PositionDirection.LONG, ``` -------------------------------- ### startBlockhashRefreshLoop Source: https://drift-labs.github.io/protocol-v2/sdk/classes/FastSingleTxSender.html Starts a loop to continuously refresh the blockhash. ```APIDOC ## startBlockhashRefreshLoop ### Description Starts a background loop responsible for continuously refreshing the blockhash to ensure transactions are submitted with up-to-date information. ### Method (Implied: SDK Method Call) ### Returns void ``` -------------------------------- ### subscribe Source: https://drift-labs.github.io/protocol-v2/sdk/classes/BlockhashSubscriber.html Starts the process of subscribing to blockhash updates. ```APIDOC ## subscribe ### Description Initiates the subscription to receive blockhash updates. ### Returns Promise ``` -------------------------------- ### initialize Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes the protocol with a specified USDC mint and admin control settings for prices. ```APIDOC ## initialize ### Description Initializes the protocol with a specified USDC mint and admin control settings for prices. ### Method (Not specified, likely a client-side method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **usdcMint** (PublicKey) - Required - The public key of the USDC mint. * **_adminControlsPrices** (boolean) - Required - Whether admin controls prices. ### Returns * **Promise<[string]>** - A promise that resolves to an array containing a string, likely a transaction signature or confirmation. ``` -------------------------------- ### get Source: https://drift-labs.github.io/protocol-v2/sdk/classes/NodeList.html Retrieves a node from the NodeList by its order signature. ```APIDOC ## get(orderSignature: string): DLOBNodeMap[NodeType] ### Description Retrieves a node from the NodeList by its order signature. ### Parameters * **orderSignature** (string) - The signature of the order to retrieve. ### Returns DLOBNodeMap[NodeType] - The node associated with the order signature. ``` -------------------------------- ### getInitializeUserInstructions Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Generates instructions to initialize a user. This can include setting a sub-account ID, a name, and referrer information. ```APIDOC ## getInitializeUserInstructions ### Description Generates instructions to initialize a user. This can include setting a sub-account ID, a name, and referrer information. ### Method N/A (SDK Method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **subAccountId** (number) - Optional - Defaults to 0. The sub-account ID. * **name** (string) - Optional - The name for the user. * **referrerInfo** (ReferrerInfo) - Optional - Information about the referrer. ### Returns Promise<[PublicKey, TransactionInstruction]> ``` -------------------------------- ### PublicKey.toStringTag Source: https://drift-labs.github.io/protocol-v2/sdk/classes/PublicKey.html Accessor to get the string tag of the PublicKey object. ```APIDOC ## get [toStringTag]() ### Description Returns the string tag of the PublicKey object. ### Returns - string ``` -------------------------------- ### createInitializeUserAccountAndDepositCollateralIxs Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Creates instructions to initialize a user account and deposit collateral. ```APIDOC ## createInitializeUserAccountAndDepositCollateralIxs ### Description Creates instructions to initialize a user account and deposit collateral. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **amount** (BN) - The amount of collateral to deposit. * **userTokenAccount** (PublicKey) - The user's token account. * **marketIndex** (number, optional) - The market index. Defaults to 0. * **subAccountId** (number, optional) - The subaccount ID. Defaults to 0. * **name** (string, optional) - The name of the user account. * **fromSubAccountId** (number, optional) - The subaccount ID to transfer from. * **referrerInfo** (ReferrerInfo, optional) - Information about the referrer. * **donateAmount** (BN, optional) - The amount to donate. * **customMaxMarginRatio** (number, optional) - A custom maximum margin ratio. ### Returns * **Promise<{ ixs: TransactionInstruction[]; userAccountPublicKey: PublicKey; }>** - A promise that resolves to an object containing the transaction instructions and the user account public key. ``` -------------------------------- ### getL3 Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DLOBSubscriber.html Get the L3 order book for a given market. ```APIDOC ## getL3(__namedParameters: { marketIndex?: number; marketName?: string; marketType?: MarketType; }) ### Description Get the L3 order book for a given market. ### Parameters #### __namedParameters: { marketIndex?: number; marketName?: string; marketType?: MarketType; } - **marketIndex** (number) - Optional - The index of the market. - **marketName** (string) - Optional - The name of the market. - **marketType** (MarketType) - Optional - The type of the market. ### Returns - L3OrderBook - The L3 order book for the specified market. ``` -------------------------------- ### AdminClient Initialization Methods Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Methods for initializing various components of the protocol, including markets, oracles, and user accounts. ```APIDOC ## AdminClient Initialization Methods Methods for initializing various components of the protocol, including markets, oracles, and user accounts. ### Methods - `initialize` - `initializeInsuranceFundStake` - `initializeOpenbookV2FulfillmentConfig` - `initializePerpMarket` - `initializePhoenixFulfillmentConfig` - `initializePredictionMarket` - `initializePrelaunchOracle` - `initializeProtocolIfSharesTransferConfig` - `initializePythPullOracle` - `initializeReferrerName` - `initializeSerumFulfillmentConfig` - `initializeSpotMarket` - `initializeUserAccount` - `initializeUserAccountAndDepositCollateral` - `initializeUserAccountForDevnet` ``` -------------------------------- ### getL2 Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DLOBSubscriber.html Get the L2 order book for a given market. ```APIDOC ## getL2(__namedParameters: { depth?: number; fallbackL2Generators?: L2OrderBookGenerator[]; includeVamm?: boolean; marketIndex?: number; marketName?: string; marketType?: MarketType; numVammOrders?: number; }) ### Description Get the L2 order book for a given market. ### Parameters #### __namedParameters: { depth?: number; fallbackL2Generators?: L2OrderBookGenerator[]; includeVamm?: boolean; marketIndex?: number; marketName?: string; marketType?: MarketType; numVammOrders?: number; } - **depth** (number) - Optional - The depth of the L2 order book to retrieve. - **fallbackL2Generators** (L2OrderBookGenerator[]) - Optional - Fallback generators for L2 order book. - **includeVamm** (boolean) - Optional - Whether to include VAMM orders. - **marketIndex** (number) - Optional - The index of the market. - **marketName** (string) - Optional - The name of the market. - **marketType** (MarketType) - Optional - The type of the market. - **numVammOrders** (number) - Optional - The number of VAMM orders to include. ### Returns - L2OrderBook - The L2 order book for the specified market. ``` -------------------------------- ### get Source: https://drift-labs.github.io/protocol-v2/sdk/interfaces/UserMapInterface.html Retrieves a User object from the map using a string key. ```APIDOC ## get ### Description Retrieves a User object from the map using a string key. ### Method get ### Parameters #### key: string ### Returns User ``` -------------------------------- ### OpenbookV2FulfillmentConfigMap Constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/OpenbookV2FulfillmentConfigMap.html Initializes a new instance of the OpenbookV2FulfillmentConfigMap class. ```APIDOC ## new OpenbookV2FulfillmentConfigMap(driftClient: DriftClient) ### Description Initializes a new instance of the OpenbookV2FulfillmentConfigMap class. ### Parameters * **driftClient** (DriftClient) - The DriftClient instance to use. ### Returns * OpenbookV2FulfillmentConfigMap - The newly created instance. ``` -------------------------------- ### initializeSpotMarket Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes a new spot market with specified parameters. This method allows for detailed configuration of market dynamics, risk parameters, and optional settings. ```APIDOC ## initializeSpotMarket ### Description Initializes a new spot market with specified parameters. This method allows for detailed configuration of market dynamics, risk parameters, and optional settings. ### Method initializeSpotMarket(mint: PublicKey, optimalUtilization: number, optimalRate: number, maxRate: number, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: number, maintenanceAssetWeight: number, initialLiabilityWeight: number, maintenanceLiabilityWeight: number, imfFactor?: number, liquidatorFee?: number, ifLiquidationFee?: number, activeStatus?: boolean, assetTier?: { collateral: {}; }, scaleInitialAssetWeightStart?: BN, withdrawGuardThreshold?: BN, orderTickSize?: BN, orderStepSize?: BN, ifTotalFactor?: number, name?: string, marketIndex?: number): Promise ### Parameters #### Path Parameters * **mint** (PublicKey) - Required - The mint address of the asset for the new market. * **optimalUtilization** (number) - Required - The optimal utilization rate for the market. * **optimalRate** (number) - Required - The optimal interest rate for the market. * **maxRate** (number) - Required - The maximum interest rate for the market. * **oracle** (PublicKey) - Required - The public key of the oracle. * **oracleSource** (OracleSource) - Required - The source of the oracle data. * **initialAssetWeight** (number) - Required - The initial weight of the asset. * **maintenanceAssetWeight** (number) - Required - The maintenance weight of the asset. * **initialLiabilityWeight** (number) - Required - The initial weight of the liability. * **maintenanceLiabilityWeight** (number) - Required - The maintenance weight of the liability. * **imfFactor** (number) - Optional - The IMF factor, defaults to 0. * **liquidatorFee** (number) - Optional - The fee for liquidators, defaults to 0. * **ifLiquidationFee** (number) - Optional - The liquidation fee, defaults to 0. * **activeStatus** (boolean) - Optional - The active status of the market, defaults to true. * **assetTier** (object) - Optional - The asset tier configuration, defaults to AssetTier.COLLATERAL. * **collateral** (object) - Required - Collateral configuration. * **scaleInitialAssetWeightStart** (BN) - Optional - The starting point for scaling initial asset weight, defaults to ZERO. * **withdrawGuardThreshold** (BN) - Optional - The threshold for withdrawing guards, defaults to ZERO. * **orderTickSize** (BN) - Optional - The tick size for orders, defaults to ONE. * **orderStepSize** (BN) - Optional - The step size for orders, defaults to ONE. * **ifTotalFactor** (number) - Optional - The total factor, defaults to 0. * **name** (string) - Optional - The name of the market, defaults to DEFAULT_MARKET_NAME. * **marketIndex** (number) - Optional - The index of the market. ### Returns Promise ``` -------------------------------- ### get Source: https://drift-labs.github.io/protocol-v2/sdk/classes/UserStatsMap.html Retrieves user statistics for a given authority public key. ```APIDOC ## get(authorityPublicKey: string): UserStats ### Description Retrieves user statistics for a given authority public key. ### Parameters * **authorityPublicKey** (string) - Required - The public key of the authority. ### Returns UserStats ``` -------------------------------- ### initialize Source: https://drift-labs.github.io/protocol-v2/sdk/functions/initialize.html Allows customization of the SDK's environment and endpoints. You can pass individual settings to override the settings with your own presets. Defaults to master environment if you don't use this function. ```APIDOC ## initialize ### Description Allows customization of the SDK's environment and endpoints. You can pass individual settings to override the settings with your own presets. Defaults to master environment if you don't use this function. ### Method initialize ### Parameters #### props - **env** (DriftEnv) - Required - The Drift environment to use. - **overrideEnv** (Partial) - Optional - Allows overriding specific environment settings. ``` -------------------------------- ### getOldestActionTs Source: https://drift-labs.github.io/protocol-v2/sdk/classes/UserStats.html Gets the timestamp of the oldest action for a given user statistics account. ```APIDOC ## getOldestActionTs ### Description Gets the timestamp of the oldest action for a given user statistics account. ### Parameters * **account**: UserStatsAccount - The user statistics account. ### Returns number - The timestamp of the oldest action. ``` -------------------------------- ### initializeOpenbookV2FulfillmentConfig Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes the Openbook V2 fulfillment configuration for a given market index and Openbook market. ```APIDOC ## initializeOpenbookV2FulfillmentConfig ### Description Initializes the Openbook V2 fulfillment configuration for a given market index and Openbook market. ### Method (Not specified, likely a client-side method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **marketIndex** (number) - Required - The index of the market. * **openbookMarket** (PublicKey) - Required - The public key of the Openbook market. ### Returns * **Promise** - A promise that resolves to a string representing the transaction signature or confirmation. ``` -------------------------------- ### forceGetStateAccount Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Forces a fetch from the RPC to get the state account. Useful for anchor tests. ```APIDOC ## forceGetStateAccount ### Description Forces a fetch from the RPC to retrieve the state account. This is particularly useful for anchor tests. ### Method (Not specified, assumed to be a client method) ### Parameters (None) ### Response #### Success Response * **Promise** - A promise that resolves to the StateAccount. ``` -------------------------------- ### constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes a new AdminClient instance. This client is used for administrative actions within the Drift Protocol. ```APIDOC ## constructor AdminClient ### Description Initializes a new AdminClient instance. This client is used for administrative actions within the Drift Protocol. ### Parameters * **config** (DriftClientConfig) - Required - Configuration object for the Drift client. ### Returns AdminClient ``` -------------------------------- ### get Method Source: https://drift-labs.github.io/protocol-v2/sdk/classes/PhoenixFulfillmentConfigMap.html Retrieves the Phoenix fulfillment configuration account for a given market index. ```APIDOC ## get ### Description Retrieves the Phoenix fulfillment configuration account for a given market index. ### Signature `get(marketIndex: number): PhoenixV1FulfillmentConfigAccount` ### Parameters #### marketIndex - **marketIndex** (number) - The index of the market. ``` -------------------------------- ### constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/JupiterClient.html Initializes a new instance of the JupiterClient class. ```APIDOC ## constructor ### Description Initializes a new instance of the JupiterClient class. ### Parameters #### __namedParameters: { connection: Connection; url?: string; } - **connection**: Connection - The connection object to use. - **url** (string) - Optional - The URL for the Jupiter service. ``` -------------------------------- ### getInitializePrelaunchOracleIx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes a pre-launch oracle for a perpetual futures market, with optional initial and maximum price settings. ```APIDOC ## getInitializePrelaunchOracleIx ### Description Initializes a pre-launch oracle for a perpetual futures market, allowing for optional initial and maximum price configurations. ### Method getInitializePrelaunchOracleIx(perpMarketIndex: number, price?: BN, maxPrice?: BN): Promise ### Parameters #### Path Parameters * **perpMarketIndex** (number) - Required - The index of the perpetual futures market. * **price** (BN) - Optional - The initial price for the oracle. * **maxPrice** (BN) - Optional - The maximum price for the oracle. ### Returns Promise ``` -------------------------------- ### get Source: https://drift-labs.github.io/protocol-v2/sdk/classes/UserMap.html Retrieves a User object from the UserMap using its public key. Returns undefined if the user is not found. ```APIDOC ## get ### Description Gets the User for a particular userAccountPublicKey. If no User exists, undefined is returned. ### Parameters * **key** (string) - The userAccountPublicKey to get the User for. ### Returns User | undefined - The User object if found, otherwise undefined. ``` -------------------------------- ### initializeUserAccountAndDepositCollateral Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Creates a user account and deposits initial collateral in a single operation. This simplifies the onboarding process. ```APIDOC ## initializeUserAccountAndDepositCollateral ### Description Creates the User account for a user, and deposits some initial collateral. ### Method N/A (SDK Method) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **amount** (BN) - Required - The amount of collateral to deposit. * **userTokenAccount** (PublicKey) - Required - The user's token account. * **marketIndex** (number) - Optional - The market index (defaults to 0). * **subAccountId** (number) - Optional - The sub-account ID (defaults to 0). * **name** (string) - Optional - The name for the user account. * **fromSubAccountId** (number) - Optional - The sub-account ID to transfer from. * **referrerInfo** (ReferrerInfo) - Optional - Information about the referrer. * **donateAmount** (BN) - Optional - The amount to donate. * **txParams** (TxParams) - Optional - Parameters for the transaction. * **customMaxMarginRatio** (number) - Optional - Custom maximum margin ratio. ### Request Example N/A ### Response #### Success Response * **[string, PublicKey]** - A tuple containing the transaction signature and the new user account's public key. ### Response Example ```json [ "", "" ] ``` ``` -------------------------------- ### DLOB Constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DLOB.html Initializes a new instance of the DLOB class. No specific setup is required beyond instantiation. ```typescript new DLOB(): DLOB ``` -------------------------------- ### createAssociatedTokenAccountAndMintToInstructions Source: https://drift-labs.github.io/protocol-v2/sdk/classes/TokenFaucet.html Generates instructions to create an associated token account and mint tokens. ```APIDOC ## createAssociatedTokenAccountAndMintToInstructions ### Description Generates instructions to create an associated token account and mint tokens. ### Parameters - **userPublicKey**: PublicKey - The public key of the user. - **amount**: BN - The amount of tokens to mint. ### Returns Promise<[PublicKey, TransactionInstruction, TransactionInstruction]> - A promise that resolves to a tuple containing the public key of the created token account and two transaction instructions. ``` -------------------------------- ### initializePrelaunchOracle Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes a prelaunch oracle for a given perpetual market index, with optional price and max price. ```APIDOC ## initializePrelaunchOracle ### Description Initializes a prelaunch oracle for a given perpetual market index, with optional price and max price. ### Method (Not specified, likely a client-side method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **perpMarketIndex** (number) - Required - The index of the perpetual market. * **price** (BN) - Optional - The initial price. * **maxPrice** (BN) - Optional - The maximum price. ### Returns * **Promise** - A promise that resolves to a string representing the transaction signature or confirmation. ``` -------------------------------- ### subscribe Source: https://drift-labs.github.io/protocol-v2/sdk/classes/EventSubscriber.html Initiates the subscription to listen for new events. This method should be called to start receiving real-time event data. ```APIDOC ## subscribe ### Description Initiates the subscription to listen for new events. ### Returns * Promise - A promise that resolves to true if the subscription was successful, false otherwise. ``` -------------------------------- ### preparePlaceAndTakePerpOrderWithAdditionalOrders Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Prepares transactions to place and take a perpetual order, along with additional orders. This method allows for specifying maker, referrer, bracket order parameters, and transaction configurations, including options to cancel existing orders, settle PnL, and exit early if simulation fails. ```APIDOC ## preparePlaceAndTakePerpOrderWithAdditionalOrders ### Description Prepares transactions to place and take a perpetual order, along with additional orders. This method allows for specifying maker, referrer, bracket order parameters, and transaction configurations, including options to cancel existing orders, settle PnL, and exit early if simulation fails. ### Method Not specified (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **orderParams** (OptionalOrderParams) - Required - Parameters for the primary perpetual order. * **makerInfo** (MakerInfo | MakerInfo[]) - Optional - Information about the maker. * **referrerInfo** (ReferrerInfo) - Optional - Information about the referrer. * **bracketOrdersParams** (OptionalOrderParams[]) - Optional - Parameters for bracket orders (defaults to an empty array). * **txParams** (TxParams) - Optional - Transaction parameters. * **subAccountId** (number) - Optional - The sub-account ID. * **cancelExistingOrders** (boolean) - Optional - Whether to cancel existing orders. * **settlePnl** (boolean) - Optional - Whether to settle PnL. * **exitEarlyIfSimFails** (boolean) - Optional - Whether to exit early if simulation fails. ### Request Example ```json { "orderParams": { "orderType": "limit", "marketIndex": 0, "side": "long", "price": 100, "baseAssetAmount": 10, "quoteAssetAmount": 1000 }, "makerInfo": {}, "referrerInfo": {}, "bracketOrdersParams": [], "txParams": {}, "subAccountId": 1, "cancelExistingOrders": true, "settlePnl": true, "exitEarlyIfSimFails": true } ``` ### Response #### Success Response (200) * **placeAndTakeTx** (Transaction | VersionedTransaction) - The transaction to place and take the perpetual order. * **cancelExistingOrdersTx** (Transaction | VersionedTransaction) - The transaction to cancel existing orders. * **settlePnlTx** (Transaction | VersionedTransaction) - The transaction to settle PnL. ``` -------------------------------- ### ClockSubscriber Methods Source: https://drift-labs.github.io/protocol-v2/sdk/classes/ClockSubscriber.html Provides methods to get Unix timestamps, set timeouts, subscribe to clock updates, and unsubscribe. ```APIDOC ## Methods ### getUnixTs * **getUnixTs()**: number * Returns the current Unix timestamp. ### subscribe * **subscribe()**: Promise * Subscribes to clock updates. ### unsubscribe * **unsubscribe(onResub?: boolean)**: Promise * Unsubscribes from clock updates. * **Parameters**: * **onResub** (boolean) - Optional. Defaults to false. Indicates if the unsubscribe is part of a resubscription process. ``` -------------------------------- ### OpenbookV2Subscriber Constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/OpenbookV2Subscriber.html Initializes a new instance of the OpenbookV2Subscriber class. ```APIDOC ## new OpenbookV2Subscriber ### Description Initializes a new instance of the OpenbookV2Subscriber class. ### Parameters #### config: OpenbookV2SubscriberConfig - **config** (OpenbookV2SubscriberConfig) - The configuration object for the subscriber. ### Returns OpenbookV2Subscriber - The newly created OpenbookV2Subscriber instance. ``` -------------------------------- ### Generate Solana Keypair and Configure Environment Source: https://drift-labs.github.io/protocol-v2/sdk/index.html Generate a new Solana keypair for your bot and configure your environment variables. You will need to fund the generated wallet address with USDC on mainnet. ```bash # Generate a keypair solana-keygen new # Get the pubkey for the new wallet (You will need to send USDC to this address to Deposit into Drift (only on mainnet - devnet has a faucet for USDC)) solana address # Put the private key into your .env to be used by your bot cd {projectLocation} echo BOT_PRIVATE_KEY=`cat ~/.config/solana/id.json` >> .env ``` -------------------------------- ### forceGetUserAccount Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Forces a fetch from the RPC to get the user account, optionally for a specific sub-account ID. Useful for anchor tests. ```APIDOC ## forceGetUserAccount ### Description Forces a fetch from the RPC to retrieve the user account. This method is useful for anchor tests and can optionally fetch a specific sub-account. ### Method (Not specified, assumed to be a client method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **subAccountId** (number) - Optional - The ID of the sub-account to fetch. ### Response #### Success Response * **Promise** - A promise that resolves to the UserAccount. ``` -------------------------------- ### getInitializeOpenbookV2FulfillmentConfigIx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Generates a transaction instruction to initialize an Openbook V2 fulfillment configuration. ```APIDOC ## getInitializeOpenbookV2FulfillmentConfigIx ### Description Generates a transaction instruction to initialize an Openbook V2 fulfillment configuration. ### Method `getInitializeOpenbookV2FulfillmentConfigIx(marketIndex: number, openbookMarket: PublicKey): Promise` ### Parameters #### Path Parameters - **marketIndex** (number) - Required - The index of the market. - **openbookMarket** (PublicKey) - Required - The public key of the Openbook market. ``` -------------------------------- ### forceGetSpotMarketAccount Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Forces a fetch from the RPC to get the spot market account for a given market index. Useful for anchor tests. ```APIDOC ## forceGetSpotMarketAccount ### Description Forces a fetch from the RPC to retrieve the spot market account. This is particularly useful for anchor tests. ### Method (Not specified, assumed to be a client method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **marketIndex** (number) - Required - The index of the spot market. ### Response #### Success Response * **Promise** - A promise that resolves to the SpotMarketAccount. ``` -------------------------------- ### PhoenixFulfillmentConfigMap Constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/PhoenixFulfillmentConfigMap.html Initializes a new instance of the PhoenixFulfillmentConfigMap class. ```APIDOC ## constructor ### Description Initializes a new instance of the PhoenixFulfillmentConfigMap class. ### Signature `new PhoenixFulfillmentConfigMap(driftClient: DriftClient): PhoenixFulfillmentConfigMap` ### Parameters #### driftClient - **driftClient** (DriftClient) - The DriftClient instance to use. ``` -------------------------------- ### forceGetPerpMarketAccount Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Forces a fetch from the RPC to get the perpetual market account for a given market index. Useful for anchor tests. ```APIDOC ## forceGetPerpMarketAccount ### Description Forces a fetch from the RPC to retrieve the perpetual market account. This is particularly useful for anchor tests. ### Method (Not specified, assumed to be a client method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **marketIndex** (number) - Required - The index of the perpetual market. ### Response #### Success Response * **Promise** - A promise that resolves to the PerpMarketAccount. ``` -------------------------------- ### getSignedTransactionMap Source: https://drift-labs.github.io/protocol-v2/sdk/classes/TxHandler.html Get a map of signed transactions from an array of transactions to sign. This method allows for batch signing of multiple transactions. ```APIDOC ## getSignedTransactionMap ### Description Get a map of signed transactions from an array of transactions to sign. ### Method (Not specified, likely a class method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **txsToSignMap**: T - Required - A map of transactions to be signed. * **wallet**: IWallet - Optional - The wallet to use for signing. ### Request Example ```json { "txsToSignMap": { "tx1": Transaction, "tx2": VersionedTransaction }, "wallet": { ... } // Wallet object } ``` ### Response #### Success Response (200) * **signedTxData**: SignedTxData[] - An array of signed transaction data. * **signedTxMap**: T - The original map with transactions now signed. #### Response Example ```json { "signedTxData": [ { ... } ], "signedTxMap": { "tx1": SignedTransaction, "tx2": SignedVersionedTransaction } } ``` ``` -------------------------------- ### getInitializeSpotMarketIx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Generates a transaction instruction to initialize a new spot market. This involves setting various parameters related to asset weights, rates, and oracle configurations. ```APIDOC ## getInitializeSpotMarketIx ### Description Generates a transaction instruction to initialize a new spot market. This involves setting various parameters related to asset weights, rates, and oracle configurations. ### Method `getInitializeSpotMarketIx(mint: PublicKey, optimalUtilization: number, optimalRate: number, maxRate: number, oracle: PublicKey, oracleSource: OracleSource, initialAssetWeight: number, maintenanceAssetWeight: number, initialLiabilityWeight: number, maintenanceLiabilityWeight: number, imfFactor?: number, liquidatorFee?: number, ifLiquidationFee?: number, activeStatus?: boolean, assetTier?: { collateral: {}; }, scaleInitialAssetWeightStart?: BN, withdrawGuardThreshold?: BN, orderTickSize?: BN, orderStepSize?: BN, ifTotalFactor?: number, name?: string, marketIndex?: number): Promise` ### Parameters #### Path Parameters * **mint** (PublicKey) - Required - The mint address of the asset. * **optimalUtilization** (number) - Required - The optimal utilization rate for the market. * **optimalRate** (number) - Required - The optimal interest rate for the market. * **maxRate** (number) - Required - The maximum interest rate for the market. * **oracle** (PublicKey) - Required - The public key of the oracle. * **oracleSource** (OracleSource) - Required - The source of the oracle data. * **initialAssetWeight** (number) - Required - The initial asset weight. * **maintenanceAssetWeight** (number) - Required - The maintenance asset weight. * **initialLiabilityWeight** (number) - Required - The initial liability weight. * **maintenanceLiabilityWeight** (number) - Required - The maintenance liability weight. * **imfFactor** (number) - Optional - The IMF factor, defaults to 0. * **liquidatorFee** (number) - Optional - The liquidator fee, defaults to 0. * **ifLiquidationFee** (number) - Optional - The liquidation fee, defaults to 0. * **activeStatus** (boolean) - Optional - The active status of the market, defaults to true. * **assetTier** (object) - Optional - The asset tier configuration, defaults to AssetTier.COLLATERAL. * **collateral** (object) - Required - Collateral configuration. * **scaleInitialAssetWeightStart** (BN) - Optional - The start of the scale for initial asset weight, defaults to ZERO. * **withdrawGuardThreshold** (BN) - Optional - The withdraw guard threshold, defaults to ZERO. * **orderTickSize** (BN) - Optional - The tick size for orders, defaults to ONE. * **orderStepSize** (BN) - Optional - The step size for orders, defaults to ONE. * **ifTotalFactor** (number) - Optional - The total factor, defaults to 0. * **name** (string) - Optional - The name of the market, defaults to DEFAULT_MARKET_NAME. * **marketIndex** (number) - Optional - The index of the market. ### Returns Promise ``` -------------------------------- ### getInitializeProtocolIfSharesTransferConfigIx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes the protocol's share transfer configuration. This is a standalone initialization function. ```APIDOC ## getInitializeProtocolIfSharesTransferConfigIx ### Description Initializes the protocol's configuration for share transfers. ### Method getInitializeProtocolIfSharesTransferConfigIx(): Promise ### Parameters This method does not take any parameters. ### Returns Promise ``` -------------------------------- ### getReferrerNamePublicKeySync Source: https://drift-labs.github.io/protocol-v2/sdk/functions/getReferrerNamePublicKeySync.html Synchronously gets the public key for a given referrer name. This is a protected method and may not be intended for direct external use. ```APIDOC ## getReferrerNamePublicKeySync ### Description Synchronously retrieves the public key associated with a given referrer name. This method is part of the SDK and is used internally or by advanced users. ### Method Signature `getReferrerNamePublicKeySync(programId: PublicKey, nameBuffer: number[]): PublicKey` ### Parameters #### Path Parameters * **programId** (PublicKey) - Required - The program ID. * **nameBuffer** (number[]) - Required - A buffer representing the referrer name. ### Returns * **PublicKey** - The public key associated with the referrer name. ``` -------------------------------- ### initializePhoenixFulfillmentConfig Source: https://drift-labs.github.io/protocol-v2/sdk/classes/AdminClient.html Initializes the Phoenix fulfillment configuration for a given market index and Phoenix market. ```APIDOC ## initializePhoenixFulfillmentConfig ### Description Initializes the Phoenix fulfillment configuration for a given market index and Phoenix market. ### Method (Not specified, likely a client-side method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters * **marketIndex** (number) - Required - The index of the market. * **phoenixMarket** (PublicKey) - Required - The public key of the Phoenix market. ### Returns * **Promise** - A promise that resolves to a string representing the transaction signature or confirmation. ``` -------------------------------- ### prepareTx Source: https://drift-labs.github.io/protocol-v2/sdk/classes/ForwardOnlyTxSender.html Prepares a transaction for sending. This method handles the necessary steps to get a transaction ready, including signing and applying options. ```APIDOC ## prepareTx ### Description Prepares a transaction for sending. ### Method POST (assumed, as it prepares a transaction) ### Endpoint /prepareTx (assumed) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **tx** (Transaction) - Required - The transaction to prepare. - **additionalSigners** (Signer[]) - Required - Additional signers for the transaction. - **opts** (ConfirmOptions) - Required - Confirmation options. - **preSigned** (boolean) - Optional - Indicates if the transaction is pre-signed. ``` -------------------------------- ### getDepositInstruction Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Generates a transaction instruction to deposit assets into a market. This method handles the creation of necessary instructions for depositing funds. ```APIDOC ## getDepositInstruction ### Description Generates a transaction instruction to deposit assets into a market. This method handles the creation of necessary instructions for depositing funds, including optional parameters for sub-account, reduce-only, and user initialization. ### Method getDepositInstruction ### Parameters - **amount** (BN) - Required - The amount to deposit. - **marketIndex** (number) - Required - The index of the market to deposit into. - **userTokenAccount** (PublicKey) - Required - The public key of the user's token account. - **subAccountId** (number) - Optional - The sub-account ID to deposit into. - **reduceOnly** (boolean) - Optional - Defaults to false. If true, the deposit is reduce-only. - **userInitialized** (boolean) - Optional - Defaults to true. If true, indicates the user's account is already initialized. ``` -------------------------------- ### getMarketIndexAndType Source: https://drift-labs.github.io/protocol-v2/sdk/classes/DriftClient.html Retrieves the market index and type for a given market name. For example, 'SOL-PERP' would return its corresponding market index and type. ```APIDOC ## getMarketIndexAndType ### Description Returns the market index and type for a given market name. E.g. "SOL-PERP" -> { marketIndex: 0, marketType: MarketType.PERP } ### Method Not specified (SDK method) ### Parameters #### Path Parameters * **name** (string) - Required - The name of the market (e.g., "SOL-PERP"). ### Returns * **marketIndex** (number) - The index of the market. * **marketType** (MarketType) - The type of the market (e.g., PERP, SPOT). ``` -------------------------------- ### Wallet Constructor Source: https://drift-labs.github.io/protocol-v2/sdk/classes/Wallet.html Initializes a new instance of the Wallet class. It requires a Keypair to be provided as the payer. ```APIDOC ## new Wallet(payer: Keypair): Wallet ### Description Initializes a new instance of the Wallet class. ### Parameters #### payer - **payer** (Keypair) - Description of the payer Keypair. ``` -------------------------------- ### getTotalPerpPositionValueExcludingMarket Source: https://drift-labs.github.io/protocol-v2/sdk/classes/User.html Gets the total position value, excluding any position coming from the specified target market. Supports filtering by margin category, liquidation buffer, and open orders. ```APIDOC ## getTotalPerpPositionValueExcludingMarket ### Description Gets the total position value, excluding any position coming from the specified target market. Supports filtering by margin category, liquidation buffer, and open orders. ### Method getTotalPerpPositionValueExcludingMarket ### Parameters #### Path Parameters * **marketToIgnore** (number) - Required - The market index to exclude. * **marginCategory** (MarginCategory) - Optional - The margin category to consider. * **liquidationBuffer** (BN) - Optional - The liquidation buffer amount. * **includeOpenOrders** (boolean) - Optional - Whether to include open orders in the value calculation. ### Returns #### Success Response * **BN** - The total perpetual position value excluding the specified market. Precision is QUOTE_PRECISION. ```