import { NextResponse } from 'next/server' import { Connection, PublicKey, Keypair } from '@solana/web3.js' export async function GET(request: Request) { try { const { searchParams } = new URL(request.url) const limit = parseInt(searchParams.get('limit') || '50') console.log('📊 API: Getting Solana transaction history...') // Get private key from environment const privateKeyString = process.env.PRIVATE_KEY if (!privateKeyString) { throw new Error('PRIVATE_KEY not found in environment variables') } // Convert private key to Keypair const privateKeyBytes = JSON.parse(privateKeyString) const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyBytes)) // Connect to Helius RPC const connection = new Connection(process.env.HELIUS_RPC_ENDPOINT || 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY') // Get transaction signatures for this wallet const signatures = await connection.getSignaturesForAddress( keypair.publicKey, { limit: limit * 2 } // Get more signatures to filter for Drift transactions ) console.log(`🔍 Found ${signatures.length} total signatures`) // Get transaction details for each signature const transactions = [] const driftProgramId = 'dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH' // Drift program ID for (const sig of signatures.slice(0, limit)) { try { const tx = await connection.getTransaction(sig.signature, { maxSupportedTransactionVersion: 0 }) if (!tx) continue // Check if this transaction involves the Drift program const isDriftTransaction = tx.transaction.message.staticAccountKeys?.some( key => key.toString() === driftProgramId ) || tx.transaction.message.compiledInstructions?.some( instruction => { const programKey = tx.transaction.message.staticAccountKeys?.[instruction.programIdIndex] return programKey?.toString() === driftProgramId } ) if (isDriftTransaction) { // Parse the transaction to extract trading information const blockTime = tx.blockTime ? new Date(tx.blockTime * 1000) : new Date() transactions.push({ id: sig.signature, signature: sig.signature, blockTime: blockTime.toISOString(), slot: tx.slot, status: sig.err ? 'FAILED' : 'SUCCESS', fee: tx.meta?.fee || 0, // Try to extract more details from logs logs: tx.meta?.logMessages?.slice(0, 5) || [], accounts: tx.transaction.message.staticAccountKeys?.slice(0, 10).map(k => k.toString()) || [] }) } } catch (txError) { console.log(`⚠️ Failed to get transaction ${sig.signature}:`, txError) } } console.log(`📊 Found ${transactions.length} Drift transactions`) return NextResponse.json({ success: true, transactions, count: transactions.length, totalSignatures: signatures.length }) } catch (error: any) { console.error('❌ API: Error getting transaction history:', error) return NextResponse.json( { success: false, error: error.message, transactions: [] }, { status: 500 } ) } }