The ability to listen to on-chain events using tools such as ethers.js is an essential part of Web3 development, which we’ll explore further in this article! Specifically, we’ll illustrate how to listen to the blockchain with ethers.js; however, please note that developers can use a much more effective and efficient method when working with on-chain events – Moralis’ Streams API. Moreover, thanks to Moralis’ Streams API, you do not need to listen to the blockchain with ethers.js. Even so, we’ll examine the two options below so you can decide which alternative will suit your project’s needs the most!
Moving forward, we’ll focus on an example blockchain address on Ethereum. First, we’ll listen to the blockchain with ethers.js. Then, we’ll take on the same on-chain events but use the Moralis Streams API instead. As a result, you’ll see how to use this excellent tool by implementing some simple code snippets. Furthermore, we’ll also show you how to listen to the blockchain with ethers.js and the Streams API via a neat UI.
Ultimately, this article will help you get started utilizing on-chain events efficiently. Also, it will expand your blockchain development horizons and acquaint you with Moralis. As a result, you’ll be ready to start creating all sorts of dapps and, in turn, join the Web3 revolution. So, just create your free Moralis account and follow our lead!
What is Ethers.js?
So, what is ethers.js? As “JS” suggests, ethers.js is a JavaScript (JS) library. It aims to be a complete and compact solution for developers looking to interact with the Ethereum chain. This JS library also supports other EVM-compatible programmable blockchains. Furthermore, aside from JavaScript support, the library also includes utility functions in TypeScript (TS).
Ultimately, the ethers.js library aims to achieve its goal by providing many useful features. One of its features enables you to connect to Ethereum nodes using JSON-RPC, Etherscan, MetaMask, Infura, Alchemy, or Cloudflare. Moreover, the connection with nodes is crucial when you want to listen to the blockchain with ethers.js.
Additionally, there are many other features that this JS library provides:
- Keeping your private keys in your client safe and sound.
- Importing and exporting JSON wallets (e.g., Geth and Parity).
- Creating JavaScript objects from any contract ABI, including ABIv2 and ethers’ Human-Readable ABI, with meta classes.
- Importing and exporting BIP 39 mnemonic phrases (twelve-word backup phrases) and HD wallets in several languages.
- Using ENS names as first-class citizens (they can be used anywhere an Ethereum address can be used).
- Minimal size.
- Provides you with complete functionality for all your Ethereum needs.
- Comes with extensive documentation.
- Includes a large collection of maintained test cases.
- Ethers.js is fully TypeScript ready – it includes definition files and complete TS sources.
- Comes with an open-source MIT License that includes all dependencies.
Why Listen to the Blockchain?
At this point, all tech experts agree that blockchain is the future. It is here to stay and will radically change how the world operates. After all, in one way or another, it will become an important part of most leading industries. That said, for now, the following four reasons remain the primary motivation to why developers should listen to on-chain events:
- Creating Whale Alerts – Automated triggers can be set in place, executing when more significant amounts of a specific cryptocurrency move.
- Building Automated Bots – Devs can use on-chain events to trigger bots (e.g., Discord bot) and post messages relevant to live on-chain changes.
- Monitoring NFT Collections – Non-fungible tokens (NFTs) remain one of the most popular blockchain use cases.
- Web3 Game Notifications – Web3 games are just getting started, and on-chain events will play a significant role in the player-owned gaming future.
So, whatever the primary purpose is when listening to the blockchain with ethers.js or other tools, your objective is to execute actions automatically as specific on-chain events take place. As such, the tool you use to listen to the blockchain must be effective and efficient. Ideally, it should also provide advanced options, such as filtering. Accordingly, you should make sure and determine if ethers.js is the right tool for you.
Listen to the Blockchain with Ethers.js – Example
Below, you can see the complete code of our example “index.js” script that enables us to listen to the blockchain with ethers.js. We use the top line to ensure that this NodeJS file uses ethers.js. Next, we import the application binary interface (ABI). That said, the “getTransfer” async function does the main job of listening to the blockchain. The latter focuses on the USDC contract address. Inside the function, we use the ethers.js library’s “WebSocketProvider” endpoint. This endpoint enables us to define which node provider we will use. Of course, we need to obtain that provider key to actually use it. Moreover, as you can see below, we are using Alchemy for this example. We also store our Alchemy key in the “.env” file under the “ALCHEMY_KEY” variable.
Note: If you decide to listen to the blockchain with Ethers.js, make sure you select the node provider that supports the chain(s) you want to focus on.
Inside the “getTransfer” function, we also define which contract, ABI, and provider to use. Finally, we set the listener that will listen to the transfer event. The listener will also console-log the details of the transfer. The latter include “from“, “to“, “value“, and “eventData“. Unfortunately, ethers.js doesn’t have the capacity to parse the data.
Our Example Script and Its Results
Following is our example script that you can use to listen to the blockchain with ethers.js:
const ethers = require("ethers"); const ABI = require("./abi.json"); require("dotenv").config(); async function getTransfer(){ const usdcAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; ///USDC Contract const provider = new ethers.providers.WebSocketProvider( `wss://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_KEY}` ); const contract = new ethers.Contract(usdcAddress, ABI, provider); contract.on("Transfer", (from, to, value, event)=>{ let transferEvent ={ from: from, to: to, value: value, eventData: event, } console.log(JSON.stringify(transferEvent, null, 4)) }) } getTransfer()
We run the above script using the “node index.js” command. Then, we get to see the results in the terminal, like so:
If you look at the above data, you can see that it includes quite a lot of information. However, while the above is a great start, the data is not parsed. Thus, you’d need to invest quite some time and effort to process it properly. Fortunately, there is a reliable alternative that can make your task of listening to on-chain events a lot simpler.
Ethers.js Alternatives for Listening to On-Chain Events
In the previous section, you were able to see ethers.js in action. When you listen to the blockchain with ethers.js, you get real-time events, and it also enables you to cover multiple chains. Accordingly, it’s safe to say that this library is a decent open-source solution for listening to the blockchain. However, ethers.js has several limitations, which will hold you back when creating dapps.
For one, it doesn’t provide you with 100% reliability because you need to provide separate node providers. Those node providers may only support some of the chains you want to focus on. Also, you need to make sure those nodes stay live. Ethers.js also doesn’t let you filter events, and it doesn’t let you use multiple addresses. Instead, you must create separate listeners for all contracts. Plus, ethers.js doesn’t provide the option to listen to wallet addresses. Finally, as pointed out above, the data you receive when you listen to the blockchain with ethers.js is not parsed.
With that said, you must admit that it would be great if there was an alternative covering all those additional options. After all, it would make listening to on-chain events a lot more user-friendly.
Fortunately, Moralis’ Streams API bridges all those gaps that ethers.js leaves you with. Hence, aside from real-time events across multiple chains, Moralis ensures 100% reliability, as you do not need to worry about node providers. Furthermore, Moralis lets you filter events, pool multiple addresses into a single stream, and listen to wallet addresses. Moralis even parses the data for you. Accordingly, you do not need to deal with additional data processing.
Listen to the Blockchain with Moralis’ Streams API – Example
In this section, we will focus on the same event – any USDC transfer on Ethereum – as above. However, instead of using ether.js, we will use Moralis’ Streams API. As such, we create another “index.js” file that imports Moralis and its utils:
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 options = { 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.start({ apiKey: process.env.MORALIS_KEY , }).then(async () => { const stream = await Moralis.Streams.add(options); const { id } = stream.toJSON(); await Moralis.Streams.addAddress({ id: id, address: ["0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"] }) });
The above script uses the same ABI. Furthermore, you can see the options that the Streams API provides. For one, it allows you to choose one or multiple supported blockchains. After all, Moralis is all about cross-chain interoperability and supports all the leading chains.
However, as you can see, for this example, we are focusing on Ethereum. Aside from the “chains” option, we need to define a description, a tag, whether we want to include contract logs or not, an ABI, a topic, and a webhook URL. Regarding the latter, you can use ngrok when developing to create a tunnel for your local host.
Moving down our example script, we need to initiate Moralis. This is where we need to use our Moralis Web3 API key. We get this key by creating a free Moralis account to access our admin area. From there, we get to copy our Web3 API in two steps, as seen in the following image:
We paste our Moralis Web3 API key into the “.env” file next to the “MORALIS_KEY” variable. Then, we create our stream with the above-described options. Nonetheless, we can simply add all the addresses we want to listen to using the “addAddress” endpoint. In our example script, we only focus on the USDC contract address. However, we could add other addresses as well (simultaneously listening to USDC and USDT transfers):
Finally, to view the results, we run the “node index.js” command.
Exploring Moralis Streams
After running the above-presented script, we get to see the “usdcTransfers” stream in our Moralis dashboard:
This is also where we can pause our edit our stream. Nonetheless, as the “New Stream” button in the image above indicates, we can create streams using the admin UI as well. Now, let’s also explore the results for our stream in our console:
Looking at the screenshot above, you can see that we have parsed data. Also, aside from transaction hashes and the “from” and “to” addresses, our results provide us with the transfers’ value.
To explore the results of our example stream further, check out the video below, starting at 8:43. In that video, you’ll see the power of event filters that the API offers (11:51). Last but not least, make sure to learn more about this powerful Web3 API using Moralis’ Web3 Streams API docs.
How to Listen to the Blockchain with Ethers.js – Summary
In today’s article, you had a chance to learn how to listen to the blockchain with ethers.js. We first made sure you know what ethers.js is. Then, you were able to follow our lead and create an example NodeJS script to fetch on-chain data using this JS library. As such, you discovered that you need to use a node provider that supports the chain you want to focus on. Next, we took a look at an ethers alternative, and you discovered what makes Moralis’ Streams API so valuable. Last but not least, you had an opportunity to see an example stream in action, and you also learned how to obtain your Moralis Web3 API key and use the Moralis admin UI to edit, pause, and create new streams.
With the knowledge obtained in this article, you are now ready to start using on-chain events as all sorts of triggers for your dapps. Aside from the Streams API, Moralis provides you with the ultimate NFT API, Token API, and Web3 Auth API. Hence, you have all the tools you need to tackle all sorts of dapp development projects. For additional guidance and practice, use the Moralis docs and the Moralis YouTube channel. If you want to explore other blockchain development topics, Moralis’ blog is the place to be. Some of the latest articles focus on Web3 storage, ethers.js vs Web3 streams, Palm NFT Studio, and much more. Plus, if Ethereum development interests you the most, make sure to read up on Ethereum’s testnets in our articles exploring Goerli ETH and the Sepolia testnet!
Additionally, you should consider taking a more professional approach to your crypto education by enrolling in Moralis Academy. There, you’ll find a ton of amazing blockchain development courses, and we recommend you start with blockchain and Bitcoin fundamentals.