#!/usr/bin/env node /** * Query Drift Protocol trade history and compare with database */ import { Connection, PublicKey } from '@solana/web3.js' import { DriftClient, initialize } from '@drift-labs/sdk' import bs58 from 'bs58' const DRIFT_WALLET_KEY = process.env.DRIFT_WALLET_PRIVATE_KEY const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com' async function queryDriftHistory() { console.log('šŸ” Querying Drift Protocol trade history...\n') // Setup connection const connection = new Connection(SOLANA_RPC_URL, 'confirmed') // Parse wallet let secretKey if (DRIFT_WALLET_KEY.startsWith('[')) { secretKey = new Uint8Array(JSON.parse(DRIFT_WALLET_KEY)) } else { secretKey = bs58.decode(DRIFT_WALLET_KEY) } const walletKeypair = { publicKey: PublicKey.default, secretKey } // Initialize Drift const sdkConfig = initialize({ env: 'mainnet-beta' }) const driftClient = new DriftClient({ connection, wallet: { publicKey: walletKeypair.publicKey }, programID: new PublicKey(sdkConfig.DRIFT_PROGRAM_ID), opts: { commitment: 'confirmed' } }) await driftClient.subscribe() // Get account const user = driftClient.getUser() const userAccount = user.getUserAccount() console.log('šŸ“Š Drift Account Summary:') console.log('=' .repeat(60)) // Get total collateral const totalCollateral = Number(user.getTotalCollateral()) / 1e6 const totalLiability = Number(user.getTotalLiabilityValue()) / 1e6 const freeCollateral = Number(user.getFreeCollateral()) / 1e6 const unrealizedPnL = Number(user.getUnrealizedPNL()) / 1e6 console.log(`Total Collateral: $${totalCollateral.toFixed(2)}`) console.log(`Total Liability: $${totalLiability.toFixed(2)}`) console.log(`Free Collateral: $${freeCollateral.toFixed(2)}`) console.log(`Unrealized P&L: $${unrealizedPnL.toFixed(2)}`) // Get settled P&L const settledPnL = Number(userAccount.settledPerpPnl) / 1e6 console.log(`\nšŸ’° Settled Perp P&L: $${settledPnL.toFixed(2)}`) // Get cumulative P&L const cumulativePnL = Number(userAccount.cumulativePerpFunding) / 1e6 console.log(`Cumulative Funding: $${cumulativePnL.toFixed(2)}`) // Calculate deposits/withdrawals impact const netDeposits = Number(userAccount.totalDeposits) / 1e6 const netWithdrawals = Number(userAccount.totalWithdraws) / 1e6 console.log(`\nTotal Deposits: $${netDeposits.toFixed(2)}`) console.log(`Total Withdrawals: $${netWithdrawals.toFixed(2)}`) console.log(`Net Deposits: $${(netDeposits - netWithdrawals).toFixed(2)}`) // Calculate actual trading P&L const actualTradingPnL = totalCollateral - (netDeposits - netWithdrawals) console.log(`\nšŸŽÆ Actual Trading P&L: $${actualTradingPnL.toFixed(2)}`) console.log(` (Total Collateral - Net Deposits)`) await driftClient.unsubscribe() return { settledPnL, unrealizedPnL, totalCollateral, netDeposits: netDeposits - netWithdrawals, actualTradingPnL } } queryDriftHistory().catch(console.error)