### Install Dependencies with Bun Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Installs project dependencies using the Bun package manager. Ensure you are in the UI directory before running this command. ```bash cd ui bun install ``` -------------------------------- ### Start Development Server with Bun Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Starts the development server using Bun. This command is used to run the application locally during development. ```bash cd ui bun dev ``` -------------------------------- ### Development Scripts with Bun Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Lists the available development scripts runnable with Bun. These include commands for starting the development server, building for production, starting the production server, and running linters. ```bash bun run dev # Start development server with Turbopack bun run build # Build for production bun run start # Start production server bun run lint # Run ESLint ``` -------------------------------- ### Create User Account with Deposit Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Creates a new Drift user account and deposits specified funds into a chosen spot market in a single transaction. ```APIDOC ## Create User Account with Deposit ### Description This API allows for the creation of a new Drift user account and simultaneously deposits a specified amount of funds into a designated spot market. This is typically done in a single transaction to streamline the onboarding process and enable immediate trading. ### Method POST (simulated via SDK function call) ### Endpoint N/A (This is a client-side SDK function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Parameters are passed as arguments to the `createUserAndDeposit` SDK function: - **`depositAmount`** (BigNum) - Required - The amount of tokens to deposit, represented as a `BigNum` object with the correct precision. - **`depositSpotMarketIndex`** (number) - Required - The market index of the spot market for the deposit (e.g., 0 for USDC). - **`newAccountName`** (string) - Required - A name for the new user account. - **`poolId`** (number) - Required - The ID of the collateral pool. - **`subAccountId`** (number) - Required - The sub-account ID for the new account. ### Request Example ```typescript import { useDriftStore } from "@/stores/DriftStore"; import { BigNum } from "@drift-labs/sdk"; import { toast } from "sonner"; const drift = useDriftStore((s) => s.drift); const spotMarketConfigs = useDriftStore((s) => s.getSpotMarketConfigs()); // Get USDC market config (market index 0) const usdcMarketConfig = spotMarketConfigs.find( (config) => config.marketIndex === 0 ); // Convert deposit amount to BigNum with correct precision const depositAmount = BigNum.fromPrint("100", usdcMarketConfig.precisionExp); try { const txSignature = await drift.createUserAndDeposit({ depositAmount: depositAmount, depositSpotMarketIndex: 0, // USDC newAccountName: "Main Account", poolId: 0, subAccountId: 0, }); toast.success(`Account created! Transaction: ${txSignature}`); console.log("New user account created with 100 USDC deposit"); } catch (error) { toast.error("Failed to create account. Please try again."); console.error("Account creation error:", error); } ``` ### Response #### Success Response (200) Upon successful creation and deposit, the function returns the transaction signature. - **`txSignature`** (string) - The signature of the transaction that created the user account and deposited funds. #### Response Example ```json { "txSignature": "EaBcDeF1gHiJkLmN5oPqRsTuVwXyZ0123456789abcdefghijklmnopqrstuvwxyzABCD" } ``` *Note: Error handling via `toast.error` is demonstrated in the example.* ``` -------------------------------- ### Configure Environment in TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Sets up the network environment (e.g., devnet, mainnet-beta) and RPC endpoints for the application. It uses the DriftStore to manage and update the environment settings. The code logs the current environment, demonstrates switching to devnet and mainnet-beta, and includes a note on configuring environment variables. ```typescript import { useDriftStore } from "@/stores/DriftStore"; const environment = useDriftStore((s) => s.environment); const setEnvironment = useDriftStore((s) => s.setEnvironment); // Current environment console.log(`Current environment: ${environment}`); // "devnet" or "mainnet-beta" // Switch to devnet for testing setEnvironment("devnet"); console.log("Switched to devnet"); // Switch to mainnet for production setEnvironment("mainnet-beta"); console.log("Switched to mainnet-beta"); // Note: Environment variables should be configured in .env.local: // NEXT_PUBLIC_SOLANA_MAINNET_RPC_ENDPOINT=your_mainnet_rpc_url // NEXT_PUBLIC_SOLANA_DEVNET_RPC_ENDPOINT=your_devnet_rpc_url ``` -------------------------------- ### Deposit and Withdraw Tokens using TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Demonstrates how to deposit tokens from a user's wallet to their Drift account and withdraw tokens from the Drift account back to the wallet. It utilizes the `deposit` and `withdraw` methods from the Drift SDK, requiring the active sub-account ID, token amount, and spot market index. Error handling is included for both operations. ```typescript import { useDriftStore } from "@/stores/DriftStore"; import { useUserAccountDataStore } from "@/stores/UserAccountDataStore"; import { BigNum } from "@drift-labs/sdk"; const drift = useDriftStore((s) => s.drift); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); const spotMarketConfigs = useDriftStore((s) => s.getSpotMarketConfigs()); // Find SOL market config (market index 1) const solMarketConfig = spotMarketConfigs.find( (config) => config.marketIndex === 1 ); // Deposit 1 SOL const depositAmount = BigNum.fromPrint("1", solMarketConfig.precisionExp); try { await drift.deposit({ subAccountId: activeSubAccountId, amount: depositAmount, spotMarketIndex: 1, // SOL isMaxBorrowRepayment: false, }); console.log("Successfully deposited 1 SOL"); } catch (error) { console.error("Deposit failed:", error); } // Withdraw 0.5 SOL const withdrawAmount = BigNum.fromPrint("0.5", solMarketConfig.precisionExp); try { await drift.withdraw({ subAccountId: activeSubAccountId, amount: withdrawAmount, spotMarketIndex: 1, // SOL isBorrow: false, isMax: false, }); console.log("Successfully withdrew 0.5 SOL"); } catch (error) { console.error("Withdrawal failed:", error); } ``` -------------------------------- ### Configure Environment Variables for RPC Endpoints Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Sets up environment variables for Solana RPC endpoints. Create a .env.local file in the UI directory and add your mainnet and devnet RPC URLs. ```env NEXT_PUBLIC_SOLANA_MAINNET_RPC_ENDPOINT=your_mainnet_rpc_url NEXT_PUBLIC_SOLANA_DEVNET_RPC_ENDPOINT=your_devnet_rpc_url ``` -------------------------------- ### Create Drift User Account and Deposit Funds (TypeScript) Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Creates a new Drift user account and deposits a specified amount of USDC in a single transaction. It retrieves market configuration and handles potential errors, displaying success or failure messages using `sonner` toasts. ```typescript import { useDriftStore } from "@/stores/DriftStore"; import { BigNum } from "@drift-labs/sdk"; import { toast } from "sonner"; const drift = useDriftStore((s) => s.drift); const spotMarketConfigs = useDriftStore((s) => s.getSpotMarketConfigs()); // Get USDC market config (market index 0) const usdcMarketConfig = spotMarketConfigs.find( (config) => config.marketIndex === 0 ); // Convert deposit amount to BigNum with correct precision const depositAmount = BigNum.fromPrint("100", usdcMarketConfig.precisionExp); try { const txSignature = await drift.createUserAndDeposit({ depositAmount: depositAmount, depositSpotMarketIndex: 0, // USDC newAccountName: "Main Account", poolId: 0, subAccountId: 0, }); toast.success(`Account created! Transaction: ${txSignature}`); console.log("New user account created with 100 USDC deposit"); } catch (error) { toast.error("Failed to create account. Please try again."); console.error("Account creation error:", error); } ``` -------------------------------- ### Initialize AuthorityDrift for Protocol Integration Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Demonstrates the basic integration with the Drift protocol using the AuthorityDrift wrapper. It initializes the wrapper with RPC endpoint, environment, and wallet adapter, then subscribes to the service. ```typescript const authorityDrift = new AuthorityDrift({ solanaRpcEndpoint: rpcEndpoint, driftEnv: "mainnet-beta", wallet: walletAdapter, }); await authorityDrift.subscribe(); ``` -------------------------------- ### AuthorityDrift Initialization and Subscription Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Initializes the AuthorityDrift instance, subscribes to Drift Protocol updates, and sets up callbacks for price and user account changes. Also includes details on accessing cached data and unsubscribing. ```APIDOC ## AuthorityDrift Initialization and Subscription ### Description Initializes the AuthorityDrift instance with provided configuration, subscribes to real-time updates from the Drift Protocol, and caches essential data like oracle prices, mark prices, and user accounts. It also demonstrates how to set up callbacks for these updates and how to clean up the subscription. ### Method Initialization involves instantiating the `AuthorityDrift` class and calling its `subscribe()` method. ### Endpoint N/A (This is a client-side SDK initialization) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Initialization parameters are passed to the constructor) ##### Constructor Parameters for `AuthorityDrift`: - **`solanaRpcEndpoint`** (string) - Required - The Solana RPC endpoint URL. - **`driftEnv`** (string) - Required - The Drift environment (e.g., "mainnet-beta"). - **`tradableMarkets`** (Array) - Required - An array of `MarketId` objects defining the tradable spot and perpetual markets. - **`wallet`** (IWalletV2) - Required - The wallet adapter instance. ### Request Example ```typescript import { AuthorityDrift, MarketId } from "@drift-labs/common"; import { MarketType } from "@drift-labs/sdk"; import { useWallet } from "@solana/wallet-adapter-react"; // Configure Drift with mainnet settings const driftConfig = { solanaRpcEndpoint: process.env.NEXT_PUBLIC_SOLANA_MAINNET_RPC_ENDPOINT, driftEnv: "mainnet-beta" as const, tradableMarkets: [ new MarketId(0, MarketType.SPOT), // USDC new MarketId(1, MarketType.SPOT), // SOL new MarketId(0, MarketType.PERP), // SOL-PERP new MarketId(1, MarketType.PERP), // BTC-PERP ], }; // Initialize AuthorityDrift instance const wallet = useWallet(); const authorityDrift = new AuthorityDrift({ ...driftConfig, wallet: wallet as IWalletV2, }); // Subscribe to protocol updates await authorityDrift.subscribe(); // Clean up subscription on unmount // await authorityDrift.unsubscribe(); ``` ### Response #### Success Response (200) Upon successful subscription, the `authorityDrift` instance will be populated with cached data and ready to receive real-time updates. ##### Available Data: - **`oraclePriceCache`** (Map) - Map of market index to oracle price. - **`markPriceCache`** (Map) - Map of market index to mark price. - **`userAccountCache`** (Map) - Map of user account address to user account data. #### Response Example No direct HTTP response. Data is accessed via the `authorityDrift` instance properties and callbacks: ```typescript // Access cached data immediately after subscription const oraclePrices = authorityDrift.oraclePriceCache; const markPrices = authorityDrift.markPriceCache; const userAccounts = authorityDrift.userAccountCache; // Set up real-time price update callbacks authorityDrift.onOraclePricesUpdate((newOraclePrices) => { console.log("Oracle prices updated:", newOraclePrices); }); authorityDrift.onMarkPricesUpdate((newMarkPrices) => { console.log("Mark prices updated:", newMarkPrices); }); authorityDrift.onUserAccountUpdate((newUserAccount) => { console.log("User account updated:", newUserAccount.subAccountId); }); ``` ``` -------------------------------- ### Initialize and Subscribe to AuthorityDrift with Callbacks (TypeScript) Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Initializes the AuthorityDrift instance with specified Drift configuration, subscribes to protocol updates, and sets up callbacks for real-time oracle price, mark price, and user account updates. It also demonstrates how to access cached data and unsubscribe. ```typescript import { AuthorityDrift, MarketId } from "@drift-labs/common"; import { MarketType } from "@drift-labs/sdk"; import { useWallet } from "@solana/wallet-adapter-react"; import { useDriftStore } from "@/stores/DriftStore"; // Configure Drift with mainnet settings const driftConfig = { solanaRpcEndpoint: process.env.NEXT_PUBLIC_SOLANA_MAINNET_RPC_ENDPOINT, driftEnv: "mainnet-beta" as const, tradableMarkets: [ new MarketId(0, MarketType.SPOT), // USDC new MarketId(1, MarketType.SPOT), // SOL new MarketId(0, MarketType.PERP), // SOL-PERP new MarketId(1, MarketType.PERP), // BTC-PERP ], }; // Initialize AuthorityDrift instance const wallet = useWallet(); const authorityDrift = new AuthorityDrift({ ...driftConfig, wallet: wallet as IWalletV2, }); // Subscribe to protocol updates await authorityDrift.subscribe(); // Access cached data immediately after subscription const oraclePrices = authorityDrift.oraclePriceCache; const markPrices = authorityDrift.markPriceCache; const userAccounts = authorityDrift.userAccountCache; // Set up real-time price update callbacks authorityDrift.onOraclePricesUpdate((newOraclePrices) => { console.log("Oracle prices updated:", newOraclePrices); }); authorityDrift.onMarkPricesUpdate((newMarkPrices) => { console.log("Mark prices updated:", newMarkPrices); }); authorityDrift.onUserAccountUpdate((newUserAccount) => { console.log("User account updated:", newUserAccount.subAccountId); }); // Clean up subscription on unmount await authorityDrift.unsubscribe(); ``` -------------------------------- ### Open Perpetual Market Order with Bracket Orders (TypeScript) Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Enables placing a market order for perpetual futures, including optional take profit and stop loss bracket orders. This function requires the Drift SDK, user account data, and toast notifications for user feedback. It accepts parameters like market index, position direction, size, and bracket order prices. Error handling and Swift client integration are demonstrated. ```typescript import { useDriftStore } from "@/stores/DriftStore"; import { useUserAccountDataStore } from "@/stores/UserAccountDataStore"; import { BigNum, PositionDirection, BASE_PRECISION_EXP, PRICE_PRECISION_EXP } from "@drift-labs/sdk"; import { toast } from "sonner"; const drift = useDriftStore((s) => s.drift); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); const isSwiftClientHealthy = useDriftStore((s) => s.isSwiftClientHealthy); // Open a 2 SOL-PERP long position with bracket orders const size = BigNum.fromPrint("2", BASE_PRECISION_EXP); const takeProfitPrice = BigNum.fromPrint("150", PRICE_PRECISION_EXP); const stopLossPrice = BigNum.fromPrint("130", PRICE_PRECISION_EXP); let toastId = ""; try { await drift.openPerpOrder({ subAccountId: activeSubAccountId, marketIndex: 0, // SOL-PERP direction: PositionDirection.LONG, assetType: "base", size: size, orderConfig: { orderType: "market", disableSwift: !isSwiftClientHealthy, bracketOrders: { takeProfitPrice: takeProfitPrice, stopLossPrice: stopLossPrice, }, swiftOptions: { callbacks: { onOrderParamsMessagePrepped: () => { toastId = toast.loading("Preparing Order") as string; }, onSigningSuccess: () => { toast.success("Order Signed", { id: toastId }); }, onSent: () => { toast.success("Order Sent", { id: toastId }); }, onConfirmed: () => { toast.success("Order Confirmed", { id: toastId }); }, onExpired: () => { toast.error("Order Expired", { id: toastId }); }, onErrored: () => { toast.error("Order Errored", { id: toastId }); }, }, }, }, reduceOnly: false, postOnly: PostOnlyParams.NONE, }); console.log("Successfully opened 2 SOL-PERP long position"); } catch (error) { console.error("Failed to place market order:", error); } ``` -------------------------------- ### Access Real-time Oracle Prices - TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Retrieves real-time oracle prices from Pyth and Switchboard feeds for any specified market on the Drift protocol. This functionality is essential for applications requiring up-to-date price information for trading, risk management, or data display. It utilizes the `OraclePriceStore` and requires market identifiers. ```typescript import { useOraclePriceStore } from "@/stores/OraclePriceStore"; import { MarketId } from "@drift-labs/common"; import { MarketType } from "@drift-labs/sdk"; const getOraclePrice = useOraclePriceStore((s) => s.getOraclePrice); // Get SOL-PERP oracle price const solPerpMarketId = new MarketId(0, MarketType.PERP); const solOraclePrice = getOraclePrice(solPerpMarketId); if (solOraclePrice) { const price = solOraclePrice.price.toNum(); const confidence = solOraclePrice.confidence.toNum(); const slot = solOraclePrice.slot.toNumber(); console.log(`SOL-PERP Oracle Price: $${price}`); console.log(`Confidence: ±$${confidence}`); console.log(`Last updated slot: ${slot}`); } // Get BTC-PERP oracle price const btcPerpMarketId = new MarketId(1, MarketType.PERP); const btcOraclePrice = getOraclePrice(btcPerpMarketId); if (btcOraclePrice) { console.log(`BTC-PERP Oracle Price: $${btcOraclePrice.price.toNum()}`); } ``` -------------------------------- ### Access Real-time Mark Prices - TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Provides access to the calculated mark prices for markets on the Drift protocol. Mark prices are used in funding rate calculations and for valuing open positions. This snippet demonstrates how to look up mark prices for specific markets or iterate through all available mark prices using the `MarkPriceStore`. ```typescript import { useMarkPriceStore } from "@/stores/MarkPriceStore"; import { MarketId } from "@drift-labs/common"; import { MarketType } from "@drift-labs/sdk"; const markPriceLookup = useMarkPriceStore((s) => s.lookup); // Get SOL-PERP mark price const solPerpMarketId = new MarketId(0, MarketType.PERP); const solMarkPrice = markPriceLookup[solPerpMarketId.key]; if (solMarkPrice) { console.log(`SOL-PERP Mark Price: $${solMarkPrice.toNum()}`); } // Get all available mark prices Object.entries(markPriceLookup).forEach(([marketKey, markPrice]) => { console.log(`Market ${marketKey}: $${markPrice.toNum()}`); }); ``` -------------------------------- ### Configure Tradable Markets in TypeScript Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Specifies the markets available for trading by uncommenting and configuring the `tradableMarkets` array in the Drift configuration. This includes defining spot and perpetual markets with their IDs and types. ```typescript tradableMarkets: [ new MarketId(0, MarketType.SPOT), // USDC new MarketId(1, MarketType.SPOT), // SOL new MarketId(0, MarketType.PERP), // SOL-PERP new MarketId(1, MarketType.PERP), // BTC-PERP ], ``` -------------------------------- ### Place Oracle Limit Order with Offset - TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Places an oracle-offset limit order on the Drift protocol. This order type is useful for dynamic pricing strategies by tracking the oracle price with a specified offset. It requires the Drift SDK, user account data, and specific market and position details. ```typescript import { BigNum, PositionDirection, BASE_PRECISION_EXP, QUOTE_PRECISION_EXP } from "@drift-labs/sdk"; const drift = useDriftStore((s) => s.drift); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); // Place oracle limit order: buy 5 SOL-PERP at oracle price minus $0.50 const size = BigNum.fromPrint("5", BASE_PRECISION_EXP); const oraclePriceOffset = BigNum.fromPrint("-0.5", QUOTE_PRECISION_EXP); try { await drift.openPerpOrder({ subAccountId: activeSubAccountId, marketIndex: 0, // SOL-PERP direction: PositionDirection.LONG, assetType: "base", size: size, orderConfig: { orderType: "oracleLimit", oraclePriceOffset: oraclePriceOffset, }, reduceOnly: false, postOnly: PostOnlyParams.NONE, }); console.log("Oracle limit order: LONG 5 SOL-PERP @ oracle - $0.50"); } catch (error) { console.error("Oracle limit order failed:", error); } ``` -------------------------------- ### Place Take Profit and Stop Loss Orders - TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Enables the placement of conditional take profit and stop loss orders for risk management on existing positions. These orders are crucial for automated trading strategies and require specifying trigger prices and optionally limit prices. They are typically used with `reduceOnly: true` to close existing positions. ```typescript import { BigNum, PositionDirection, BASE_PRECISION_EXP, QUOTE_PRECISION_EXP } from "@drift-labs/sdk"; const drift = useDriftStore((s) => s.drift); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); // Place take profit order at $160 for existing long position const takeProfitSize = BigNum.fromPrint("2", BASE_PRECISION_EXP); const takeProfitTrigger = BigNum.fromPrint("160", QUOTE_PRECISION_EXP); const takeProfitLimit = BigNum.fromPrint("159.5", QUOTE_PRECISION_EXP); try { await drift.openPerpOrder({ subAccountId: activeSubAccountId, marketIndex: 0, // SOL-PERP direction: PositionDirection.SHORT, // Close long position assetType: "base", size: takeProfitSize, orderConfig: { orderType: "takeProfit", triggerPrice: takeProfitTrigger, limitPrice: takeProfitLimit, // Optional limit price }, reduceOnly: true, postOnly: PostOnlyParams.NONE, }); console.log("Take profit order placed @ $160"); } catch (error) { console.error("Take profit order failed:", error); } // Place stop loss order at $135 const stopLossSize = BigNum.fromPrint("2", BASE_PRECISION_EXP); const stopLossTrigger = BigNum.fromPrint("135", QUOTE_PRECISION_EXP); try { await drift.openPerpOrder({ subAccountId: activeSubAccountId, marketIndex: 0, // SOL-PERP direction: PositionDirection.SHORT, // Close long position assetType: "base", size: stopLossSize, orderConfig: { orderType: "stopLoss", triggerPrice: stopLossTrigger, }, reduceOnly: true, postOnly: PostOnlyParams.NONE, }); console.log("Stop loss order placed @ $135"); } catch (error) { console.error("Stop loss order failed:", error); } ``` -------------------------------- ### Access User Account Data in TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Retrieves comprehensive user account information including positions, balances, and margin data using the UserAccountDataStore. This function requires access to the store's state and lookup methods. It outputs account name, sub-account ID, authority, margin details, spot balances, perpetual positions, and open orders. ```typescript import { useUserAccountDataStore } from "@/stores/UserAccountDataStore"; import { useDriftStore } from "@/stores/DriftStore"; const userAccountLookup = useUserAccountDataStore((s) => s.lookup); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); const getCurrentAccount = useUserAccountDataStore((s) => s.getCurrentAccount); const drift = useDriftStore((s) => s.drift); // Get active user account const currentAccount = getCurrentAccount(); if (currentAccount) { // Account information console.log(`Account Name: ${currentAccount.name}`); console.log(`Sub-Account ID: ${currentAccount.subAccountId}`); console.log(`Authority: ${currentAccount.authority.toBase58()}`); // Margin information const netUsdValue = currentAccount.marginInfo.netUsdValue.toNotional(); const totalCollateral = currentAccount.marginInfo.totalCollateral.toNotional(); const freeCollateral = currentAccount.marginInfo.freeCollateral.toNotional(); console.log(`Net USD Value: $${netUsdValue}`); console.log(`Total Collateral: $${totalCollateral}`); console.log(`Free Collateral: $${freeCollateral}`); // Spot balances currentAccount.spotBalances.forEach((balance) => { const symbol = balance.marketSymbol; const amount = balance.baseBalance.toNum(); console.log(`${symbol} Balance: ${amount}`); }); // Perp positions currentAccount.perpPositions.forEach((position) => { const symbol = position.marketSymbol; const baseSize = position.baseAssetAmount.toNum(); const direction = baseSize > 0 ? "LONG" : "SHORT"; const notionalValue = position.notionalValue.toNotional(); const unrealizedPnl = position.unrealizedPnl.toNotional(); console.log(`${symbol} Position: ${direction} ${Math.abs(baseSize)}`); console.log(` Notional Value: $${notionalValue}`); console.log(` Unrealized PnL: $${unrealizedPnl}`); }); // Open orders currentAccount.orders.forEach((order) => { console.log(`Order ${order.orderId}: ${order.direction} ${order.baseAssetAmount.toNum()}`); }); } // Get all user accounts for connected wallet const allUserAccounts = Object.values(userAccountLookup).filter( (account) => account?.authority?.toBase58() === drift?.authority?.toBase58() ); console.log(`Total accounts: ${allUserAccounts.length}`); ``` -------------------------------- ### Switch Active Sub-Account in TypeScript Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Enables changing the active trading sub-account for managing multiple accounts. It utilizes the UserAccountDataStore to access available accounts and set the active one. The function logs available sub-accounts and confirms the switch to the new sub-account. ```typescript import { useUserAccountDataStore } from "@/stores/UserAccountDataStore"; const setActiveSubAccountId = useUserAccountDataStore((s) => s.setActiveSubAccountId); const userAccountLookup = useUserAccountDataStore((s) => s.lookup); // Get available sub-accounts const availableAccounts = Object.values(userAccountLookup); console.log("Available sub-accounts:"); availableAccounts.forEach((account) => { console.log(` #${account.subAccountId}: ${account.name}`); }); // Switch to sub-account #1 setActiveSubAccountId(1); console.log("Switched to sub-account #1"); console.log("All future trades will use this sub-account"); ``` -------------------------------- ### Open Perpetual Limit Order with Post-Only (TypeScript) Source: https://context7.com/drift-labs/drift-ui-template/llms.txt Allows placing a limit order for perpetual futures at a specified price with a post-only execution constraint. This TypeScript snippet uses the Drift SDK and requires the active sub-account ID and order details like market index, direction, size, and limit price. It demonstrates setting the `postOnly` parameter to `PostOnlyParams.MUST_POST_ONLY`. ```typescript import { BigNum, PositionDirection, PostOnlyParams, BASE_PRECISION_EXP, QUOTE_PRECISION_EXP } from "@drift-labs/sdk"; const drift = useDriftStore((s) => s.drift); const activeSubAccountId = useUserAccountDataStore((s) => s.activeSubAccountId); // Place a limit order to short 1 BTC-PERP at $45,000 const size = BigNum.fromPrint("1", BASE_PRECISION_EXP); const limitPrice = BigNum.fromPrint("45000", QUOTE_PRECISION_EXP); try { await drift.openPerpOrder({ subAccountId: activeSubAccountId, marketIndex: 1, // BTC-PERP direction: PositionDirection.SHORT, assetType: "base", size: size, orderConfig: { orderType: "limit", limitPrice: limitPrice, disableSwift: false, }, reduceOnly: false, postOnly: PostOnlyParams.MUST_POST_ONLY, }); console.log("Limit order placed: SHORT 1 BTC-PERP @ $45,000"); } catch (error) { console.error("Limit order failed:", error); } ``` -------------------------------- ### Switch Network Configuration in TypeScript Source: https://github.com/drift-labs/drift-ui-template/blob/master/README.md Modifies the network configuration from mainnet to devnet within the `useSetupDrift.ts` hook. This involves changing the `driftConfig` variable. ```typescript // Change this line const driftConfig = MAINNET_DRIFT_CONFIG; // To const driftConfig = _DEVNET_DRIFT_CONFIG; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.