diff --git a/index.js b/index.js index 5fe7dfc..7a1ccff 100644 --- a/index.js +++ b/index.js @@ -213,6 +213,11 @@ async function validateMultimediaUrl(url) { // Bitcoin transaction monitoring functions async function initBitcoinMonitoring() { try { + // Make sure to stop any existing monitoring first + if (btcSocket) { + stopBitcoinMonitoring(); + } + btcSocket = new Socket(); btcSocket.onTransaction(async (tx) => { @@ -312,10 +317,20 @@ async function processBitcoinTransaction(tx, blockexplorer) { function stopBitcoinMonitoring() { if (btcSocket) { isMonitoring = false; + + // Properly close the WebSocket connection + try { + if (btcSocket.ws && btcSocket.ws.readyState === 1) { // WebSocket.OPEN = 1 + btcSocket.ws.close(); + } + } catch (error) { + console.error('Error closing WebSocket:', error); + } + btcSocket = null; btcMonitorChannel = null; minBtcAmount = 0; // Reset minimum amount - console.log('Bitcoin monitoring stopped'); + console.log('Bitcoin monitoring stopped and WebSocket closed'); return true; } return false;