### Build Drift Protocol SDK Source: https://github.com/drift-labs/drift-common/blob/master/README.md Navigate into the protocol directory, install its dependencies, build the SDK, and then link it globally. ```bash cd protocol yarn yarn build cd sdk yarn yarn build npm link cd ../.. ``` -------------------------------- ### Install Project Dependencies with Yarn Source: https://github.com/drift-labs/drift-common/blob/master/README.md Installs project dependencies using Yarn. This should be run at the root of the project. ```bash yarn ``` -------------------------------- ### Build Deposit Transaction and Instructions Source: https://context7.com/drift-labs/drift-common/llms.txt Use `createDepositTxn` to build a full deposit transaction or `createDepositIxs` to get individual deposit instructions. These are useful for programmatic deposit management. ```typescript import { createDepositTxn, createDepositIxs } from '@drift-labs/common'; import { BigNum, QUOTE_PRECISION_EXP } from '@drift-labs/sdk'; // Build a full versioned deposit transaction const depositTxn = await createDepositTxn({ driftClient, user, amount: BigNum.from(100_000_000, QUOTE_PRECISION_EXP), // 100 USDC spotMarketConfig: usdcSpotConfig, txParams: { computeUnits: 150_000, computeUnitsPrice: 10_000 }, // externalWallet: someOtherPublicKey, // deposit from a different wallet }); // driftClient.txSender.sendVersionedTransaction(depositTxn) ``` ```typescript // Build just the instruction(s) for composing into a larger transaction const depositIxs = await createDepositIxs({ driftClient, user, amount: BigNum.from(50_000_000, QUOTE_PRECISION_EXP), spotMarketConfig: usdcSpotConfig, isMaxBorrowRepayment: true, // scales 2x, sets reduceOnly }); // Compose into custom transaction alongside other instructions ``` -------------------------------- ### Internal Import Update Example Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Illustrates an internal import path change required for files that remain but need to reference utilities from new locations. ```typescript src/utils/superstake.ts (imports aprFromApy from '../utils' → '../utils/math/numbers') src/drift/ files (imports of sleep, ENUM_UTILS from '../utils' → new paths) ``` -------------------------------- ### Initialize SDK Configuration Source: https://context7.com/drift-labs/drift-common/llms.txt Initializes the global Config singleton with spot and perp market lookups for a given Drift environment. This must be called once before any market-aware operation. ```APIDOC ## Initialize — Bootstrap SDK configuration Initialises the global `Config` singleton with spot and perp market lookups for a given Drift environment. Must be called once before any market-aware operation. ```typescript import { Initialize, Config } from '@drift-labs/common'; // Initialize for mainnet-beta const sdkConfig = Initialize('mainnet-beta'); console.log(Config.initialized); // true console.log(Config.perpMarketsLookup[0]); // PerpMarketConfig for SOL-PERP console.log(Config.spotMarketsLookup[1]); // SpotMarketConfig for SOL // Initialize for devnet Initialize('devnet'); ``` ``` -------------------------------- ### Token Utilities Source: https://context7.com/drift-labs/drift-common/llms.txt A utility function to get the associated token address for deposits and withdrawals for a given spot market account and authority. ```typescript import { getTokenAddressForDepositAndWithdraw } from '@drift-labs/common/utils/token'; const ata = await getTokenAddressForDepositAndWithdraw(spotMarketAccount, authority); ``` -------------------------------- ### Initialize and Update Git Submodules Source: https://github.com/drift-labs/drift-common/blob/master/README.md Run these commands to initialize and update all git submodules required by the project. ```bash git submodule init git submodule update ``` -------------------------------- ### Initialize DriftProvider for React Apps Source: https://context7.com/drift-labs/drift-common/llms.txt Wrap your application with DriftProvider to set up wallet adapters, Solana connection, and other essential Drift functionalities. Configure options like autoconnection, environment, and disable specific features. ```tsx import { DriftProvider } from '@drift-labs/react'; import { DEFAULT_BREAKPOINTS } from '@drift-labs/react'; const App = () => ( { // redirect geo-blocked users window.location.href = '/geo-blocked'; }, }} > ); // Inside any child component, access the global store: import { useCommonDriftStore } from '@drift-labs/react'; const TradingWidget = () => { const driftClient = useCommonDriftStore((s) => s.driftClient.client); const authority = useCommonDriftStore((s) => s.authority); const isGeoBlocked = useCommonDriftStore((s) => s.isGeoBlocked); const connection = useCommonDriftStore((s) => s.connection); return
Authority: {authority?.toBase58()}
; }; ``` -------------------------------- ### Initialize SDK Configuration Source: https://context7.com/drift-labs/drift-common/llms.txt Initializes the global Config singleton with market lookups for a given Drift environment. Must be called once before any market-aware operation. ```typescript import { Initialize, Config } from '@drift-labs/common'; // Initialize for mainnet-beta const sdkConfig = Initialize('mainnet-beta'); console.log(Config.initialized); // true console.log(Config.perpMarketsLookup[0]); // PerpMarketConfig for SOL-PERP console.log(Config.spotMarketsLookup[1]); // SpotMarketConfig for SOL // Initialize for devnet Initialize('devnet'); ``` -------------------------------- ### Copy Settings File Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Copy the settings file to the new utils/settings directory before it is deleted from common-ui-utils. ```bash mkdir -p src/utils/settings cp src/common-ui-utils/settings/settings.ts src/utils/settings/settings.ts ``` -------------------------------- ### Run Project Tests Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Execute the project's test suite using `npm test` to ensure all tests pass after the refactoring process. ```bash npm test ``` -------------------------------- ### Link Drift SDK to Other Packages Source: https://github.com/drift-labs/drift-common/blob/master/README.md After building and linking the SDK, use this command to link it to other packages that depend on it. ```bash npm link @drift-labs/sdk ``` -------------------------------- ### Commit Account and Settings Utilities Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Commit changes after creating the new utils/accounts module and moving the settings file. ```bash git add src/utils/accounts/ src/utils/settings/ git commit -m "refactor(common-ts): create utils/accounts module, move settings to utils/" ``` -------------------------------- ### Initialize and Use DlobWebsocketClient Source: https://context7.com/drift-labs/drift-common/llms.txt Connects to the Drift DLOB websocket server to receive live L2 orderbook data. Manages market subscriptions and provides deserialized updates via RxJS observables. Ensure to unsubscribe and destroy the client when no longer needed. ```typescript import { DlobWebsocketClient, MarketId } from '@drift-labs/common'; const dlobWs = new DlobWebsocketClient({ websocketUrl: 'wss://dlob.drift.trade/ws', enableIndicativeOrderbook: false, onFallback: (marketId) => { console.warn('Websocket fallback for:', marketId.key); }, }); const markets = [ { marketId: MarketId.createPerpMarket(0), grouping: 0.01 }, { marketId: MarketId.createPerpMarket(1) }, ]; // Start receiving data dlobWs.subscribeToMarkets(markets); // Get a typed stream for specific markets const stream = dlobWs.getMarketDataStream([MarketId.createPerpMarket(0)]); const sub = stream.subscribe(({ marketId, deserializedData, slot }) => { console.log(`Slot ${slot} orderbook for ${marketId.key}`); console.log('Bids:', deserializedData.bids.slice(0, 3)); console.log('Asks:', deserializedData.asks.slice(0, 3)); }); // Handle browser tab return (prevents slot-skipping) document.addEventListener('visibilitychange', () => { if (!document.hidden) dlobWs.handleTabReturn(); }); // Clean up sub.unsubscribe(); dlobWs.unsubscribeAll(); dlobWs.destroy(); ``` -------------------------------- ### useSyncOraclePriceStore Source: https://context7.com/drift-labs/drift-common/llms.txt This hook polls oracle prices for a set of markets at a configurable refresh rate and writes them into the `useOraclePriceStore` Zustand store. It should be connected once near the root to make oracle prices available app-wide. ```APIDOC ## `useSyncOraclePriceStore` — Sync oracle prices into React store Polls oracle prices for a set of markets at a configurable refresh rate and writes them into the `useOraclePriceStore` Zustand store. Connect this hook once near the root to make oracle prices available app-wide. ```tsx import { useSyncOraclePriceStore } from '@drift-labs/react'; import { useOraclePriceStore } from '@drift-labs/react'; import { UIMarket, MarketId } from '@drift-labs/react'; import { MarketType } from '@drift-labs/sdk'; import { PublicKey } from '@solana/web3.js'; // In a top-level component const OraclePriceSync = () => { const marketsAndAccounts = [ { market: UIMarket.createPerpMarket(0), // SOL-PERP accountToUse: new PublicKey('SOL_ORACLE_PUBKEY'), }, ]; useSyncOraclePriceStore(marketsAndAccounts, 1000 /* refresh every 1s */); return null; }; // In any consuming component const PriceDisplay = () => { const oraclePrices = useOraclePriceStore((s) => s.oraclePrices); const solPerpKey = MarketId.createPerpMarket(0).key; const solPrice = oraclePrices[solPerpKey]; return

SOL oracle: ${solPrice?.price?.toNum().toFixed(2)}

; }; ``` ``` -------------------------------- ### Commit Deprecation Facades Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md This bash command stages and commits the newly created deprecation facade files. Run this after creating all the facade files to save the changes. ```bash git add src/_deprecated/ git commit -m "refactor(common-ts): create deprecation facades for backwards compatibility" ``` -------------------------------- ### Initialize and Use CentralServerDrift Client Source: https://context7.com/drift-labs/drift-common/llms.txt Instantiate the CentralServerDrift client for server-side transaction building. Subscribe to market data and fetch user data on demand. This client returns unsigned transactions for client-side signing. ```typescript import { CentralServerDrift } from '@drift-labs/common'; import { PublicKey, BN } from '@drift-labs/sdk'; const server = new CentralServerDrift({ solanaRpcEndpoint: process.env.RPC_URL, driftEnv: 'mainnet-beta', supportedPerpMarkets: [0, 1, 2], // SOL, BTC, ETH perps supportedSpotMarkets: [0, 1], // USDC, SOL spot }); await server.subscribe(); // Build a deposit transaction for a user const userAccount = new PublicKey('USER_ACCOUNT_PUBKEY'); const depositTxn = await server.getDepositTxn( userAccount, new BN(100_000_000), // 100 USDC 0, // USDC spot market index { txParams: { computeUnits: 200_000 } } ); // Return depositTxn to client for signing // Build a market order transaction const marketOrderTxn = await server.getOpenPerpMarketOrderTxn({ userAccountPublicKey: userAccount, useSwift: false, marketIndex: 0, direction: 'long', amount: new BN(1_000_000_000), // 1 SOL in base precision assetType: 'base', positionMaxLeverage: 5, }); // Build a Swift (off-chain signed) market order message const swiftMessage = await server.getOpenPerpMarketOrderTxn({ userAccountPublicKey: userAccount, useSwift: true, marketIndex: 0, direction: 'long', amount: new BN(1_000_000_000), assetType: 'base', positionMaxLeverage: 5, swiftOptions: { isDelegate: false }, }); // Return swiftMessage.message + swiftMessage.signature to client // Build a withdraw transaction const withdrawTxn = await server.getWithdrawTxn( userAccount, new BN(50_000_000), 0, { isMax: false } ); // Create account + initial deposit in one transaction const { transaction, userAccountPublicKey } = await server.getCreateAndDepositTxn( new PublicKey('AUTHORITY_PUBKEY'), new BN(100_000_000), 0, { accountName: 'Main Account', referrerName: 'drift' } ); // Cancel specific orders const cancelTxn = await server.getCancelOrdersTxn(userAccount, [101, 102]); // Cancel all orders for a market const cancelAllTxn = await server.getCancelAllOrdersTxn(userAccount); // Swap USDC → SOL via Jupiter const swapTxn = await server.getSwapTxn(userAccount, 0, 1, new BN(50_000_000), { slippageBps: 50, swapMode: 'ExactIn', }); // Send a pre-signed transaction const sig = await server.sendSignedTransaction(signedTxn); await server.unsubscribe(); ``` -------------------------------- ### Search for Old Import Paths Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Use grep commands to find and update all internal imports referencing old paths like `'../utils'` or `'../common-ui-utils'`. ```bash grep -rn "from '../utils'" src/ --include="*.ts" | grep -v node_modules ``` ```bash grep -rn "from '../common-ui-utils'" src/ --include="*.ts" | grep -v node_modules ``` ```bash grep -rn "from './commonUiUtils'" src/ --include="*.ts" | grep -v node_modules ``` ```bash grep -rn "from '.'" src/utils/ --include="*.ts" | grep -v node_modules ``` -------------------------------- ### useCommonDriftStore Source: https://context7.com/drift-labs/drift-common/llms.txt A Zustand hook to access the central global store, which holds connection state, wallet context, DriftClient, user accounts, SOL balance, and more. ```APIDOC ## useCommonDriftStore ### Description The central Zustand store for the `@drift-labs/react` package. Holds connection state, wallet context, `DriftClient`, user accounts, SOL balance, geo-block status, emulation mode, and the SDK config. ### Usage ```tsx import { useCommonDriftStore } from '@drift-labs/react'; const Component = () => { // Select individual slices to minimise re-renders const authority = useCommonDriftStore((s) => s.authority); const driftClient = useCommonDriftStore((s) => s.driftClient.client); const isSubscribed = useCommonDriftStore((s) => s.driftClient.isSubscribed); const userAccounts = useCommonDriftStore((s) => s.userAccounts); const solBalance = useCommonDriftStore((s) => s.currentSolBalance); const connection = useCommonDriftStore((s) => s.connection); const env = useCommonDriftStore((s) => s.env); const actions = useCommonDriftStore((s) => s.actions); // Imperatively read the full store without subscribing (e.g. in callbacks) const get = useCommonDriftStore((s) => s.get); const set = useCommonDriftStore((s) => s.set); const handleDeposit = async () => { const store = get(); if (!store.driftClient.client) return; // ... }; return (

Wallet: {authority?.toBase58()}

SOL: {solBalance.value.toNum().toFixed(4)}

Accounts: {userAccounts.length}

Client ready: {isSubscribed.toString()}

); }; ``` ``` -------------------------------- ### Utility Modules Source: https://context7.com/drift-labs/drift-common/llms.txt Exposes tree-shakeable utility functions through subpath exports for common domain-scoped helpers. ```APIDOC ## Utility modules — Domain-scoped helpers `@drift-labs/common` exposes tree-shakeable utility functions through subpath exports. Below are the key modules with representative usage. ```typescript // Math utilities import { calculateSpread, roundToStepSize, bnMin, bnMax } from '@drift-labs/common/utils/math'; import { BN } from '@drift-labs/sdk'; const spread = calculateSpread(markPrice, bidPrice, askPrice); const rounded = roundToStepSize(1.23456, 0.01); // => 1.23 const smallest = bnMin(new BN(100), new BN(200)); // => BN(100) // String utilities import { abbreviateAddress, trimTrailingZeros, toSnakeCase } from '@drift-labs/common/utils/strings'; abbreviateAddress('7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU'); // => '7xKX...AsU' trimTrailingZeros('1.50000'); // => '1.5' toSnakeCase('myVariable'); // => 'my_variable' // Order utilities import { sortUIOrderRecords, orderIsNull } from '@drift-labs/common/utils/orders'; const sorted = sortUIOrderRecords(orders); // Sort by slot descending const isEmpty = orderIsNull(order); // true if order is zeroed-out // Account utilities import { getUserKey, fetchCurrentSubaccounts } from '@drift-labs/common/utils/accounts'; const userAccountKey = getUserKey(subAccountId, authorityPublicKey); const subaccounts = await fetchCurrentSubaccounts(driftClient, authority, 8); // Core utilities import { sleep, chunks } from '@drift-labs/common/utils/core'; await sleep(500); // pause 500ms const batches = chunks([1,2,3,4,5], 2); // => [[1,2],[3,4],[5]] // Enum utilities import { ENUM_UTILS } from '@drift-labs/common/utils/enum'; import { MarketType, PositionDirection } from '@drift-labs/sdk'; const isPerp = ENUM_UTILS.match(marketType, MarketType.PERP); const dirStr = ENUM_UTILS.toStr(PositionDirection.LONG); // => 'long' const dirObj = ENUM_UTILS.toObj('long') as PositionDirection; // Token utilities import { getTokenAddressForDepositAndWithdraw } from '@drift-labs/common/utils/token'; const ata = await getTokenAddressForDepositAndWithdraw(spotMarketAccount, authority); // Trading utilities import { calculatePnlPctFromPosition, convertLeverageToMarginRatio } from '@drift-labs/common/utils/trading'; const pnlPct = calculatePnlPctFromPosition(position, oraclePrice); const marginRatio = convertLeverageToMarginRatio(5); // 5x leverage => 0.2 ``` ``` -------------------------------- ### Dispatch Drift Protocol Actions Source: https://context7.com/drift-labs/drift-common/llms.txt Obtain actions from the common Drift store to imperatively manage wallet connections, subaccount switching, and RPC endpoint changes. Requires initialization of the DriftClient. ```tsx import { useCommonDriftActions } from '@drift-labs/react'; const WalletControls = () => { const actions = useCommonDriftActions(); const handleConnect = async () => { // Initialize and subscribe the DriftClient for a connected wallet await actions.initDriftClient( connection, walletContext, 'mainnet-beta', { basePollingRateMs: 1000, priorityFeePollingMultiplier: 5, txSenderRetryInterval: 2000, subscribeToAccounts: true, } ); }; const handleSubAccountSwitch = async (newSubAccountId: number) => { await actions.switchActiveSubAccount(newSubAccountId); }; return (
); }; ``` -------------------------------- ### DriftProvider Source: https://context7.com/drift-labs/drift-common/llms.txt The top-level React context provider that initializes Drift functionalities for your application. It sets up wallet adapters, Solana connection, geo-blocking checks, and more. ```APIDOC ## DriftProvider ### Description Top-level React context provider that wraps your application to set up wallet adapters, Solana connection, geo-blocking checks, idle polling optimisation, SOL balance tracking, and screen-size responsiveness. ### Usage ```tsx import { DriftProvider } from '@drift-labs/react'; import { DEFAULT_BREAKPOINTS } from '@drift-labs/react'; const App = () => ( { // redirect geo-blocked users window.location.href = '/geo-blocked'; }, }} > ); ``` ### Accessing Store ```tsx import { useCommonDriftStore } from '@drift-labs/react'; const TradingWidget = () => { const driftClient = useCommonDriftStore((s) => s.driftClient.client); const authority = useCommonDriftStore((s) => s.authority); const isGeoBlocked = useCommonDriftStore((s) => s.isGeoBlocked); const connection = useCommonDriftStore((s) => s.connection); return
Authority: {authority?.toBase58()}
; }; ``` ``` -------------------------------- ### useCommonDriftActions Source: https://context7.com/drift-labs/drift-common/llms.txt Returns the actions object from the common Drift store, providing imperative methods for connecting wallets, switching subaccounts, switching RPC endpoints, and other store-level mutations. ```APIDOC ## `useCommonDriftActions` — Drift protocol action dispatcher Returns the actions object from the common Drift store, providing imperative methods for connecting wallets, switching subaccounts, switching RPC endpoints, and other store-level mutations. ```tsx import { useCommonDriftActions } from '@drift-labs/react'; const WalletControls = () => { const actions = useCommonDriftActions(); const handleConnect = async () => { // Initialize and subscribe the DriftClient for a connected wallet await actions.initDriftClient( connection, walletContext, 'mainnet-beta', { basePollingRateMs: 1000, priorityFeePollingMultiplier: 5, txSenderRetryInterval: 2000, subscribeToAccounts: true, } ); }; const handleSubAccountSwitch = async (newSubAccountId: number) => { await actions.switchActiveSubAccount(newSubAccountId); }; return (
); }; ``` ``` -------------------------------- ### Commit Changes for utils/markets Module Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md This command stages all changes within the `src/utils/markets/` directory and commits them with a descriptive message, signifying the creation of a new common TypeScript module for market-related utilities. ```bash git add src/utils/markets/ git commit -m "refactor(common-ts): create utils/markets module" ``` -------------------------------- ### Initialize and Use AuthorityDrift Client Source: https://context7.com/drift-labs/drift-common/llms.txt Instantiate the AuthorityDrift client for wallet-connected trading. Subscribe to on-chain data, handle oracle and orderbook updates, and build various trading transactions. Remember to unsubscribe for cleanup. ```typescript import { AuthorityDrift, MarketId } from '@drift-labs/common'; import { IWalletV2, BN } from '@drift-labs/sdk'; const client = new AuthorityDrift({ solanaRpcEndpoint: 'https://aurora-d3bv7j-fast-mainnet.helius-rpc.com/', driftEnv: 'mainnet-beta', wallet: myWallet as IWalletV2, selectedTradeMarket: MarketId.createPerpMarket(0), // SOL-PERP tradableMarkets: [ MarketId.createPerpMarket(0), MarketId.createSpotMarket(1), ], }); // Subscribe: starts polling DLOB, oracle prices, user accounts, orderbook await client.subscribe(); // React to real-time oracle price updates const unsubOracle = client.onOraclePricesUpdate((prices) => { const solPerpKey = MarketId.createPerpMarket(0).key; console.log('SOL oracle price:', prices[solPerpKey]?.price.toString()); }); // React to orderbook updates const unsubOrderbook = client.onOrderbookUpdate((orderbook) => { console.log('Best bid:', orderbook.bestBidPrice?.toString()); console.log('Best ask:', orderbook.bestAskPrice?.toString()); }); // Open a SOL-PERP market buy ($100 notional) const txSig = await client.openPerpOrder({ marketIndex: 0, direction: 'long', amount: new BN(100_000_000), // 100 USDC in quote precision assetType: 'quote', }); console.log('Order tx:', txSig); // Deposit 50 USDC into spot market 0 const depositSig = await client.deposit({ amount: new BN(50_000_000), spotMarketIndex: 0, }); // Switch to a different active trade market (re-optimises polling) client.updateSelectedTradeMarket(MarketId.createPerpMarket(1)); // BTC-PERP // Update wallet on wallet reconnect await client.updateAuthority(newWallet, 0); // Settle PnL for SOL-PERP const settleSig = await client.settleAccountPnl({ marketIndexes: [0] }); // Cancel specific orders await client.cancelOrders({ orderIds: [42, 43] }); // Clean teardown unsubOracle(); unsubOrderbook(); await client.unsubscribe(); ``` -------------------------------- ### SwiftClient Source: https://context7.com/drift-labs/drift-common/llms.txt Off-chain Swift order submission and confirmation. Static utility class for submitting pre-signed Swift (off-chain) orders to the Drift Swift server and confirming their execution via HTTP polling or WebSocket account change listeners. ```APIDOC ## `SwiftClient` — Off-chain Swift order submission and confirmation Static utility class for submitting pre-signed Swift (off-chain) orders to the Drift Swift server and confirming their execution via HTTP polling or WebSocket account change listeners. ```typescript import { SwiftClient } from '@drift-labs/common'; import { MarketType } from '@drift-labs/sdk'; import { PublicKey } from '@solana/web3.js'; // Initialize the client once at app startup SwiftClient.init('https://swift.drift.trade', 'my-app'); // Send and confirm a Swift order with HTTP polling const observable = SwiftClient.sendAndConfirmSwiftOrder( 0, // marketIndex (SOL-PERP) MarketType.PERP, encodedOrderMessage, // base64 encoded signed message from SDK signatureBuffer, // Buffer of the Ed25519 signature new PublicKey('TAKER_PUBKEY'), 15_000, // confirmDuration in ms new PublicKey('AUTHORITY_PUBKEY') ); observable.subscribe({ next: (event) => { if (event.type === 'sent') { console.log('Order sent, hash:', event.hash); } else if (event.type === 'confirmed') { console.log('Order confirmed! orderId:', event.orderId); } else if (event.type === 'errored' || event.type === 'expired') { console.error('Order failed:', event.message, 'status:', event.status); } }, error: (err) => console.error('Observable error:', err), }); // Check Swift server health before submitting const isHealthy = await SwiftClient.isSwiftServerHealthy(); if (!isHealthy) throw new Error('Swift server is down'); // Send and confirm with faster WebSocket confirmation const wsObservable = SwiftClient.sendAndConfirmSwiftOrderWS( connection, driftClient, 0, MarketType.PERP, encodedOrderMessage, signatureBuffer, takerPublicKey, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, // Uint8Array UUID 15_000, authorityPublicKey ); ``` ``` -------------------------------- ### createDepositTxn / createDepositIxs Source: https://context7.com/drift-labs/drift-common/llms.txt Low-level functions for constructing deposit transactions or individual deposit instructions against a Drift spot market. These are used internally by higher-level abstractions. ```APIDOC ## `createDepositTxn` / `createDepositIxs` — Low-level deposit builders Building-block functions for constructing deposit transactions or individual deposit instructions against a Drift spot market. Used internally by both `AuthorityDrift` and `CentralServerDrift`. ```typescript import { createDepositTxn, createDepositIxs } from '@drift-labs/common'; import { BigNum, QUOTE_PRECISION_EXP } from '@drift-labs/sdk'; // Build a full versioned deposit transaction const depositTxn = await createDepositTxn({ driftClient, user, amount: BigNum.from(100_000_000, QUOTE_PRECISION_EXP), // 100 USDC spotMarketConfig: usdcSpotConfig, txParams: { computeUnits: 150_000, computeUnitsPrice: 10_000 }, // externalWallet: someOtherPublicKey, // deposit from a different wallet }); // driftClient.txSender.sendVersionedTransaction(depositTxn) // Build just the instruction(s) for composing into a larger transaction const depositIxs = await createDepositIxs({ driftClient, user, amount: BigNum.from(50_000_000, QUOTE_PRECISION_EXP), spotMarketConfig: usdcSpotConfig, isMaxBorrowRepayment: true, // scales 2x, sets reduceOnly }); // Compose into custom transaction alongside other instructions ``` ``` -------------------------------- ### Commit token module changes Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Stage and commit the newly created token utility files, including deduplicated functions. ```bash git add src/utils/token/ git commit -m "refactor(common-ts): create utils/token module with deduplicated functions" ``` -------------------------------- ### Trading Utilities Source: https://context7.com/drift-labs/drift-common/llms.txt Functions for calculating Profit and Loss percentage from a position and converting leverage values into margin ratios. ```typescript import { calculatePnlPctFromPosition, convertLeverageToMarginRatio } from '@drift-labs/common/utils/trading'; const pnlPct = calculatePnlPctFromPosition(position, oraclePrice); const marginRatio = convertLeverageToMarginRatio(5); // 5x leverage => 0.2 ``` -------------------------------- ### Environment Constants Registry Source: https://context7.com/drift-labs/drift-common/llms.txt Provides the canonical URLs for every Drift infrastructure service (RPC nodes, history API, data API, DLOB HTTP/WS, Swift server, events websocket) across all environments. ```APIDOC ## EnvironmentConstants — Centralized endpoint registry Provides the canonical URLs for every Drift infrastructure service (RPC nodes, history API, data API, DLOB HTTP/WS, Swift server, events websocket) across all environments. ```typescript import { EnvironmentConstants } from '@drift-labs/common'; // Get DLOB HTTP endpoint for mainnet const dlobUrl = EnvironmentConstants.dlobServerHttpUrl.mainnet; // => 'https://dlob.drift.trade' // Get Swift server URL for production const swiftUrl = EnvironmentConstants.swiftServerUrl.mainnet; // => 'https://swift.drift.trade' // Get all mainnet RPC options const rpcs = EnvironmentConstants.rpcs.mainnet; rpcs.forEach(rpc => { console.log(rpc.label, rpc.value); // 'Helius 1', 'https://aurora-d3bv7j-fast-mainnet.helius-rpc.com/' }); // Candle data API for staging const dataUrl = EnvironmentConstants.dataServerUrl.staging; ``` ``` -------------------------------- ### Commit Order Utilities Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Commit changes after creating the new utils/orders module. ```bash git add src/utils/orders/ git commit -m "refactor(common-ts): create utils/orders module" ``` -------------------------------- ### String Utilities Source: https://context7.com/drift-labs/drift-common/llms.txt Offers functions for abbreviating wallet addresses, trimming trailing zeros from strings, and converting strings to snake_case. ```typescript import { abbreviateAddress, trimTrailingZeros, toSnakeCase } from '@drift-labs/common/utils/strings'; abbreviateAddress('7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU'); // => '7xKX...AsU' trimTrailingZeros('1.50000'); // => '1.5' toSnakeCase('myVariable'); // => 'my_variable' ``` -------------------------------- ### Compile with TypeScript Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Run the TypeScript compiler with the `--noEmit` flag to check for compilation errors after refactoring. Address any reported issues, such as missing imports or circular dependencies. ```bash npx tsc --noEmit ``` -------------------------------- ### Import and Use Drift Icons in React Source: https://context7.com/drift-labs/drift-common/llms.txt Demonstrates how to import and use SVG icons from the @drift-labs/icons package in a React component. Icons accept standard SVG props for customization. ```tsx import { SolIcon, CaretDownIcon, WalletIcon, ArrowRightIcon } from '@drift-labs/icons'; const TokenSelector = () => (
Solana
); const ConnectButton = () => ( ); ``` -------------------------------- ### Submit and Confirm Off-chain Swift Orders Source: https://context7.com/drift-labs/drift-common/llms.txt Submits pre-signed off-chain orders to the Drift Swift server and confirms their execution. Supports both HTTP polling and faster WebSocket confirmation. Ensure the Swift server is healthy before submitting orders. ```typescript import { SwiftClient } from '@drift-labs/common'; import { MarketType } from '@drift-labs/sdk'; import { PublicKey } from '@solana/web3.js'; // Initialize the client once at app startup SwiftClient.init('https://swift.drift.trade', 'my-app'); // Send and confirm a Swift order with HTTP polling const observable = SwiftClient.sendAndConfirmSwiftOrder( 0, // marketIndex (SOL-PERP) MarketType.PERP, encodedOrderMessage, // base64 encoded signed message from SDK signatureBuffer, // Buffer of the Ed25519 signature new PublicKey('TAKER_PUBKEY'), 15_000, // confirmDuration in ms new PublicKey('AUTHORITY_PUBKEY') ); observable.subscribe({ next: (event) => { if (event.type === 'sent') { console.log('Order sent, hash:', event.hash); } else if (event.type === 'confirmed') { console.log('Order confirmed! orderId:', event.orderId); } else if (event.type === 'errored' || event.type === 'expired') { console.error('Order failed:', event.message, 'status:', event.status); } }, error: (err) => console.error('Observable error:', err), }); // Check Swift server health before submitting const isHealthy = await SwiftClient.isSwiftServerHealthy(); if (!isHealthy) throw new Error('Swift server is down'); // Send and confirm with faster WebSocket confirmation const wsObservable = SwiftClient.sendAndConfirmSwiftOrderWS( connection, driftClient, 0, MarketType.PERP, encodedOrderMessage, signatureBuffer, takerPublicKey, signedMsgUserOrdersAccountPubkey, signedMsgOrderUuid, // Uint8Array UUID 15_000, authorityPublicKey ); ``` -------------------------------- ### Build Cancel Orders Transaction and Instruction Source: https://context7.com/drift-labs/drift-common/llms.txt Construct transactions or individual instructions to cancel open orders using `createCancelOrdersTxn` or `createCancelOrdersIx`. Specify order IDs for cancellation. ```typescript import { createCancelOrdersTxn, createCancelOrdersIx } from '@drift-labs/common'; // Cancel two orders — returns a ready-to-sign versioned transaction const cancelTxn = await createCancelOrdersTxn({ driftClient, user, orderIds: [42, 43], txParams: { computeUnits: 100_000 }, }); // await wallet.sendTransaction(cancelTxn, connection) ``` ```typescript // Or get just the instruction for composing const cancelIx = await createCancelOrdersIx({ driftClient, user, orderIds: [42], mainSignerOverride: delegatePublicKey, // optional delegate signer }); ``` -------------------------------- ### Fetch and Subscribe to Candle Data with CandleClient Source: https://context7.com/drift-labs/drift-common/llms.txt Fetches historical OHLCV candle data and subscribes to live updates from the Drift Data API. Caches recent candles and uses unique keys for subscriptions. Remember to unsubscribe when finished to free up resources. ```typescript import { CandleClient, MarketId } from '@drift-labs/common'; import { CandleResolution } from '@drift-labs/sdk'; const candleClient = new CandleClient(); const env = { sdkEnv: 'mainnet-beta', isStaging: false, isDevnet: false, key: 'mainnet' }; const marketId = MarketId.createPerpMarket(0); // SOL-PERP // Fetch historical candles const nowSeconds = Math.floor(Date.now() / 1000); const candles = await candleClient.fetch({ env, marketId, resolution: CandleResolution.ONE_MINUTE, fromTs: nowSeconds - 3600, // 1 hour ago toTs: nowSeconds, }); console.log(`Fetched ${candles.length} 1m candles`); console.log('Latest candle:', candles[candles.length - 1]); // => { ts: 1234567890, open: '150.5', high: '151.2', low: '150.1', close: '150.8', volume: '12345' } // Subscribe to live candle updates await candleClient.subscribe( { env, marketId, resolution: CandleResolution.ONE_MINUTE }, 'sol-perp-1m' // unique subscription key ); candleClient.on('sol-perp-1m', 'candle-update', (candle) => { console.log('New/updated candle:', candle.ts, candle.close); }); // Unsubscribe when done candleClient.unsubscribe('sol-perp-1m'); // Or unsubscribe all candleClient.unsubscribeAll(); ``` -------------------------------- ### Reconstruct COMMON_UI_UTILS Namespace Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/specs/2026-03-26-utils-restructure-design.md This facade reconstructs COMMON_UI_UTILS by importing from new locations and spreading in other utility namespaces. Use direct imports from specific modules instead. ```typescript import { abbreviateAddress } from '../utils/strings'; import { deriveMarketOrderParams, ... } from '../utils/trading'; import { getUserKey, getMarketKey, ... } from '../utils/accounts'; // ... etc /** @deprecated Use direct imports from specific modules */ export const COMMON_UI_UTILS = { abbreviateAddress, calculateAverageEntryPrice, chunks, // ... all existing members including spreads }; ``` -------------------------------- ### Configure and Use PollingDlob for Market Data Source: https://context7.com/drift-labs/drift-common/llms.txt The `PollingDlob` class polls the Drift DLOB server for market data. Configure polling intervals and depths, then subscribe to data and error streams. ```typescript import { PollingDlob, MarketId, POLLING_INTERVALS, POLLING_DEPTHS } from '@drift-labs/common'; const pollingDlob = new PollingDlob({ driftDlobServerHttpUrl: 'https://dlob.drift.trade', indicativeLiquidityEnabled: true, }); // Configure polling tiers pollingDlob.addInterval('live', POLLING_INTERVALS.LIVE_MARKET, POLLING_DEPTHS.ORDERBOOK); pollingDlob.addInterval('background', POLLING_INTERVALS.BACKGROUND_DEEP, POLLING_DEPTHS.DEEP); pollingDlob.addInterval('idle', POLLING_INTERVALS.BACKGROUND_SHALLOW, POLLING_DEPTHS.SHALLOW); // Assign markets to tiers pollingDlob.addMarketsToInterval('live', [MarketId.createPerpMarket(0).key]); pollingDlob.addMarketsToInterval('background', [ MarketId.createPerpMarket(1).key, MarketId.createPerpMarket(2).key, ]); // Subscribe to data stream const subscription = pollingDlob.onData().subscribe((marketDataArr) => { for (const { marketId, data } of marketDataArr) { console.log(`${marketId.key} mark: ${data.markPrice?.toString()}`); console.log(`${marketId.key} oracle: ${data.oracleData?.price?.toString()}`); } }); // Subscribe to error stream pollingDlob.onError().subscribe((err) => console.error('DLOB error:', err)); await pollingDlob.start(); // Move a market between intervals dynamically pollingDlob.moveMarketToInterval(MarketId.createPerpMarket(0).key, 'idle'); // Stop polling pollingDlob.stop(); subscription.unsubscribe(); ``` -------------------------------- ### Account Utilities Source: https://context7.com/drift-labs/drift-common/llms.txt Helper functions for deriving user account public keys and fetching current subaccounts for a given authority. ```typescript import { getUserKey, fetchCurrentSubaccounts } from '@drift-labs/common/utils/accounts'; const userAccountKey = getUserKey(subAccountId, authorityPublicKey); const subaccounts = await fetchCurrentSubaccounts(driftClient, authority, 8); ``` -------------------------------- ### Commit Changes for utils/trading Module Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md This command stages all changes within the `src/utils/trading/` directory and commits them with a descriptive message, indicating a refactoring of the common TypeScript trading utilities. ```bash git add src/utils/trading/ git commit -m "refactor(common-ts): create utils/trading module" ``` -------------------------------- ### Add package.json Exports and typesVersions Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Update the package.json file to include the 'exports' field for subpath mapping and 'typesVersions' for backward compatibility with older module resolution strategies. ```json { "name": "@drift-labs/common-ts", "version": "1.0.0", "main": "lib/index.js", "module": "lib/index.mjs", "types": "lib/index.d.ts", "exports": { ".": { "types": "./lib/index.d.ts", "import": "./lib/index.mjs", "require": "./lib/index.js" }, "./utils/math": { "types": "./lib/utils/math/index.d.ts", "import": "./lib/utils/math/index.mjs", "require": "./lib/utils/math/index.js" }, "./utils/orders": { "types": "./lib/utils/orders/index.d.ts", "import": "./lib/utils/orders/index.mjs", "require": "./lib/utils/orders/index.js" }, "./utils/enum": { "types": "./lib/utils/enum/index.d.ts", "import": "./lib/utils/enum/index.mjs", "require": "./lib/utils/enum/index.js" }, "./utils/core/equality": { "types": "./lib/utils/core/equality/index.d.ts", "import": "./lib/utils/core/equality/index.mjs", "require": "./lib/utils/core/equality/index.js" }, "./_deprecated/common-ui-utils": { "types": "./lib/_deprecated/common-ui-utils/index.d.ts", "import": "./lib/_deprecated/common-ui-utils/index.mjs", "require": "./lib/_deprecated/common-ui-utils/index.js" } }, "typesVersions": { "*": { "*": [ "lib/*", "lib/utils/*", "lib/utils/math/*", "lib/utils/orders/*", "lib/utils/enum/*", "lib/utils/core/equality/*", "lib/_deprecated/common-ui-utils/*" ] } }, "scripts": { "build": "tsup src/index.ts --format esm,cjs --dts --clean", "circular-deps": "bunx madge --circular --extensions ts,tsx src", "test": "vitest" }, "devDependencies": { "@types/node": "^18.15.11", "tsup": "^1.2.0", "vitest": "^0.31.0" }, "dependencies": { "@drift-labs/common-types": "^1.0.0" } } ``` -------------------------------- ### Commit Changes for package.json Source: https://github.com/drift-labs/drift-common/blob/master/common-ts/docs/superpowers/plans/2026-03-26-utils-restructure.md Stage and commit the updated package.json file after adding the 'exports' and 'typesVersions' fields. ```bash git add package.json git commit -m "refactor(common-ts): add subpath exports and typesVersions to package.json" ``` -------------------------------- ### Enum Utilities Source: https://context7.com/drift-labs/drift-common/llms.txt Provides utilities for working with enums, including matching enum values, converting them to strings, and converting strings back to enum objects. ```typescript import { ENUM_UTILS } from '@drift-labs/common/utils/enum'; import { MarketType, PositionDirection } from '@drift-labs/sdk'; const isPerp = ENUM_UTILS.match(marketType, MarketType.PERP); const dirStr = ENUM_UTILS.toStr(PositionDirection.LONG); // => 'long' const dirObj = ENUM_UTILS.toObj('long') as PositionDirection; ```