[Tutorial] How to receive all new transactions in a websocket connection

Hello,

Here is a very simple code example on how to receive all new transactions via websocket.

This example is a simple NodeJS app but can be translated to any language that supports websocket connections.

const WebSocket = require('ws');

const shardTemplate = (subscription, shardId) => ({
    request: {
        jsonrpc: "1.0",
        method: "subcribenewshardblock",
        params: [shardId],
        id: 1
    },
    subcription: subscription,
    type: 0
});

const txTemplate = (subscription, transactionHash) => ({
    request: {
        jsonrpc: "1.0",
        method: "subcribependingtransaction",
        params: [transactionHash],
        id: 1
    },
    subcription: subscription,
    type: 0
});

const shardBlocksSubscription = "1";
const txSubscription = "2";

const ws = new WebSocket("ws://fullnode.incognito.best:19334");

const subscribeToShardBlock = (shardId) => {
    ws.send(JSON.stringify(shardTemplate(shardBlocksSubscription, shardId)));
}

const subscribeToTransaction = (transactionHash) => {
    ws.send(JSON.stringify(txTemplate(txSubscription, transactionHash)));
}

const processNewTransaction = console.log;

ws.on('open', () => {
    [0,1,2,3,4,5,6,7].forEach(subscribeToShardBlock);
});

ws.on('message', (data) => {
    const result = JSON.parse(data).Result;    
    if (result.Subscription === shardBlocksSubscription) {
        result.Result.TxHashes.forEach(subscribeToTransaction);
    } 
    else if (result.Subscription === txSubscription) {
        processNewTransaction(result.Result);
    } 
});

The code block is scrollable, and a full version of this example is published here.

cc @abduraman :wink:

7 Likes