A significant a part of blockchain growth revolves round interacting with and listening to decentralized networks. One of the crucial environment friendly methods to take action is thru blockchain listeners that obtain alerts concerning good contract occasions in actual time. However how do you arrange blockchain listeners? One different is ethers.js, which is a distinguished JavaScript library making it extra accessible to work together with the Ethereum community. If you wish to study extra about how this library works, be part of us on this tutorial as we illustrate easy methods to hearken to good contract occasions utilizing ethers.js!
Together with displaying you easy methods to hearken to good contract occasions utilizing ethers.js, the article initially covers the intricacies of each good contract occasions and this library. Nonetheless, if you’re already aware of these ideas, be happy to skip straight into the ”Take heed to Sensible Contract Occasions Utilizing Ethers.js” part. From there, we look at the variations between working with ethers.js and the Moralis Web3 Streams API to arrange blockchain listeners. Moreover, the Streams API is one among a number of Web3 APIs featured by Moralis that may help your growth endeavors. Furthermore, if you wish to grow to be a blockchain developer, we advocate taking a more in-depth have a look at different Moralis Web3 growth instruments. As an example, try the NFT API permitting you to, for instance, get all transfers of an NFT with a couple of traces of code!
Nonetheless, it doesn’t matter if you wish to arrange streams or have a normal curiosity in Web3 growth; enroll with Moralis now to totally leverage the ability of the blockchain trade!
Sensible Contract Occasions and Ethers.js
Earlier than displaying you easy methods to hearken to good contract occasions utilizing ethers.js, we are going to dedicate the next two sections to exploring the intricacies of good contract occasions and ethers.js. As such, should you already know what they entail, be happy to skip proper into the ”Take heed to Sensible Contract Occasions Utilizing Ethers.js” part. In any other case, be part of us as we begin by answering the query, ”what are good contract occasions?”.
What are Sensible Contract Occasions?
All Web3 contracts emit so-called ”good contract occasions” when one thing related occurs inside them primarily based on their code. In brief, these occasions are a kind of sign emitted by good contracts to inform builders and software program techniques that one thing significant has occurred. Furthermore, purposes and different platforms use these alerts to speak.
Allow us to use the ERC-20 token normal for instance to make clear this additional. All good contracts implementing this normal routinely emit a ”switch” occasion every time somebody trades a token. Furthermore, along with a notification, these occasions typically comprise extra particulars concerning the transactions.
As you might need already concluded, it’s important to have the ability to hearken to occasions like these in actual time when constructing Web3 tasks. With that mentioned, you require a seamless workflow for organising blockchain listeners that may provide you with a warning and your tasks every time one thing related happens on-chain, and that is the place ethers.js enters the equation!
Exploring Ethers.js
Ethers.js is a blockchain JavaScript (JS) library launched in 2016. It is without doubt one of the hottest open-source Ethereum JS libraries up to now, that includes hundreds of thousands and hundreds of thousands of downloads. Like typical programming libraries, ethers.js is a group of prewritten snippets of code that builders can use and reuse to carry out frequent capabilities. Nonetheless, in comparison with conventional libraries, ethers.js is Web3-based. As such, builders use this library to speak and work together with the Ethereum community extra seamlessly.

Ethers.js options 4 core modules: ”ethers.contract“, “ethers.utils“, “ethers.wallets“, and “ethers.supplier“. These 4 modules are on the very heart of the library’s software programming interface (API). Nonetheless, for extra detailed details about them and the library normally, try our article answering the query, ”what’s ethers.js?”.
Now, with this transient overview of the intricacies of ethers.js, allow us to discover a number of the library’s most distinguished advantages within the following sub-section!
Advantages of Ethers.js
With a purpose to higher perceive the utility of ethers.js and why you may wish to use the library, allow us to discover a few of its most distinguished advantages:
Safety – When working with ethers.js, you may preserve non-public keys protected and safe.Dimension – Ethers.js is a small library, solely 88 KB compressed and 284 KB uncompressed. MIT Licence – Ethers.js is totally open-source, together with all dependencies.ENS – The library options Ethereum Title Service (ENS) assist. As such, ENS names are dealt with as first-class residents. Take a look at Instances – Ethers.js gives a major assortment of check instances actively maintained and up to date.
The bullet factors above are solely 5 examples; there’s rather more so that you can uncover! Nonetheless, with a extra profound understanding of ethers.js, the library’s advantages, and good contract occasions, we’ll check out the central a part of this tutorial, easy methods to hearken to good contract occasions utilizing ethers.js!
Take heed to Sensible Contract Occasions Utilizing Ethers.js
On this part, we’ll present you easy methods to hearken to good contract occasions utilizing ethers.js. Extra particularly, we are going to shortly present you easy methods to arrange a blockchain listener for monitoring switch occasions of the USD coin (USDC) good contract. Nonetheless, earlier than dividing deeper into the central script, it’s good to take care of a couple of conditions!
To start with, it’s good to arrange a brand new NodeJS challenge and create two information: ”abi.json” and ”.env”. To the ”abi.json” file, add the USDC good contract software binary interface (ABI). From there, it’s good to add the important thing of a sound node supplier to the ”.env” file. On this occasion, we are going to present you easy methods to hearken to good contract occasions utilizing ethers.js and Alchemy. So, add a brand new surroundings variable known as ”ALCHEMY_KEY” to the file and embrace your key.
For the reason that core focus of this text is on easy methods to hearken to good contract occasions utilizing ethers.js, we is not going to dive into any extra element on organising the ”abi.json” and ”.env” information however reasonably direct our consideration towards the script itself. Nonetheless, earlier than doing so, you have to set up a few dependencies. To take action, open a brand new terminal and run the command beneath:
npm i ethers dotenv
The “index.js” File
If you find yourself finished organising the ”abi.json” and ”.env” information, the following step is to create an ”index.js” file, to which we are going to add the code for the blockchain listener. As such, with a brand new file at your disposal, the very first thing you wish to add is the next snippet on the high of ”index.js”:
const ethers = require(“ethers”);
const ABI = require(“./abi.json”);
require(“dotenv”).config();
The code above specifies that ”index.js” makes use of ethers.js, imports the contract ABI, and gives entry to the important thing from the ”.env” file. From there, you’re going to wish to create a brand new asynchronous perform known as ”getTransfers()”:
async perform getTransfer(){
const usdcAddress = “0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48”; ///USDC Contract
const supplier = new ethers.suppliers.WebSocketProvider(
`wss://eth-mainnet.g.alchemy.com/v2/${course of.env.ALCHEMY_KEY}`
);
const contract = new ethers.Contract(usdcAddress, ABI, supplier);
contract.on(“Switch”, (from, to, worth, occasion)=>{
let transferEvent ={
from: from,
to: to,
worth: worth,
eventData: occasion,
}
console.log(JSON.stringify(transferEvent, null, 4))
})
}
The perform above is comparatively simple; nonetheless, allow us to break it down from high to backside. To start with, the preliminary two traces throughout the perform’s curly brackets create two variables: ”usdcAddress” and ”supplier”.
To the previous, specify the contract tackle that you simply want to monitor. For the latter, add the node supplier utilizing one among ethers.js’ modules and the important thing from the ”.env” file.
From there, you create a brand new ”contract” object by passing the ”usdcAddress”, ”ABI”, and ”supplier” variables as arguments when calling the ”ethers.Contract()” perform. You then use the ”contract” object to set the listener, specifying that it’s switch occasions that you’re taken with.
Lastly, you make it possible for the outcomes are returned to the console. All in all, your ”index.js” file ought to now appear to be this:
const ethers = require(“ethers”);
const ABI = require(“./abi.json”);
require(“dotenv”).config();
async perform getTransfer(){
const usdcAddress = “0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48”; ///USDC Contract
const supplier = new ethers.suppliers.WebSocketProvider(
`wss://eth-mainnet.g.alchemy.com/v2/${course of.env.ALCHEMY_KEY}`
);
const contract = new ethers.Contract(usdcAddress, ABI, supplier);
contract.on(“Switch”, (from, to, worth, occasion)=>{
let transferEvent ={
from: from,
to: to,
worth: worth,
eventData: occasion,
}
console.log(JSON.stringify(transferEvent, null, 4))
})
}
getTransfer()
Working the Script
Now that you’ve accomplished the complete script used to hearken to good contract occasions utilizing ethers.js, the very last thing remaining is working the code. As such, open a brand new terminal, enter the command beneath, and hit enter:
node index.js
Working this command will return new transactions related to the USDC good contract. To offer you an thought of what it could actually appear to be, you will see a print display screen of an instance down beneath:

As you may see, the ”getTransfers()” perform returns a bunch of knowledge, such because the “to” and “from” addresses, occasion knowledge just like the block quantity, block hash, transaction index, and rather more.
That’s it! You now know easy methods to hearken to good contract occasions utilizing ethers.js! Now, whereas ethers.js is a superb growth device, there’s another many builders have discovered to be rather more useful. Thus, within the subsequent part, we are going to current an ethers.js different!
An Ethers.js Various
Regardless that ethers.js is a good library and power for organising blockchain listeners, it’s all the time price trying over different distinguished options, and an incredible instance is Moralis’ Streams API! With this software programming interface, you may simply stream on-chain knowledge into the backend of your blockchain tasks utilizing Moralis webhooks!

What’s extra, with the accessibility of Moralis, you may arrange streams or blockchain listeners in solely 5 easy steps:
Provide an tackle Apply filters to specify if you wish to obtain webhooks Choose the chain(s) you have an interest in monitoringAdd a webhook URLReceive webhooks
It doesn’t need to be extra difficult than that! Nonetheless, allow us to additionally intently look at a number of the major benefits of utilizing Moralis’ Web3 Streams API!
Benefits of Moralis’ Streams API
Moralis’ Streams API options many distinguished benefits, and yow will discover 5 examples down beneath:
100% Reliability – When working with Moralis’ Streams API, you don’t want to hassle with unreliable node suppliers. As a substitute, by utilizing Moralis, you get 100% reliability. A number of Contracts – With Moralis’ Streams API, you may create one blockchain listener for a number of completely different good contract addresses.Filters – Moralis’ Streams API is versatile, permitting you to arrange streams to obtain Web3 webhooks solely when sure circumstances are met. No Pointless Abstractions – Moralis eliminates redundant processes akin to constructing abstractions. Save Time – You would not have to waste time constructing difficult knowledge pipelines, which lets you save time in terms of listening to blockchain networks.
That covers some examples of the benefits that come from working with Moralis. With a extra profound understanding of good contract occasions, ethers.js, and Moralis, it’s time to leap into an action-packed part. As we accomplish that, we get to take a seat ringside and watch ethers.js vs Moralis Streams!
Ethers.js vs Moralis Streams When Listening to Sensible Contract Occasions
The choice to hearken to good contract occasions utilizing ethers.js is an efficient begin. Nonetheless, as you discovered within the ”Benefits of Moralis’ Streams API” part, Moralis’ Streams API gives quite a few advantages. So, how do ethers.js and Moralis Streams examine? Let’s have a more in-depth have a look at the next picture:

Within the desk above, you may see a short abstract of the similarities and variations between them. With a fast look, you instantly discover that Moralis gives all the things that ethers.js has to supply and extra. This contains 100% reliability, the choice to filter occasions, use a number of addresses, get parsed knowledge, and so on. Consequently, you may wish to contemplate Moralis in its place for listening to good contract occasions.
Nonetheless, you would not have to take our phrase for it! Within the following sub-section, we are going to shortly present you easy methods to arrange the identical blockchain listener. However as an alternative of using ethers.js, we’ll now use Moralis. Doing so highlights the benefits of working with Moralis in comparison with ethers.js!
Take heed to Sensible Contact Occasions with Moralis
You could find the complete code for organising the blockchain listener with Moralis down beneath:
const Moralis = require(“moralis”).default;
const Chains = require(“@moralisweb3/common-evm-utils”);
const EvmChain = Chains.EvmChain;
const ABI = require(“./abi.json”);
require(“dotenv”).config();
const choices = {
chains: [EvmChain.ETHEREUM],
description: “USDC Transfers 100k”,
tag: “usdcTransfers100k”,
includeContractLogs: true,
abi: ABI,
topic0: [“Transfer(address,address,uint256)”],
webhookUrl: “https://22be-2001-2003-f58b-b400-f167-f427-d7a8-f84e.ngrok.io/webhook”,
advancedOptions: [
{
topic0: “Transfer(address,address,uint256)”,
filter: {
gt : [“value”, “100000”+””.padEnd(6,”0″)]
}
}
]
};
Moralis.begin({
apiKey: course of.env.MORALIS_KEY ,
}).then(async () => {
const stream = await Moralis.Streams.add(choices);
const { id } = stream.toJSON();
await Moralis.Streams.addAddress({
id: id,
tackle: [“0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48”]
})
});
To briefly summarize, within the code above, we create an ”choices” object with a couple of parameters. Furthermore, it’s handed as an argument when calling the ”Moralis.Streams.add()” perform. So, what are the principle variations between the 2 choices?
A big distinction between ethers.js and the Moralis Streams choices is the ”Moralis.Streams.AddAddress()” perform. As you may see from the code above, we go an ”tackle” array as a parameter. On this instance, we solely embrace the USDC contract tackle. Nonetheless, you may embrace as many addresses as you want to. Consequently, you should utilize the identical blockchain listener for a number of contracts with Moralis. That is, sadly, not attainable when working with ethers.js, as it will require you to arrange new listeners for various addresses. One other distinguished instance is that you could add the ”advancedOptions” parameter within the ”choices” object to create filters!
Lastly, allow us to check out the response from working the streams-based script (earlier than executing the code, set up the required Moralis dependencies, along with “ethers” and “dotenv” put in earlier than, by working ”npm i moralis @moralisweb3/common-evm-utils” in a brand new terminal):

Within the picture above, we’ve included one of many responses despatched to our webhooks server. That is one among many transactions which might be a part of a extra in depth array. Nonetheless, because the screenshot signifies, the stream’s response incorporates parsed knowledge, together with a transaction hash, contract tackle, log index, and so on.
Would you want a extra detailed breakdown of the variations between the 2 choices we’ve in contrast? In that case, try our article on ethers.js vs Web3 streams. What’s extra, you may as well study extra about creating streams by way of the next video from the Moralis YouTube channel:
Take heed to Sensible Contract Occasions Utilizing Ethers.js – Abstract
On this article, we taught you easy methods to hearken to the blockchain with ether.js. In doing so, you found and discovered easy methods to create a blockchain listener for monitoring switch occasions. Moreover, we did so with those related to the USDC contract. Now you can apply the identical rules to some other contracts to obtain real-time alerts for future tasks!
Furthermore, should you discovered this text useful, try extra Moralis content material on the Web3 weblog. As an example, study the distinction between Web3.js vs ethers.js, or try our tutorial that additional examines an ethers.js instance.
What’s extra, if you’re severe about entering into blockchain growth, enroll with Moralis immediately! You’ll be able to create an account free of charge; it solely takes a couple of seconds, so you don’t have anything to lose!