본문으로 건너뛰기

How to Stream Pending Transactions with Ethers.js

업데이트 날짜:
2025년 11월 26일

읽는 데 4분

개요

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.

Prefer a video walkthrough? Follow along with Noah and learn how to stream pending transactions with Ethers.js in 8 minutes.
더 많은 영상을 보시려면 저희 유튜브 채널을 구독해 주세요!

필수 조건

  • Node.js installed on your system
  • 텍스트 편집기
  • 터미널(일명 명령줄)
  • 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:

$ node -v

설치되어 있지 않다면, 공식 웹사이트에서 NodeJS의 LTS 버전을 다운로드할 수 있습니다.

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

$ npm i ethers@5.7

Make sure that your Ethers.js installation version is 5.7

이 단계에서 가장 흔히 발생하는 문제는 `node-gyp`의 내부 오류입니다. node-gyp 설치 방법은 여기에서 확인하실 수 있습니다.

참고: node-gyp 관련 문제가 발생할 경우, 사용 중인 파이썬 버전이 위 지침에 나열된 호환 가능한 버전 중 하나와 일치해야 합니다. 

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

$ npm 캐시 정리

모든 것이 순조롭게 진행된다면, ethers.js가 시스템에 설치될 것입니다.

Quicknode 이더리움 엔드포인트 설정하기

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 create a free Quicknode account here and easily set up an Ethereum endpoint. After you've created your free Ethereum endpoint, copy your WSS (WebSocket) Provider endpoint:

Screenshot of Quicknode Ethereum Endpoint

나중에 필요할 테니, 복사해서 저장해 두세요.

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:

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. 

위의 코드에 대한 설명.

1행: ethers 라이브러리 가져오기.

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.

$ node pending

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

Use Ctrl+c to stop the script.

결론

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.

이더리움에 관한 더 많은 기사와 가이드를 받아보시려면 뉴스레터를 구독해 주세요. 의견이 있으시면 트위터를 통해 언제든지 연락해 주세요. 디스코드 커뮤니티 서버에서도 언제든지 저희와 대화를 나눌 수 있으며, 이곳에는 여러분이 만나볼 수 있는 가장 멋진 개발자들이 모여 있습니다 :)

이 가이드를 공유하세요