MEV 101: How To Listen For Mempool Transactions
January 11th, 2023

TL: DR; The Ethereum mempool is a waiting area for unconfirmed transactions. When a transaction is sent on the Ethereum network, it is broadcast to other nodes and must go through a series of validity checks before it can be added to a block and confirmed. While it is waiting to be confirmed, it resides in the mempool. The mempool is also known as the "pending transactions" or "txpool." Each node has its own mempool with its own rules for accepting and dropping transactions, which are determined by the node's settings. The mempool is used to store pending transactions and can be queried for information, such as to obtain trading prices on decentralized exchanges or to analyze gas prices and transaction rejection rates. In this post, we’ll have technical dive on how to take a look into the mempool and listen for particular transactions.

Requirements:

  • RPC if you don’t have one you may get one from one of the major RPC providers examples; (Infura, Quicknode, Alchemy, ect )

    • what is an RPC ? It stands for Remote Procedure Call, and it is a protocol that allows a computer program to request a service from a program located in another computer on a network without having to understand the network's details. In the context of Ethereum, an RPC is a way for a user or program to communicate with an Ethereum node or client over HTTP or IPC (Inter-Process Communication). Ethereum nodes and clients expose a set of APIs (Application Programming Interfaces) that can be accessed using RPC calls. These APIs allow users or programs to interact with the Ethereum blockchain, such as by querying the state of the blockchain, sending transactions, or interacting with smart contracts. Some examples methods we’ll use in this post are eth_getBlockByNumber, and eth_sendTransaction.
  • Ethers.js

    • what is this ? Ethers.js is a JavaScript library for interacting with the Ethereum blockchain and Ethereum-based networks. It provides a simple, easy-to-use interface for working with Ethereum, making it easier for developers to build Ethereum-based applications. Some of the features of we’ll be using in this post are:

      • Querying the Ethereum blockchain (For listing to the mempool)

      • Encrypting and decrypting messages (For decoding hash data)

      • Generating and managing Ethereum keys and addresses (for interacting with sending our own unique transactions)

      Ethers.js can be used in both Node.js and browser-based JavaScript environments, and it is designed to be lightweight and easy to use. It is a popular choice for developers building Ethereum applications because it abstracts away many of the low-level details of working with the Ethereum blockchain, making it easier to focus on building applications. you can learn more about Ethers.js here.

with all the requirements out the way let’s begin!

What Is The Mempool ?

The mempool is a part of the blockchain infrastructure that serves as a temporary storage area for transactions that have not yet been added to a block. When a node on the Ethereum network receives a transaction, it will send the transaction to other nodes for validation. If the transaction is deemed valid, it will be added to a new block by a validator. Before it is included in the block, the transaction remains in the mempool. The mempool, also known as the "pending transactions" area, serves as a buffer zone that allows nodes to perform validity checks on transactions, such as verifying that funds are available and signatures are valid. Each node can have its own rules for managing its mempool, and a transaction may be received by one node before it is propagated to the rest of the network. Although the terms may change across client {TX-POOL, TX-QUEUE, ect} the term "mempool" is widely accepted and commonly used and is the one we’ll be using.

How To Listen To The Mempool

First, let's take a look at the code:

/*
* My Code Example
*/


require('dotenv').config()
const { ethers, providers } = require("ethers");


console.log()

async function main() {
    /**
     * The WebSocketProvider connects to a JSON-RPC WebSocket compatible
     *  backend which allows for a persistent connection, multiplexing requests 
     * and pub-sub events for a more immediate event dispatching.
     */

    const provider = new ethers.providers.WebSocketProvider(process.env.ETH_RPC) //replace the Param with your endpoint 

    /**
     * provider.on( eventName , listener )
     * Add a listener to be triggered for each eventName event.     
     */

    provider.on('pending', async (tx) => {
     //prints out pending transactions aka the mempool
    // console.log(tx);

        const txInfo = await provider.getTransaction(tx);
   //print the transaction info a bit more useful! 
        console.log(txInfo);

  //in the next article we'll set up a filter to listen for
 //specific tx using the function signature.

    })

}
main();


/For a deeper dive into how exactly the methods work 
//check out the Ether.js Docs.

The following script, when executed, will output a list of all the pending transactions in the Ethereum network's memory pool, or "mempool" for short. These are transactions that have been broadcast to the network but have not yet been included in a block and confirmed by the network. By inspecting one of these transactions, we can gain a better understanding of how Ethereum's transaction processing and confirmation system works.

Example Output. The script will constantly run and query the mempool.
Example Output. The script will constantly run and query the mempool.

At first glance, the "data" value in a transaction may appear to be random and insignificant, but it actually holds crucial information that can be decoded by actors to simulate your transaction. A common tactic in the blockchain space is to exploit this information in a technique known as “front-running“. The practice of using privileged information (In this case the “privilege information” is the data hash) about an upcoming trade or transaction to execute trades before that transaction, in order to profit from the price movements caused by it.

This can happen in various ways, for example, in decentralized exchanges (DEX), where the transactions are made on-chain and therefore can be observed by anyone. If a trader has knowledge of a large trade that is about to happen, they can buy up a large amount of the assets in question before the trade is executed, anticipating the price to go up, and then sell them for a profit after the trade goes through and drive the price up.

Following this idea, we can also monitor certain actions on a decentralized exchange such as "swap" or "add liquidity" by recognizing specific function signatures. For example, the function signature for a "swap" may look something like this:

1. Swapin (0xec126c77) 

and would be included in the "data" parameter of the transaction.

The crypto and blockchain space is highly competitive, with many actors constantly looking for profitable opportunities. Traders and investors are constantly monitoring the markets for changes in prices and market trends, and they use various tools and techniques to gain an edge.

In the next article, we will delve deeper into the topic of listening for specific transactions on a decentralized exchange and how to decode the data hash using the Application Binary Interface (ABI). The ABI is a tool that helps developers understand and interact with smart contracts on the Ethereum blockchain, and it plays an important role in identifying and decoding the data hash associated with a specific transaction.

We'll explore different methods and techniques for monitoring transactions on a DEX and how to use the ABI to interpret the data hash and extract the relevant information. We'll also explain the technical details behind this process, such as how to locate the relevant function signatures and how to use the data hash to simulate the transactions.

conclusion

This guide demonstrated how to easily obtain information about unconfirmed transactions in the mempool of an Ethereum node. As mentioned previously Knowing about pending transactions can be useful for analyzing your own transactions and those of others, allowing you to make informed decisions. Following that same line of thought this Information asymmetry or toxic flow of orders can lead to an imbalance of power in the transaction and can have negative consequences for the party with less information. I believe that it is important for more people to be aware of this issue in order to help prevent it from occurring and to protect the integrity and fairness of financial markets and the Ethereum ecosystem.

If you enjoy using Twitter, feel free to send me a message and say hello.

Note: As a side note, it's important to keep the code examples included in the article, as it will be useful in the building of the script and we’ll continue its development. The code samples will give readers a hands-on understanding of how to implement the techniques and tools discussed in the article, and they can use the code as a starting point for their own projects or as a reference for troubleshooting.

sources and inspiration for this article:

Subscribe to Santiago
Receive the latest updates directly to your inbox.
Nft graphic
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from Santiago

Skeleton

Skeleton

Skeleton