Comparing Blockchain Libraries: Web3.js vs. Ethers.js
Tags: blockchain, web3, ethers
Published: 2023-03-15 01:03:56


by [Godwin Alexander](https://blog.openreplay.com/authors/godwin-alexander)





Every programmable blockchain has a set of SDKs or libraries that aid in connecting and communicating with the particular blockchain. Most blockchains today depend on the Ethereum network, making them [EVM-compatible](https://ethereum.org/en/developers/docs/evm/). This means if an ETH library is created, it can be used across any EVM-compatible blockchain. However, communication is possible using the JSON-RPC protocol.

In this article, we will be comparing two popular ETH libraries. You get to learn the differences between them, their pros and cons. This can also help you as a chief technology officer (CTO) / Team leader decide what library to use in future projects.

## JavaScript for Blockchain

Since the inception of JavaScript by Brendan Eich in 1995, it has become the most used programming language on the internet to build many tools in use today. According to [Statista](https://www.statista.com/statistics/793628/worldwide-developer-survey-most-used-languages/), the most used language amongst software developers is JavaScript. 

Imagine you need to solve a particular problem, and the only language you know of is JavaScript. Wouldn't it be easier if you could use JavaScript to solve this problem rather than learning a new advanced language? Many developers have faced this roadblock and found ways to build dApps with JavaScript by building SDKs/libraries that can connect to the blockchain through providers. This has, however, reduced the entry level for building in the blockchain space. You do not need to learn an advanced language like Rust and Solidity to build for [Solana](https://solana.com/) or [Ethereum](https://ethereum.org/en/) chain.

Furthermore, lowering the entry level for blockchain development is one of the main roles of JavaScript.

## What is Ethers.js

Since the inception of [ethers.js](https://docs.ethers.org/v5/), it has experienced steady growth and gained popularity as one of the most used JavaScript-based libraries for web3 development among Ethereum developers. 
This tool helps Javascript developers to interact with the Ethereum chain and any Ethereum Virtual Machine (EVM) compatible blockchain.

A Canadian software engineer called Richard Moore created Ethers.js in 2015 as an alternative to web3.js

Ethers.js is known to be lightweight. How it manages keys and interacts with the blockchain makes it different. In ethers.js, two entities handle the above:

-  A wallet that signs transactions with private keys.
- A provider that connects to the blockchain using JSON-RPC URL. Ethers.js checks the state and sends transactions.
### Advantages of Ethers.js

- Library Size: Ethers.js is 88KB when compressed and 284KB uncompressed.


- ENS: ENS is like the DNS in Blockchain. Wherever Ethereum addresses are used, .eth address can be used there too. You can easily set up a domain name without a boilerplate code.

- Test Cases: Ethers.js is well-tested. Richard Moore himself writes a chunk of these test cases, and Ethers.js has over 10,000 test cases.

- License: Ethers.js is licensed under the MIT license, allowing free use and modification. However, if you use Ethers.js as a library and link it to a larger program, the derivative work must be released under the LGPL-3.0 license.
    
- Performance: Considering the small size, it will be a good idea to use it on the front end as it will drastically improve performance.
  
### Drawbacks of Ether.js
- Ethers.js is relatively new, and if you run into issues, finding answers in places like StackOverflow might not be enough.

- Many foundational companies now use Web3.js for their core projects, and if you need to work for such companies, you might need to spend some time learning web3.js.

### Ethers.js Modules

Ethers.js have four (4) modules that are the core of Ethers.js API. 

- [Ethers.Provider](https://docs.ethers.org/v5/api/providers/): To understand what the `Ethers.Provider`  module does, it is important to understand what a  [node](https://www.blockchain-council.org/blockchain/blockchain-nodes/) is. To access the blockchain network, you need a node running on your machine to access it. The node connects to other nodes to check that transactions between people are valid while it stores information about the state of the blockchain. The blockchain is entirely built up or composed of nodes. These nodes are being run by individuals around the world, and this means that there is no central server or single source of truth. This is what makes it decentralized. Think of nodes like the gas for your cars; it won’t start if empty. Nodes can be quite difficult to set up; as a matter of fact, it can take up to a week or more, but providers like [alchemy](https://www.alchemy.com/), [infura](https://www.infura.io/), and [Quicknode](https://www.quicknode.com/) exists. They have the node set up for you, all they need is for you to establish a connection, and you have access to the blockchain.

- [Ethers.Contract](https://docs.ethers.org/v5/api/contract/contract/#Contract--creating): This module is used to deploy and interact with [smart contracts](https://www.ibm.com/topics/smart-contracts#:~:text=Smart%20contracts%20are%20simply%20programs,intermediary's%20involvement%20or%20time%20loss.). It offers the ability ( packed functions) to listen to smart contract events. However, you can use this module to call for information about a smart contract and the functions provided by the smart contract.

- [Ethers.utils](https://docs.ethers.org/v5/api/utils/): This module can help you format data like a wallet’s balance figure and process other user input. In the code below, after getting the address from a wallet, we retrieve the wallet's balance, but since the returned value is outputted in Wei, we use the `.formatEther` to make it more human readable.

```javascript
const accountChangedHandler = async (newAccount) => {
        const address = await newAccount.getAddress();
        setDefaultAccount(address);
        const balance = await newAccount.getBalance()
        setUserBalance(ethers.utils.formatEther(balance));
        await getuserBalance(address)
    }
```
- [Ethers.Wallet](https://docs.ethers.org/v5/api/signer/#Wallet): This module allows you to connect to an existing address. However, you can sign and create new wallets seamlessly.


<h2>Session Replay for Developers</h2> 
<p><em>
Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data
</em></p>
<img alt="OpenReplay" width="768" height="400" src="https://blog.openreplay.com/assets/overview_Z17Qdyg.png" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em>




## What is Web3.js 

[Web3.js](https://web3js.readthedocs.io/en/v1.8.1/) is a popular JavaScript-based library connecting clients to the blockchain. This library runs and interacts with a local or remote Ethereum node using HTTP, IPC, or Websockets.
Web3.js was released in 2015; it is an open-source library created by the Ethereum foundation. This means it has the largest community, unlike Ethers.js, which was released a year later. The Web3.js library is part of more projects and packages than any other library.

Web3.js, however does not manage keys like Ethers.js. Wallets and providers are not separated; it instead assumes that a local node is connected to the application that handles storing of keys, signing of transactions, and checking for the state on the blockchain.


### Advantages of web3.js

- Ethereum foundation support: The Ethereum foundation developed Web3.js. This means it has many developers contributing to it, and it is only ideal that you are sure to find the solution quicker when issues arise than its counterpart Ethers.js

- Popular: We can use the number of GitHub stars to measure its popularity amongst blockchain developers. According to Github, web3.js has over seventeen thousand (17,000) stars, while Ethers.js have seven thousand (7000) stars. A lot of its popularity is because of first mover impact, which leaves it with a larger community.

### Drawbacks of Web3.js

- Size: Web3.js is relatively larger than Ethers.js, which makes using it in the front end not desirable, as it can reduce the website's performance.
- Flexibility: Because of how keys are handled in Ethers.js through separation of concern, which allows developers to handle storing and managing keys differently, web3.js falls short in this area.
- License: Web3.js works under a more restrictive license where modification is not allowed if not publicly released first.

### Web3.js Modules

- [web3.eth](https://web3js.readthedocs.io/en/v1.8.1/web3-eth.html):  This module is used to connect Ethereum blockchain and smart contracts. It also allows you to subscribe to events on the blockchain.

- [web3.net](https://web3js.readthedocs.io/en/v1.8.1/web3-net.html): This module allows you to interact with the network’s node property.

- [web3.shh](https://web3js.readthedocs.io/en/v1.8.1/web3-shh.html): This module allows communication to the Whisper ( a communication technique dApps use to communicate with each other) protocol. 

- [web3.utils](https://web3js.readthedocs.io/en/v1.8.1/web3-utils.html): This module provides utility functions for Ethereum dApps and other web3 packages.

- [Web3.bzz](https://web3js.readthedocs.io/en/v1.8.1/web3-bzz.html): This module allows you to interact with the [Swarm network](https://swarm-guide.readthedocs.io/en/latest/)

## Comparison of Web3.js and Ethers.js

In this section, we will be comparing these two libraries with the following yardsticks:

- Comparison by code
- Developer experience
- Popularity
- Documentation
- Ease of use
- Performance
- Maintenance


### Comparison by Code

To complete the section, we will need to write a program to send transactions over the blockchain network using both libraries. 
To run this project, you must have the following

-  Node 16 and above.
- metasMask extension ( [create an account](https://metamask.io/) ).
- Node providers like infura ( [Create an account](https://app.infura.io/login) ).

- Send Transactions using Ethers.js: To send transactions over the Ethereum blockchain using ethers.js, copy the following code into your `index.js` file:
```javascript

const ethers = require('ethers');
(async()=>{
    const provider = new ethers.providers.JsonRpcProvider("https://goerli.infura.io/v3/private key");
    const gasPrice = provider.getGasPrice()
    const wallet = ethers.Wallet.fromMnemonic('your Mnemonics');
    const signer = wallet.connect(provider);
    
    const receiver = "0x8dC847Af872947Ac18d5d63fA646EB65d4D99560"
    const trt = {
        from: wallet.address,
        to: receiver,
        value:  ethers.utils.parseUnits('0.001', 'ether'),
        gasPrice: gasPrice
    } 
    const sendTransaction = await signer.sendTransaction(trt);
    console.log(sendTransaction);
})();
```
- Send Transactions using Web3.js: To send transactions over the Ethereum blockchain using Web3.js, copy the following code into your `index.js` file:
```javascript
var Web3 = require('web3');
async function main() {
    const private_key = 'private_key';
    var web3 = new Web3('https://goerli.infura.io/v3/secret key');
    const fromAdress = '0xF63576c9369a87D74d84C49895581a6B1E412D31'; 
    const nonce = await web3.eth.getTransactionCount(fromAdress, 'latest'); 
    const transaction = {
     'to': '0xc419E0B31A46d3071e336E062676352637428500', 
     'value':web3.utils.toWei('0.01', 'ether'),
     'gas': 30000,
     'nonce': nonce,
    };
    const signedTrans = await web3.eth.accounts.signTransaction(transaction, private_key);
 web3.eth.sendSignedTransaction(signedTrans.rawTransaction, function(error, hash) {
    if (!error) {
      console.log("The hash of your transaction is: ", hash);
    } else {
      console.log("❗Something went wrong while submitting your transaction:", error)
    }
   });
   console.log(signedTrans);
}
main();
```

The two code snippets provided above are examples of how to perform a transaction on the Ethereum blockchain using two different libraries: Ethers.js and web3.js.
Here is a detailed comparison of the main differences between the two:

-  Syntax: Ethers.js uses a more object-oriented syntax, while web3.js uses a more functional syntax. This means that in Ethers.js you would create instances of classes and call methods on them, while in web3.js you would call functions on the web3 object.


- Provider: Ethers.js uses a `JsonRpcProvider` class to connect to an   Ethereum node, while web3.js uses the `Web3` class.


-  Wallet: Ethers.js uses the `Wallet` class to create a new wallet or import an existing one, while web3.js uses the `eth.accounts` object to create a new wallet or import an existing one.


- Signing Transactions: In Ethers.js, the `signer` object is used to sign the transaction, while in web3.js, the `eth.accounts.signTransaction` function is used to sign the transaction.


- Sending Transactions: In Ethers.js, the **send transaction** method is called on the `signer` object to send the transaction, while in web3.js, the `web3.eth.sendSignedTransaction` function is used to send the transaction.


- Error Handling:In Ethers.js, you can use try-catch blocks to handle errors, while in web3.js you can use a callback function to handle the errors.


- Gas Price: In Ethers.js the gas price is obtained by calling the `getGasPrice` method on the provider object, while in web3.js it is defined in the transaction object.


- Types of Units: Ethers.js has its own utilities for handling different types of units, such as `ethers.utils.parseUnits`, while web3.js uses its own utilities such as `web3.utils.toWei`.


- Mnemonic: Ethers.js allows creating a wallet from a mnemonic, while web3.js doesn't have this feature.

Overall, both libraries are very similar in terms of functionality, but they have different syntax and utilities. The choice between the two libraries will depend on personal preference, familiarity, and the specific use case.

### Developer Experience

Both libraries have all it takes to create really powerful blockchain applications with few lines of code but Ethers.js is perceived to be cleaner because of the separation of concern between providers and wallets.

However, many foundation projects use web3.js. This makes most available tutorials written in web3.js, which poses a much easy learning curve for new developers. There are more resources and solutions to various issues out there than Ethers.js.


### Popularity

- GitHub: A popular project on GitHub is exactly authentic as you think.
Web3.js tops the chart as the most popular Ethereum JavaScript library with over 16000 starts on GitHub but GitHub stars in my opinion only prove the first mover advantage. On the other hand, ethers.js has over 6k stars on Git Hub.

- NPM Downloads: NPM downloads show how many downloads per week a library gets downloaded by developers for their projects.
Web3.js has over 265000 downloads per week while ethers.js has over 610 downloads per week.
This shows that there is a change or a shift from web3.js to ethers.js.

### Documentation

Both libraries have quite thorough documentation. Either way, ethers.js has an advantage over web3.js thanks to its getting started and play areas.

### Ease of Use

Web3 makes the handling of wallets and providers into a single object but its ethers make reading the blockchain, modifying its state, and managing keys all separate operations.

### Performance

Performance-wise, Ethers.js is a better library. It is suitable for use on front-end apps due to its compact size. Ethers are 248 kB uncompressed and 77 kB compressed.


### Maintenance

Web3.js is being maintained by the Ethereum Foundation but was [awarded to ChainSafe a grant](https://blog.chainsafe.io/chainsafe-receives-grant-from-ef-for-web3js-9e4376f5f36a) in Fall 2020 to rewrite web3.js using the modern Typescript. 
With this development, Chainsafe is dedicated to bringing change to cushion the pain points of using Web3.js.
According to Chainsafe, the areas they plan to make mends to are:

- Make the transition to Typescript efficient in any project.
- Have entirely the library in Typescript.
- Create a flexible and unified version of the library.
- A wide array of features to support eth2.

In conclusion, Chainsafe seems to be committed to doing a good job to maintain web3.js.

However, Ethers.js is maintained by one person Richard Moore, a Canadian software engineer. On GitHub, only 15 contributors are listed.

## What’s Next

Using the libraries for yourself will determine which one works best suites your requirements. There are lots of tutorials on the internet to get you started as soon as possible.

## Conclusion

Both Web3.js and Ethers.js have robust ecosystems that can be utilized to create extremely fast dApps.
It is amazing how much these libraries have expanded and are still in use during my research for this piece. I hope this has given you some insight and made it clearer for you to choose the right tool for the job.


[![newsletter](https://blog.openreplay.com/newsletter_Z1P0UIP.png)](https://newsletter.openreplay.com/)