Whether you’re a developer needing a refresher on Web3 libraries or are currently transitioning from Web2 to Web3 and need help understanding which Web3 library would benefit you the most, you’ve come to the right place! In addition to exploring the top Web3 libraries, we’ll also look at an alternative to these libraries offering a superior solution: Moralis. Now, since ethers.js is one of the most popular Web3 libraries, we’ll compare ethers.js vs Web3 streams, showing the power of the Moralis Streams API! To illustrate, when working with Moralis’ JS SDK, these are the lines of code that do the trick:
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, address }) });
If you want to learn how to properly implement the above snippet of code, make sure to dive into the “Web3 Libraries Example” section. This is where we’ll also show you how to obtain your Web3 API key. If you’re ready, create your free Moralis account and follow our lead!
Overview
In today’s article, we will first do an overview of the leading Web3 libraries. This will help you determine which of them might be worth your attention. As pointed out above, ethers.js has become the most popular Web3 library. As such, we’ll proceed by focusing on comparing the ethers.js Web3 library with the Web3 Streams API from Moralis. This comparison will clearly indicate how you can take the path of least resistance and join the Web3 revolution with your legacy skills.
For those who may not yet be familiar with Web3 libraries, we’ll also explain what they are. Last but not least, we’ll dig a little deeper into the best alternative to our highlighted Web3 libraries. This is where you’ll have an opportunity to learn more about the Streams API and other Moralis tools. Then, you’ll be ready to start building dapps the easy way!
List of Web3 Libraries
As the above image indicates, some of the leading Web3 libraries are:
- Libp2p
- Web3j
- Web3.js
- Web3.py
- Ethers.js
You might have noticed the light.js library in the above image but not in our list. That’s because that library is deprecated. Therefore, we won’t explore this library any further. Now, let’s cover each of the above five libraries in further detail!
Libp2p
“Library peer-to-peer,” or “libp2p,” is more than a Web3 library. It is a peer-to-peer (P2P) networking framework – a collection of specifications, protocols, and libraries. The framework facilitates P2P communication between network participants (a.k.a. “peers”) and enables the development of P2P applications.
Libp2p started as IPFS’ (InterPlanetary File System) wire protocol. However, it phased out into an independent networking layer, which provides a set of specs that many protocols can adopt. This allows libp2p apps to operate in diverse runtimes and networking environments. For instance, IPFS uses the Golang implementation of libp2p, but Polkadot uses the Rust implementation of this library. So, libp2p handles the peer discovery and communication in the Polkadot ecosystem. In addition, according to Polkadot’s official website, libp2p is positioned to be the standard for future dapps.
Following are some of the key advantages of libp2p as listed in this framework’s documentation:
- Modularity – Allows developers to mix and match different components to accommodate the needs of their apps.
- Extensive Transport “Configurability” – By supporting various transport protocols, libp2p applications can operate in various runtime and networking environments.
- Versatility – Offers a range of discovery mechanisms and data storage/retrieval patterns and is implementable in many programming languages.
- Security – Includes several security features.
- Robustness – Designed to withstand stress, disturbance, and change. Further, it can recover quickly from disruptions or failures.
- Resiliency – Even if some peers are offline or unreachable, the network remains available and accessible.
- Efficiency – Makes it possible to store and retrieve data in a cost-effective and scalable way.
- Piercing NAT Barriers – With capabilities for NAT traversal, libp2p maintains the connectivity of the network and ensures that it remains accessible despite the presence of firewalls or NAT devices.
- Interoperability – Implementations in different programming languages and versions are interoperable with one another.
- Decentralization – Operating without a central authority.
Web3j
Web3j is a highly modular, reactive, type-safe Java and Android library for the Ethereum network. It enables you to work with smart contracts and interact with Ethereum clients (nodes) (see the above image) without writing your own integration code.
Like all leading Web3 libraries, web3j supports Ethereum wallets and the implementation of Ethereum’s JSON-RPC client API via HTTP and IPC. It also features an auto-generation of Java smart contract wrappers. This means you can create, deploy, transact with and call smart contracts from native Java code. Web3j also supports Solidity and Truffle definition formats.
This library enables you to work with filters using its reactive-functional API. Web3j further supports Ethereum Name Service (ENS), OpenEthereum’s and Geth’s personal client APIs, node providers (Alchemy and Infura), ERC-20 and ERC-721 token standards, and JP Morgan’s Quorum via “web3j-quorum.”
The Web3j Ethereum Java library also includes comprehensive integration tests, command line tools, and Android compatibility. If you are interested in learning more about this library and working with it, visit the official web3j documentation.
Web3.js
Web3.js is an open-source JavaScript (JS) library created by the Ethereum Foundation. The main purpose of Web3.js is to facilitate seamless interactions with the Ethereum chain. This interaction is possible via communication with Ethereum nodes, which goes through the JSON-RPC protocol. The core of Web3.js are the following five modules:
- “web3.eth“ – It facilitates interaction with the Ethereum network via multiple sub-modules (“web3.eth.contract,“ “web3.eth.subscribe,“ “web3.eth.accounts,“ etc.).
- “web3.net“ – Facilitates interaction with network properties.
- “web3.shh“ – It facilitates interaction with the Whisper protocol.
- “web3.utils“ – Provides access to functions for Ethereum dapps and other packages.
- “web3.bzz“ – It facilitates interaction with the Swarm network.
Once we cover ethers.js (below), you’ll realize that these two Web3 libraries are quite similar. Even though they both serve the same purpose, there are several distinct differences between the two. Moreover, if you are interested in learning more about those distinct differences, make sure to check out our Web3.js vs ethers.js comparison. For more details, visit the official Web3.js documentation.
Web3.py
If you are Python proficient, you can use the Web3.py library to join the Web3 revolution. As “.py” indicates, this Web3 library supports the Python programming language for interactions with the Ethereum chain. So, whether you want to send transactions, read block data, interact with smart contracts, or more, Web3.py has your back.
Just like Web3.js, Web3.py communicates with the Ethereum network using the JSON-RPC protocol. The latter enables the Web3.py library to make requests to Ethereum nodes and write and read data on the Ethereum blockchain. The concept behind this communication is much like making HTTP requests to JSON APIs on web servers.
It’s worth pointing out that Web3.py’s application programming interface (API) originates from the above-described Web3.js. Of course, through time, Web3.py has evolved to become more adapted for Python development. Still, there are many similarities between the two Web3 libraries. As such, it can be of great value to go over the Web3.py vs Web3.js comparison as well. That is especially true if you are JavaScript and Python proficient. However, if Python is your preferred programming language, you should focus on Ethereum Python implementation.
Ethers.js
As mentioned above, just like Web3.js, ethers.js is a JS library aiming to be a complete and compact solution for Ethereum development. This library entered the scene about a year after Web3.js. However, despite its latter arrival, it has managed to become the most popular Web3 library.
Aside from JavaScript support, ethers.js also includes utility functions in TypeScript (TS). Some of its main advantages include a considerable collection of maintained test cases, keeping private keys in your client safe and sound, and the ability to create JavaScript objects from any contract ABI, including ABIv2 and the ethers Human-Readable ABI with meta classes. Other important benefits of ethers.js include the following:
- Importing and exporting JSON wallets (e.g., Geth and Parity).
- Supports use of ENS names anywhere Ethereum addresses can be used.
- Importing and exporting BIP 39 mnemonic phrases (twelve-word backup phrases) and HD wallets in several languages.
- Multiple ways to connect to Ethereum nodes (JSON-RPC, Etherscan, MetaMask, Infura, Alchemy, or Cloudflare).
- Compact size.
- Fully TypeScript ready – it includes definition files and full TS sources.
- An open-source MIT license that includes all dependencies.
Thanks to all these benefits, ethers.js dapp development really took off in 2022, with more than 900,000 downloads. However, we believe there is an even better way to fetch on-chain data and listen to on-chain events. But we want you to determine for yourself whether you prefer working with ethers.js events or the Moralis Streams API. As such, make sure to explore the upcoming Web3 libraries example.
Web3 Libraries Example – Ethers.js vs Web3 Streams
The above video shows you how to listen to events using ethers.js and how to do the same with the Moralis Streams API. In the case of ethers.js, the “getTransfer()” function does most of the job. Within the function, we provide a contract address we want to listen to, a provider, and define the smart contract’s event that we want to focus on (“Transfer” in our case). Here’s the full script that gets the job done using ethers.js:
const ethers = require(“ethers”); const ABI = require(“./abi.json”); require (“dotenv”).config(); async function getTransfer(){ const usdcAddress = ”0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48”; 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()
Here’s the format in which you’ll see the result in your terminal after running the above script:
Note: Your exact results won’t match the ones above but the current live transactions.
Looking at the above screenshot, you can see that the data is not parsed. This means you need to further process the results before you can utilize them in your dapp. Fortunately, that is not the case when we use the Moralis Streams API.
Web3 Libraries – The “Killer” Alternative
In this section, you’ll finally learn how to properly implement the snippet of code provided in the introduction of today’s article. If you want to use the following script to listen for on-chain events, you need to obtain your Moralis Web3 API key. The latter awaits you inside your admin area, which you’ll be able to access with your free account:
Then, save your API key inside your “.env” file under the “MORALIS_KEY” variable. Next, you can use our script below.
First, we need to import Moralis, EVM-compatible chains, and the ABI, and require “dotenv”:
const Moralis = require("moralis").default; const Chains = require("@moralisweb3/common-evm-utils"); const EvmChain = Chains.EvmChain; Const ABI = require(“/abi.json”); require("dotenv").config();
With the above lines in place, we can define our stream’s options:
const options = { chains: [EvmChain.ETHEREUM], description: "USDC Transfers", tag: "usdcTransfers", includeContractLogs: true, abi: ABI, Topic0: [“Transfer(address, address,uint256)”], webhookUrl: "your webhook url - use" };
Finally, we get to implement the snippet of code from the intro and add the USDC smart contract address:
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”] }) });
With all of the above lines of code in place, we are ready to run the script, which returns parsed on-chain data:
The above-created stream also appears in our admin area. The “Streams” tab of the admin area is also the place where we can pause, edit, or delete any existing stream:
As the “New Stream” button indicates, this is also the place where we can create new streams using the admin UI. The latter takes us through the steps to set up options (like in the code above).
What are Web3 Libraries?
Web3 libraries are programming libraries that focus on Web3 development. They are collections of non-volatile resources that programmers can use for consistent and more user-friendly coding of scripts that in some way interact with blockchain networks. These resources can include configuration data, documentation, help data, message templates, pre-written code and subroutines, classes, values or type specifications, and more.
Ethereum continues to be the leading programmable blockchain and, therefore, the heart of Web3 development. Plus, many other blockchains follow Ethereum’s lead by being EVM-compatible. This also means they can use the same development tools. As such, most Web3 libraries focus on Ethereum. However, a Web3 library can target any other blockchain network (private or public) and any programming language.
Programming Languages for Web3 Libraries
If you covered the above-presented Web3 libraries, you now know that JavaScript, Python, and Java are the programming languages behind the most popular libraries and also their alternatives. This also tells you that Web3 libraries help legacy devs use their Web2 proficiency to enter dapp development. For instance, in the case of Polkadot and Solana, Rust would be the language to use.
However, you probably know that smart contracts are an essential part of Web3 technology. As you progress, you may become interested in creating advanced and unique smart contracts. In that case, the aforementioned Web3 programming languages may not be enough. Sure, there are already some ways to create smart contracts with legacy languages, but Solidity is the leading choice among smart contract programming languages.
If you want to explore how you can utilize your legacy skills, make sure to check out our articles showing how to create an ERC721 token or ERC1155 token. Also, see how to tackle the “create ERC20 token” quest!
Web3 Libraries Alternative
If you took on the above example, you already had an opportunity to get acquainted with the Moralis Streams API. You learned that it is the ultimate tool to listen to any smart contract or wallet address. You also found out that you can create new streams using the Moralis admin UI or Moralis’ SDK. Essentially, Moralis Streams enable you to stream blockchain data into your backend via webhooks. Furthermore, since Moralis supports all the leading blockchains, you can do this on Ethereum, Polygon, Avalanche, BNB Chain, Fantom, Cronos, all testnets, and other networks. To explore the Moralis Streams API further, use the “Streams API” link in the intro.
Aside from listening to smart contracts and wallets, you can use Moralis to implement Web3 authentication with a single line of code. Also, with the Moralis Web3 Data API, you can quickly fetch any on-chain data. This toolset provides you with everything you need to create killer dapps – from Web3 wallets to Web3 games and everything in between. So, in case you haven’t done so yet, create your free Moralis account and start BUIDLing!
Web3 Libraries – Summary
In today’s article, you had a chance to meet all the leading Web3 libraries. As such, you now know that web3j, Web3.js, Web3.py, and ethers.js stand out. Along the way, we also answered, “what is ethers.js?” This is also where you discovered that ethers.js is arguably the most popular Web3 library. Then, you had an opportunity to take on our example, where we compared ethers.js with the Moralis Streams API. Consequently, you now know what the best method is when you want to listen to on-chain events.
Moving forward, you can focus on tackling your own dapp ideas using the knowledge and skills obtained herein. However, if you need more practice and guidance, or want to spark some creative thinking, make sure to use Moralis’ resources. The Moralis documentation, our Web3 development video tutorials, and our crypto blog are all you need to become a Web3 developer for free. There, you can also find other practical tools, such as a gwei to ether converter and a reliable crypto faucet. Of course, you can also take a more professional approach to your blockchain development education by enrolling in Moralis Academy. In that case, make sure to start with blockchain and Bitcoin fundamentals.