Start for free and get your app to production levels immediately. No credit card required.You can sign up with your GitHub, X, Google, or Microsoft account.
A way to use the clearSubscriptions method is to place it in a timer to clear all of the subscriptions after a pre-determined about.The following code is an example using the subscribe(“newBlockHeaders”) method, which will be stopped and removed after one minute using clearSubscriptions:
const { ethers } = require("ethers");const NODE_URL = "CHAINSTACK_WSS_URL";const provider = new ethers.WebSocketProvider(NODE_URL);async function subscribeToNewBlocks() { try { // Subscribe to new blocks by listening for the 'block' event provider.on("block", handleNewBlock); console.log("New subscription: block"); // Attach a listener that logs any provider errors provider.on("error", handleError); } catch (error) { console.error(`Error subscribing to new blocks: ${error}`); }}/* Fallback functions to react to the different events */// Event listener that logs the received block numberasync function handleNewBlock(blockNumber) { const block = await provider.getBlock(blockNumber); console.log(block);}// Event listener that logs any errors that occurfunction handleError(error) { console.error(`Error receiving new blocks: ${error}`);}async function clearSubscriptions() { try { await provider.removeAllListeners(); console.log("Subscriptions were canceled successfully"); return process.exit(1) } catch (error) { console.error("Failed to cancel subscriptions:", error); return process.exit(1) }}async function main() { subscribeToNewBlocks(); // Run clearSubscriptions() once after 60 seconds setTimeout(clearSubscriptions, 60000);}main()
The code starts by defining an async function called subscribeToNewBlocks that creates a new subscription to new blocks by registering a listener for the block event using the provider.on method. The provider emits this event for every new block, and you can attach additional listeners, such as one for the error event. The code defines two event listener functions handleNewBlock and handleError that log messages to the console when these events occur.The subscribeToNewBlocks function is called from the main function, which is also defined in the code. The main function calls subscribeToNewBlocks to create a new subscription and then schedules the clearSubscriptions function to run once after 60 seconds using the setTimeout function. The clearSubscriptions function uses the provider.removeAllListeners method to cancel any existing subscriptions and log a message to the console if the cancellation was successful.