Day 11 / #100DaysOfWeb3 Ethers.js and Web3.js
I will learn about the two main libraries used to interact with the Ethereum blockchain ecosystem : Ethers.js and Web3.js
What is Ethers.js?
from official documentation
The ethers.js library aims to be a complete and compact library for interacting with the Ethereum Blockchain and its ecosystem. It was originally designed for use with ethers.io and has since expanded into a more general-purpose library.
Features
Keep your private keys in your client, safe and sound
Import and export JSON wallets (Geth, Parity and crowdsale)
Meta-classes create JavaScript objects from any contract ABI, including ABIv2 and Human-Readable ABI
Connect to Ethereum nodes over JSON-RPC, INFURA, Etherscan, Alchemy, Cloudflare or MetaMask.
Complete functionality for all your Ethereum needs
Extensive documentation
Large collection of test cases which are maintained and added to
Fully TypeScript ready, with definition files and full TypeScript source
MIT License (including ALL dependencies); completely open source to do with as you please
What is Web3.js
from official documentation
web3.js is a collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or WebSocket.
Features
Get Ethereum Node Information
Check User’s balance
Transfer Ether from “A” to “B”
Check whether a transaction has been confirmed or not
Web3.js is asynchronous
Interact with ABI, etc...
Difference between Ethers.js and Web3.js
While web3.js provides a single instantiated web3 object with methods for interacting with the blockchain, ethers.js separates the API into two separate roles. The provider, which is an anonymous connection to the ethereum network, and the signer, which can access the private key and sign the transactions. The ethers team intended this separation of concerns to provide more flexibility to developers.
Instantiating provider with MetaMask wallet
web3
const web3 = new Web3(Web3.givenProvider);
ethers
const provider = new ethers.providers.Web3Provider(window.ethereum)
Getting balance of account
web3
const balance = await web3.eth.getBalance("0x0")
ethers (supports ENS!)
const balance = await provider.getBalance("ethers.eth")
Instantiating contract
web3
const myContract = new web3.eth.Contract(ABI, contractAddress);
ethers
const myContract = new ethers.Contract(contractAddress, ABI, provider.getSigner());
Calling contract method
web3
const balance = await myContract.methods.balanceOf("0x0").call()
ethers
const balance = await myContract.balanceOf("ethers.eth")
Finally Ethers.js or Web3.js ?
Ethers.js is a lighter, developer-friendly library with a solid background. it is maintained just by a small group, which limits the development of the library.
On the other hand, Web3.js is the most used Ethereum JavaScript library. While also widely used, it lacks the breadth and depth of Ethers documentation and may not be the best solution for early Web3 developers.