Listening to new blocks

Get notified when a new block is included.

Prerequisites

Method #01: Using WebSockets

1. First, we need to create a bidirectional link between our client application and the REST Gateway. To do so, open a new WebSocket connection connection. Remember to use a suitable NODE_URL.

import * as WebSocket from 'ws';

const host = 'NODE_URL';
const ws = new WebSocket('ws://' + host + '/ws');

ws.on('open', () => {
    console.log('Connection opened');
});

ws.on('close', () => {
    console.log('Connection closed');
});

ws.on('message', (msg) => {
    const response = JSON.parse(msg);
    if ('uid' in response) {
        console.log('uid:', response);
    } else {
        console.log(response);
    }
});

Once the connection is open, you will get a unique string identifier named uid. As we want to get notifications every time there is a new block harvested; the next step is to subscribe to the block channel. Check here the complete list of channels available.

  1. Send the uid received during the connection phase, and the channel name formatted as follows.

ws.on('message', (msg) => {
    const response = JSON.parse(msg);
    if ('uid' in response) {
      const body = '{"uid":"' + response.uid +'", "subscribe":"block"}';
      console.log('uid:', response);
      ws.send(body);
    } else {
        console.log(response);
    }
});

From that moment, every 30 seconds more or less, you will receive a new notification with the content of the new harvested blocks.

Method #02: Using the SDK

The Symbol SDK simplifies the process of handling WebSocket connections.

In the SDK, WebSockets are named Listeners. As we have done with WebSockets, we need to open the connection first and subscribe to the desired channel, but this time without handling uids.

const nodeUrl = 'NODE_URL';
const repositoryFactory = new RepositoryFactoryHttp(nodeUrl);
const listener = repositoryFactory.createListener();

listener.open().then(() => {
  listener.newBlock().subscribe(
    (block) => {
      console.log(block);
      listener.close();
    },
    (err) => console.error(err),
  );
});
const nodeUrl = 'NODE_URL';
const repositoryFactory = new symbol_sdk_1.RepositoryFactoryHttp(nodeUrl);
const listener = repositoryFactory.createListener();
listener.open().then(() => {
  listener.newBlock().subscribe(
    (block) => {
      console.log(block);
      listener.close();
    },
    (err) => console.error(err),
  );
});

Note that the Symbol SDK for TypeScript base Listener is designed to work on Node.js backend environments. If you want to execute Listeners from the client-side (e.g., Angular, React, Vue.), pass the browser implementation of the WebSocket to the Listener.

const listener = new Listener('ws://ngl-dual-101.testnet.symboldev.network:3000', WebSocket);
listener.open().then(() => ...

Method #03: Using the CLI

Open a terminal window and run the following command.

symbol-cli monitor block