Marketplace has launched, further enabling blockchain developers! Learn more

How to stream pending transactions with ethers.js

September 21, 2022

Overview

Here is a video representation of this guide if you prefer to watch instead of read



On ethereum, before being included in a block, transactions remain in what is called a pending transaction queue, tx pool, or mempool - they all mean the same thing. Miners then select a subset of all pending transactions from this queue to mine - there are a lot of benefits to being able to access and analyze this information for traders, people who want to save fees on gas, and more.

In this guide, we will learn how to stream pending transactions from Ethereum and similar chains with ethers.js.

Prerequisites
  • NodeJS installed on your system.
  • A text editor
  • Terminal aka Command Line
  • An Ethereum node

What is a Pending Transaction?

To write or update any on the Ethereum network, someone needs to create, sign and send a transaction. Transactions are how the external world communicates with the Ethereum network. When sent to the Ethereum network, a transaction stays in a queue known as mempool where transactions wait to be processed by miners - the transactions in this waiting state are known as pending transactions. The small fee required to send a transaction is known as a gas; Transactions get included in a block by miners, and they are prioritized based on the amount of gas price they include which goes to the miner.

You can get more information on mempool and pending transactions here.

Why do we want to see pending transactions?
By examining pending transactions, one can do the following:

  • Estimate gas: We can theoretically look at pending transactions to predict the next block's optimal gas price.
  • For Trading analytics: We can analyze pending transactions on decentralized exchanges. To predict market trends using the analysis.
  • Front running: In DeFi, you can preview upcoming oracle related transactions related to price and potentially issue a liquidation for a vault on MKR, COMP, and other protocols.

There can be many use cases for streaming pending transactions - we won't cover them all here.

We’ll use ethers.js to stream these pending transactions with WebSockets. Let’s see how to install ethers.js before writing our code.

Installing ethers.js

Our first step here would be to check if node.js is installed on the system or not. To do so, copy-paste the following in your terminal/cmd:

installing ethers js

Copy
$ node -v

If not installed, you can download the LTS version of NodeJS from the official website.

Now that we have node.js installed let’s install the ethers.js library using npm (Node Package Manager), which comes with node.js.

installing ethers js

Copy
$ npm i ethers

The most common issue at this step is an internal failure with `node-gyp.` You can follow node-gyp installation instructions here.

Note: You will need to have your python version match one of the compatible versions listed in the instructions above if you encounter the node-gyp issue. 

Another common issue is a stale cache; clear your npm cache by simply typing the below into your terminal:

installing ethers js

Copy
$ npm cache clean

If everything goes right, ethers.js will be installed on your system.

Booting our Ethereum node

We could use pretty much any Ethereum client, such as Geth or OpenEthereum (fka Parity), for our purposes today. Since to stream incoming new pending transactions, a node connection must be stable and reliable; it’s a challenging task to maintain a node, we'll just grab a free endpoint from QuickNode to make this easy. After you've created your free ethereum endpoint, copy your WSS (WebSocket) Provider endpoint:

Screenshot of QuickNode Ethereum Endpoint

You'll need this later, so copy it and save it.

Streaming pending transactions

Create a short script file pending.js, which will have a transaction filter on incoming pending transactions. Copy-paste the following in the file:

streaming pending transactions

Copy
var ethers = require("ethers");
var url = "ADD_YOUR_ETHEREUM_NODE_WSS_URL";

var init = function () {
  var customWsProvider = new ethers.providers.WebSocketProvider(url);
  
  customWsProvider.on("pending", (tx) => {
    customWsProvider.getTransaction(tx).then(function (transaction) {
      console.log(transaction);
    });
  });

  customWsProvider._websocket.on("error", async () => {
    console.log(`Unable to connect to ${ep.subdomain} retrying in 3s...`);
    setTimeout(init, 3000);
  });
  customWsProvider._websocket.on("close", async (code) => {
    console.log(
      `Connection lost with code ${code}! Attempting reconnect in 3s...`
    );
    customWsProvider._websocket.terminate();
    setTimeout(init, 3000);
  });
};

init();

So go ahead and replace `ADD_YOUR_ETHEREUM_NODE_WSS_URL` with the WSS  (WebSocket) provider from the section above. 

Explanation of the code above.

Line 1: Importing the ethers library.

Line 2: Setting our Ethereum node URL.

Line 4: Creating the init function.

Line 5: Instantiating an ethers WebSocketProvider instance.

Line 7: Creating an event listener for pending transactions that will run each time a new transaction hash is sent from the node.

Line 8-10: Getting the whole transaction using the transaction hash obtained from the previous step and printing the transaction in the console.

Line 13-16: A function to restart the WebSocket connection if the connection encounters an error.

Line 17-21: A function to restart the WebSocket connection if the connection ever dies.

Line 24: Calling the init function.

Now, let’s run our script.

streaming pending transactions

Copy
$ node pending

If everything goes right, you must see incoming pending transactions. Something like this



Use Ctrl+c to stop the script.

Conclusion

Here we saw how to get pending transactions from the Ethereum network using ethers,js. Learn more about Event filters and Transaction filters in ethers.js in their documentation.

Subscribe to our newsletter for more articles and guides on Ethereum. If you have any feedback, feel free to reach out to us via Twitter. You can always chat with us on our Discord community server, featuring some of the coolest developers you’ll ever meet :)

Related articles 35

How to do a non-custodial transaction with QuickNode
Originally Published On: Jun 19, 2021
Updated On: Sep 9, 2022

Private keys are one of the most... A non-custodial wallet is a... Custodian of Private... At We could use pretty much any... We could use any of the many... Let us create a token transfer... Congratulations on making a...

Continue reading
How to Set Up a Near Project from Scratch
Originally Published On: Jan 27, 2022
Updated On: Sep 9, 2022

In this tutorial we will look at... In this section, we will... In this section, we will look at... In this section, we will look at... When writing smart contracts on... In the last section, we looked... In the last section, we looked... In the last section, we looked... We have finally come to the end...

Continue reading
Estimating gas price using pending transactions in Python
Originally Published On: Feb 20, 2021
Updated On: Sep 9, 2022

To send a transaction on the... Gas is the unit to measure the... Why do we want to estimate gas?... Our first step here would be to... For our purposes today, we could... The first thing we’re going to... Now you know how to estimate gas...

Continue reading
Como crear y lanzar un ERC-721 (NFT)
Originally Published On: Dec 27, 2021
Updated On: Sep 9, 2022

Coleccionables digitales que son... Fungible significa que es lo... ERC es la abreviación para... Ahora que conocemos qué es y... Antes de escribir nuestro... Felicidades por crear tu propio...

Continue reading
How to Access Bitcoin Mempool
Originally Published On: Aug 16, 2021
Updated On: Sep 21, 2022

Bitcoin is the father of... The transactions which are sent... For our purpose today, we need a... We will use Bitcoin RPC methods... Congratulations on mastering the...

Continue reading
How to Mint an NFT on Polygon with Ethers.js
Originally Published On: Mar 28, 2022
Updated On: Sep 9, 2022

This guide demonstrates how to... Ethers.js is a complete Ethereum... As a reminder, the act of... We will deploy our contract on... Time to write the code! Start by... Note, you will need some... That’s it! You have minted an...

Continue reading
How to access Ethereum Mempool
Originally Published On: Oct 15, 2020
Updated On: Sep 15, 2022

On Ethereum, when a transaction... In blockchain terminology, a... For the purpose of this guide,... First, query the Let’s examine how to subscribe... This short guide showed you how...

Continue reading
The Web3 Developer Stack
Originally Published On: Jul 3, 2021
Updated On: Sep 15, 2022

A developer stack is a bag of... If we can imagine web3 as a car... The Chainlink price feed... Head over to the We’ll need a Kovan node to... We’ll now write a short... Congratulations :D You’ve taken...

Continue reading
How to Mint NFTs on the Stacks Blockchain
Originally Published On: Aug 19, 2022
Updated On: Sep 9, 2022

Stacks is an emerging blockchain... The Stacks ecosystem has adopted... Open up a terminal window and... Implementing the SIP-009... This section will demonstrate... The moment you've been waiting... Awesome Work! You’ve learned how...

Continue reading
Introduction to Scaffold-ETH 🏗
Originally Published On: Oct 7, 2021
Updated On: Sep 9, 2022

Developing applications involves... First of all, before getting... Scaffold-ETH comes with a demo... We will set up a QuickNode... Congratulations, and thank you...

Continue reading
How to connect to Ethereum using PHP
Originally Published On: Jun 11, 2021
Updated On: Sep 9, 2022

PHP is a very popular choice... Before installing the web3.php,... We could use pretty much any... Now, make a PHP script file... Congratulations on connecting to...

Continue reading
How to use Subspace with QuickNode
Originally Published On: Sep 8, 2020
Updated On: Sep 9, 2022

In this guide, we'll understand... To install Subspace, we'll need... For our purposes today, we could... Now let's create a short script,... Run the file using the node...

Continue reading
How to Connect Your Dapp With MetaMask Using Ethers.js
Originally Published On: Dec 13, 2021
Updated On: Sep 9, 2022

In our dApp, we will have a... A dApp is an application that... We will need to install the... Ethers.js is a lightweight... With this application, we will... Next, we will create a function... After connecting to MetaMask, we... To handle the wallet address of... This section will show us how to... In this tutorial, we...

Continue reading
How to Lazy Mint an NFT on Rarible with Rarepress
Originally Published On: Feb 23, 2022
Updated On: Sep 9, 2022

NFTs are great for creators to... To mint an NFT, you write data... Lazy Minting is a process in... We will write some JavaScript... Rarepress interacts with the... Now that we have everything in... Congratulations on listing your...

Continue reading
How to get the balance of an ERC-20 token
Originally Published On: Jun 14, 2021
Updated On: Sep 21, 2022

When a new token is made on the... You could use any Ethereum... Now that you've done the legwork... Getting the ERC20-Token Balance... In the top of your... ABI is short for You will most likely interact... You can use a similar process... We now have a connection to an... Having made it to the end, you...

Continue reading