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

in node •  6 years ago  (edited)

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);
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!