rawbot avatar

[Web3][Node] Rawbot - Subscribing to Pending Transactions

rawbot

Published: 29 Jul 2018 › Updated: 29 Jul 2018[Web3][Node] Rawbot - Subscribing to Pending Transactions

[Web3][Node] Rawbot - Subscribing to Pending Transactions

One of the easy ways to track a transaction on the blockchain, is by subscribing to the pendingTransactions event by using the Web3 function subscribe (web3.eth.subscribe).

Pre-requisites:

-NodeJS installed

Let's kick off with installing the necessary module (Web3)

npm init
npm install web3 --save

We're going to use Web3's WebsocketProvider, what does that mean?

WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake. This process starts with the client sending a regular HTTP request to the server. - Team Treehouse

Mainnet's Websocket endpoint: wss://mainnet.infura.io/ws
Ropsten's Websocket endpoint: wss://ropsten.infura.io/ws
Rinkeby Websocket endpoint: wss://rinkeby.infura.io/ws

Whenever the Websocket times out, we will renew the provider variable by re-assigning it.
We will track the pending transactions that return a transaction hash, then we will get each transaction details (object).

The code:

const Web3 = require('web3');
let provider = new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws');
let web3 = new Web3(provider);

provider.on('error', (e) => {
    console.error('WS Error', e);
    web3 = new Web3(provider);
    setTimeout(() => {
        subscribe_pendingTransactions();
    }, 2500);
});

provider.on('end', (e) => {
    console.error('WS End', e);
    web3 = new Web3(provider);
    setTimeout(() => {
        subscribe_pendingTransactions();
    }, 2500);
});

function subscribe_pendingTransactions() {
    web3.eth.subscribe('pendingTransactions', function (error, result) {
        if (error) {
        }
    }).on("data", function (transaction) {
        console.log("Transaction hash: " + transaction);
        web3.eth.getTransaction(transaction).then(object => {
            console.log(object);
        });
    });
}

setTimeout(() => {
    subscribe_pendingTransactions();
}, 2500);

Leave [Web3][Node] Rawbot - Subscribing to Pending Transactions to:

Written by

Read more #node posts


Best Posts From rawbot

We have not curated any of rawbot's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From rawbot