critical: Fix withdrawal statistics to use actual Drift deposits
- Query Drift Protocol's cumulativeDeposits for ground truth - Discovered user deposited ,440.61 (not hardcoded 46) - Previous withdrawals: ~26.78 (not tracked in ENV) - Database P&L -.01 is correct - Reconciliation: ,440.61 deposits - .01 P&L - 26.78 withdrawn = 11.82 current - Available profit now shows current balance (includes all trading results) - Created /api/drift/account-summary endpoint for account reconciliation - Statistics now mathematically consistent and trustworthy
This commit is contained in:
@@ -12,14 +12,23 @@ export async function GET() {
|
||||
try {
|
||||
const prisma = getPrismaClient()
|
||||
|
||||
// Get total invested (from roadmap: $546)
|
||||
const totalInvested = 546
|
||||
|
||||
// Get current Drift balance
|
||||
// Get current Drift balance and actual deposits
|
||||
const driftService = await initializeDriftService()
|
||||
const health = await driftService.getAccountHealth()
|
||||
const currentBalance = health.freeCollateral // Already a number
|
||||
|
||||
// Get actual deposits from Drift Protocol (ground truth from blockchain)
|
||||
const user = driftService.getUser()
|
||||
const userAccount = user.getUserAccount()
|
||||
const usdcSpotPosition = userAccount.spotPositions.find(
|
||||
(pos: any) => pos.marketIndex === 0 // USDC market index
|
||||
)
|
||||
const cumulativeDeposits = usdcSpotPosition
|
||||
? Number(usdcSpotPosition.cumulativeDeposits.toString()) / 1_000_000
|
||||
: 546 // Fallback to hardcoded if query fails (shouldn't happen)
|
||||
|
||||
const totalInvested = cumulativeDeposits // Use actual deposits as "invested"
|
||||
|
||||
// Calculate total P&L from database
|
||||
const trades = await prisma.trade.findMany({
|
||||
where: {
|
||||
@@ -36,7 +45,13 @@ export async function GET() {
|
||||
const totalWithdrawn = parseFloat(process.env.TOTAL_WITHDRAWN || '0')
|
||||
|
||||
// Calculate available profit
|
||||
const availableProfit = Math.max(0, currentBalance - totalInvested)
|
||||
// Current balance is what's left after deposits + P&L - previous withdrawals
|
||||
// Available profit = current balance (what we have now, which includes trading profit/loss)
|
||||
const availableProfit = Math.max(0, currentBalance)
|
||||
|
||||
// Calculate inferred previous withdrawals
|
||||
// If deposits + P&L - current balance > 0, that's what was withdrawn
|
||||
const inferredWithdrawals = Math.max(0, cumulativeDeposits + totalPnL - currentBalance)
|
||||
|
||||
// Calculate next withdrawal amount
|
||||
const withdrawalPercent = parseFloat(process.env.WITHDRAWAL_PROFIT_PERCENT || '10')
|
||||
|
||||
Reference in New Issue
Block a user