const { ethers } = require("ethers");
const NODE_URL = "CHAINSTACK_WSS_URL";
const provider = new ethers.WebSocketProvider(NODE_URL);
async function subscribeToNewBlocks() {
try {
// Log a message when the block subscription is set up
handleConnected();
// Subscribe to new blocks and attach event listeners
provider.on("block", handleNewBlock);
provider.on("error", handleError);
} catch (error) {
console.error(`Error subscribing to new blocks: ${error}`);
}
}
/* Fallback functions to react to the different events */
// Function that logs a message when the subscription is connected
function handleConnected() {
console.log("New subscription to new blocks");
}
// Event listener that logs the received block data
async function handleNewBlock(blockNumber) {
const block = await provider.getBlock(blockNumber);
console.log(block);
}
// Event listener that logs any errors that occur
function 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()