subscribe("syncing") | Gnosis

web3.js subscription method that is used to subscribe to updates on the current syncing status of a Gnosis Chain node. When a client node is syncing with the rest of the network, it is in the process of downloading and verifying new blocks to ensure that its copy of the blockchain is up-to-date and in sync with the latest version of the network.

Parameters

  • string β€” a keyword identifying the type of event to subscribe to, logs in this case.
  • function β€” (optional) a callback function that will be called every time a new event of the specified type is received. This function takes two parameters: error and result. The error parameter contains any error that occurred while subscribing to the event, and the result parameter contains the data for the event that was received.

Response

  • object β€” the following sync object when the node is currently syncing:
    • startingBlock β€” the block number from which the node began syncing.
    • currentBlock β€” the latest block number the node has synced to.
    • highestBlock β€” the estimated highest block number that needs to be synced.
    • pulledStates β€” the number of state entries that have already been downloaded.
    • knownStates β€” the estimated number of state entries to be downloaded during the sync.
  • boolean β€” returns False when the node is already in sync.

subscribe("syncing") code example

πŸ“˜

Note that web3.js subscriptions require a WebSocket connection.

Use the event emitter instances to attach event listeners to the subscription object:

  • data β€” activates for each new syncing event:
  • error β€” activates if an error is detected during the subscription.
  • connected β€” activates after the subscription is successfully connected and returns the subscription ID.
  • unsubscribe β€” unsubscribes the subscription and returns true if successful.
const Web3 = require("web3");
const NODE_URL = "CHAINSTACK_WSS_URL";
const web3 = new Web3(NODE_URL);

async function subscribeToSync() {
    try {
        // Create a new subscription to the 'pendingTransactions' event
        const subscription = await web3.eth.subscribe('syncing');

        // Attach event listeners to the subscription object
        subscription.on('connected', handleConnected);
        subscription.on('data', handleSync);
        subscription.on('error', handleError);

    } catch (error) {
        console.error(`Error subscribing to sync: ${error}`);
    }
}

/* Fallback functions to react to the different events */

// Event listener that logs a message when there is a new syncing event
function handleConnected(subscriptionId) {
    console.log(`New subscription: ${subscriptionId}`);
}

// Event listener that logs the filtered events
async function handleSync(sync) {
    console.log(sync)
}

// Event listener that logs any errors that occur
function handleError(error) {
    console.error(`Error: ${error}`);
}

subscribeToSync();

Use case

A practical use case for subscribe("syncing") is a DApp that continuously listens for the status of a node and notifies the developer if the node falls behind a certain number of blocks.

The following is an implementation of this concept using web3.js subscriptions, this program will leave a notification in the console if the node falls more than 100 blocks behind.

const Web3 = require("web3");
const NODE_URL = "CHAINSTACK_WSS_URL";
const web3 = new Web3(NODE_URL);

async function subscribeToSync() {
    try {
        // Create a new subscription to the 'pendingTransactions' event
        const subscription = await web3.eth.subscribe('syncing');

        // Attach event listeners to the subscription object
        subscription.on('connected', handleConnected);
        subscription.on('data', handleSync);
        subscription.on('error', handleError);

    } catch (error) {
        console.error(`Error: ${error}`);
    }
}

/* Fallback functions to react to the different events */

// Event listener that logs a message when there is a new syncing event
function handleConnected(subscriptionId) {
    console.log(`New subscription: ${subscriptionId}`);
}

// Event listener that logs the filtered events
async function handleSync(sync) {
    let currentBlock;
    let highestBlock;
    const status = sync.status;
  
    for (const property in status) {
      if (property === 'CurrentBlock') {
        currentBlock = status[property];
        
      } else if (property === 'HighestBlock') {
        highestBlock = status[property];
      }
    }
  
    if (currentBlock !== undefined && highestBlock !== undefined) {
      const blocksBehind = highestBlock - currentBlock;
      console.log(`The node is ${blocksBehind} blocks behind the network.`);
      
      if (blocksBehind > 1000) {
        alert(`The node is ${blocksBehind} blocks behind the network. Please check your connection.`);
      }
    } 
  }

// Event listener that logs any errors that occur
function handleError(error) {
    console.error(`Error receiving new blocks: ${error}`);
}

subscribeToSync();

This code creates a new subscription to the syncing event using the web3.eth.subscribe method. This method returns a subscription object that can be used to attach event listeners to the subscription.

The code defines three event listener functions that are attached to the subscription object: handleConnected, handleSync, and handleError. The handleConnected function is called when the subscription is connected, and it logs a message with the subscription ID. The handleSync function is called when a new syncing event is emitted, extracts the CurrentBlock and the HighestBlock field, and then compares them. If the node is more than 1,000 blocks behind, the user will receive an alert.

The handleError function is called when an error occurs, and it logs an error message.

Finally, the code calls the subscribeToSync function, which creates the subscription and attaches the event listeners. When a new event is received, the handleSync function is called to extract the data and log it to the console.