Fix database race condition and Drift initialization errors

- Remove saveTradeState() call from addTrade() to avoid P2025 error
- Add initialization check in checkTradeConditions() to skip when Drift not ready
- Silence 'not initialized' errors during startup (expected behavior)
- Trade state is now saved only by API endpoint after DB record created
This commit is contained in:
mindesbunister
2025-10-29 16:00:06 +01:00
parent 344a79a753
commit f7cf9ec63b

View File

@@ -141,8 +141,8 @@ export class PositionManager {
this.activeTrades.set(trade.id, trade)
// Save initial state to database
await this.saveTradeState(trade)
// Note: Initial state is saved by the API endpoint that creates the trade
// We don't save here to avoid race condition (trade may not be in DB yet)
console.log(`✅ Trade added. Active trades: ${this.activeTrades.size}`)
@@ -274,7 +274,15 @@ export class PositionManager {
// CRITICAL: First check if on-chain position still exists
// (may have been closed by TP/SL orders without us knowing)
try {
const driftService = await getDriftService()
const driftService = getDriftService()
// Skip position verification if Drift service isn't initialized yet
// (happens briefly after restart while service initializes)
if (!driftService || !(driftService as any).isInitialized) {
// Service still initializing, skip this check cycle
return
}
const marketConfig = getMarketConfig(trade.symbol)
const position = await driftService.getPosition(marketConfig.driftMarketIndex)
@@ -350,7 +358,12 @@ export class PositionManager {
} catch (error) {
// If we can't check position, continue with monitoring (don't want to false-positive)
console.error(`⚠️ Could not verify on-chain position for ${trade.symbol}:`, error)
// This can happen briefly during startup while Drift service initializes
if ((error as Error).message?.includes('not initialized')) {
// Silent - expected during initialization
} else {
console.error(`⚠️ Could not verify on-chain position for ${trade.symbol}:`, error)
}
}
// Update trade data