Godwin Alexander Ekainu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Comparison of Libraries: Web3js vs Ethersjs 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 grown to be 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 have knowledge of is JavaScript, wouldn't it be easier that you can 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 has even 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. What makes it different is how it manages keys and interacts with the blockchain. 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. Ethers.js has over 10,000 test cases. - License: Ethers.js is licensed under the MIT license, which allows for free use and modification. However, if you are using Ethers.js as a library and linking 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 it is 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. ```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) } ``` From the code above, 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. #### [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. ## What is Web3.js [Web3.js](https://web3js.readthedocs.io/en/v1.8.1/) is also a popular JavaScript-based library that connects 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 itself. This means web3.js 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 performance of the website. #### Flexibility Because of how keys are handled in Ethers.js through separation of concern, which allows developers to handle storing and management of 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 what is used to connect the to 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 session, 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.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully