feat: Add automated database sync validator for ghost position detection
PROBLEM: - Analytics page showed 3 open trades when only 1 actually open on Drift - Ghost positions in database (realizedPnL set but exitReason = NULL) - Happens when on-chain orders fill but database update fails - Manual cleanup required = unreliable dashboard SOLUTION: Automated Database Sync Validator 1. Runs every 10 minutes (independent of Position Manager) 2. Validates ALL 'open' database trades against actual Drift positions 3. Auto-fixes ghost positions (marks as closed with exitReason) 4. Provides manual validation endpoint: GET /api/admin/validate-db FEATURES: - Detects ghost positions (DB open, Drift closed) - Detects orphan positions (DB closed, Drift open) - Provides detailed validation reports - Runs on server startup + periodic intervals - Zero manual intervention required FILES: - lib/database/sync-validator.ts: Core validation logic - app/api/admin/validate-db/route.ts: Manual validation endpoint - instrumentation.ts: Auto-start on server initialization RESULT: Reliable dashboard data - always matches Drift reality
This commit is contained in:
48
app/api/admin/validate-db/route.ts
Normal file
48
app/api/admin/validate-db/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Manual Database Validation Endpoint
|
||||
*
|
||||
* GET /api/admin/validate-db
|
||||
*
|
||||
* Triggers immediate validation of database vs Drift positions
|
||||
* Useful for debugging or manual checks
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { runManualValidation } from '@/lib/database/sync-validator'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Optional: Add auth check
|
||||
const authHeader = request.headers.get('authorization')
|
||||
const expectedAuth = `Bearer ${process.env.API_SECRET_KEY}`
|
||||
|
||||
if (authHeader && authHeader !== expectedAuth) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: 'Unauthorized' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log('🔧 Manual database validation triggered via API')
|
||||
|
||||
const result = await runManualValidation()
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
result,
|
||||
message: result.ghosts > 0 || result.orphans > 0
|
||||
? `Fixed ${result.ghosts} ghost(s) and ${result.orphans} orphan(s)`
|
||||
: 'All trades validated successfully'
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Manual validation failed:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Validation failed'
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user