I am working on a project using Solana web3.js with the QuickNode API. I have split my code into two files, track.js and remove.js, to keep it organized. However, I am encountering an issue when trying to remove a log listener using removeLogsListener.
Context In track.js, I use connection.onLogs(programId) to start listening to logs and save the subscription ID to a JSON file. In remove.js, I retrieve this saved ID and attempt to call connection.removeLogsListener(id).
My Codes:
Track.js
const fs = require('fs');
const connection = new Connection(clusterApiUrl('mainnet-beta'));
const programId = 'yourProgramId';
const id = connection.onLogs(programId, (log) => {
console.log('Log received:', log);
});
console.log(`Subscription ID: ${id}`);
fs.writeFileSync(`GroupsData/${ctx.chat.id}.json`, JSON.stringify({ subscriptionId: id }), 'utf8');
Remove.js
const fs = require('fs');
const connection = new Connection(clusterApiUrl('mainnet-beta'));
try {
const data = fs.readFileSync(`GroupsData/${ctx.chat.id}.json`, 'utf8');
const { subscriptionId } = JSON.parse(data);
console.log(`Retrieved Subscription ID: ${subscriptionId}`);
connection.removeLogsListener(subscriptionId);
} catch (error) {
console.error('Error removing subscription:', error);
}
when i run remove.js i got error:
Ignored unsubscribe request because an active subscription with id `0` for 'logs' events could not be found.
Additional Information:
The subscription ID is correctly saved and retrieved. It appears that onLogs and removeLogsListener need to be called within the same context, which is not feasible with my current setup.
Question:
How can I effectively manage onLogs and removeLogsListener across separate files? Is there a recommended approach to modularize this functionality while ensuring the subscription ID remains valid for removal?
What I've Tried:
Verifying that the subscription ID is correctly saved and retrieved.
Ensuring the file paths and IDs are consistent.
Environment
Solana web3Js version: ["^1.91.4"]
NodeJs version: [22.3.0]
QuickNode API
Any insights or recommendations would be greatly appreciated. Thank you!