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:
@@ -141,8 +141,8 @@ export class PositionManager {
|
|||||||
|
|
||||||
this.activeTrades.set(trade.id, trade)
|
this.activeTrades.set(trade.id, trade)
|
||||||
|
|
||||||
// Save initial state to database
|
// Note: Initial state is saved by the API endpoint that creates the trade
|
||||||
await this.saveTradeState(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}`)
|
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
|
// CRITICAL: First check if on-chain position still exists
|
||||||
// (may have been closed by TP/SL orders without us knowing)
|
// (may have been closed by TP/SL orders without us knowing)
|
||||||
try {
|
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 marketConfig = getMarketConfig(trade.symbol)
|
||||||
const position = await driftService.getPosition(marketConfig.driftMarketIndex)
|
const position = await driftService.getPosition(marketConfig.driftMarketIndex)
|
||||||
|
|
||||||
@@ -350,7 +358,12 @@ export class PositionManager {
|
|||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// If we can't check position, continue with monitoring (don't want to false-positive)
|
// 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
|
// Update trade data
|
||||||
|
|||||||
Reference in New Issue
Block a user