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 .
import * as WebSocket from 'ws';

const host = 'localhost:3000';
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 15 seconds more or less, you will receive a new notification with the content of the new harvested blocks.

Method #02: Using the SDK

The NEM2-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 listener = new Listener('http://localhost:3000');
listener.open().then(() => {
    listener
        .newBlock()
        .subscribe(block => console.log(block), err => console.error(err));
});
const listener = new nem2_sdk_1.Listener('http://localhost:3000');
listener.open().then(() => {
    listener
        .newBlock()
        .subscribe(block => console.log(block), err => console.error(err));
});

Note that the NEM2-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://localhost:3000', WebSocket);
listener.open().then(() => ...

Method #03: Using the CLI

nem2-cli monitor block