Get notified when a new block is included.
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 = 'api-01.us-east-1.096x.symboldev.network: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.
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.
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 = 'http://api-01.us-east-1.096x.symboldev.network:3000';
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 = 'http://api-01.us-east-1.096x.symboldev.network:3000';
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://api-01.us-east-1.096x.symboldev.network:3000', WebSocket);
listener.open().then(() => ...
symbol-cli monitor block
Did you find what you were looking for? Give us your feedback.