const Web3 = require("web3");
const NODE_URL = "CHAINSTACK_WSS_URL";
const web3 = new Web3(NODE_URL);
async function subscribeToNewBlocks() {
try {
// Create a new subscription to the 'newBlockHeaders' event
const subscription = await web3.eth.subscribe('newBlockHeaders');
// Attach event listeners to the subscription object
subscription.on('connected', handleConnected);
subscription.on('data', handleNewBlock);
subscription.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 a message when the subscription is connected
function handleConnected(subscriptionId) {
console.log(`New subscription: ${subscriptionId}`);
}
// Event listener that logs the received block header data
function handleNewBlock(blockHeader) {
console.log(blockHeader);
}
// Event listener that logs any errors that occur
function handleError(error) {
console.error(`Error receiving new blocks: ${error}`);
}
async function clearSubscriptions() {
try {
await web3.eth.clearSubscriptions();
console.log("Subscriptions were cancelled 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()