본문으로 건너뛰기

Web3.js How to subscribe to pending transactions using web3.subscribe

정보

This tutorial makes use of Web3.js v1.x.x. Not all functionality might work with Web3.js v4.

Web3 subscriptions allow you to subscribe to events on the blockchain, including new blocks, pending transactions, and contract events.

To subscribe to pending transactions for a certain address using Web3, you can use the following code snippet:

const Web3 = require("web3");

const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_API_KEY");

const address = "0x1234567890123456789012345678901234567890";

const subscription = web3.eth.subscribe(
"pendingTransactions",
{
address: address,
},
(error, result) => {
if (!error) {
console.log(result);
} else {
console.error(error);
}
},
);

// Unsubscribe after 10 minutes
setTimeout(() => {
subscription.unsubscribe((error, success) => {
if (success) {
console.log("Unsubscribed successfully!");
} else {
console.error("Error unsubscribing:", error);
}
});
}, 10 * 60 * 1000); // 10 minutes

In this code snippet, we are using the web3.eth.subscribe method to subscribe to pending transactions for a specific address. We pass in the 'pendingTransactions' parameter to specify that we want to subscribe to pending transactions, and we also pass in an options object with the address property set to the address we want to monitor.

Once we have subscribed to the pending transactions, we can listen for new transactions by passing a callback function to the subscribe function. In this example, we are simply logging the transaction hash to the console.

Finally, we set a timeout to unsubscribe from the subscription after 10 minutes. This is important to prevent the subscription from running indefinitely, which could lead to performance issues or excessive API usage.

Note that you will still be rate limited by your Ethereum node or API provider, so you may want to consider upgrading to a higher-tier plan if you need to monitor a large number of addresses.