See More

What Is Ethers.js? A Deep Dive Into Ethereum’s JavaScript Library

10 mins
Updated by May Woods
Join our Trading Community on Telegram

If you are eyeing Ether (ETH) over other crypto players, you should take a moment to understand Ethereum from a more technical perspective. A blockchain protocol known for its toolkit, smart contracts, and code-aligned ecosystem, Ethereum relies heavily on ethers.js — a Javascript library — to give its developer-centric approach the required potency.

While ethers.js isn’t the only Ethereum native JavaScript library, it is the better option for smaller DApps. In this guide, we delve deeper into the aspects of ethers.js, helping you make sense of this technical concept.

Unpacking ethers.js

ethers.js is a JavaScript library — a set of pre-written code that automates several functions. Using JavaScript libraries for development can minimize the effort of code writing. The process becomes more user-friendly, and for DApp developers, these libraries help offer basic blockchain-specific functionalities as bundles.

Ethers.js and the development cycle: BIC
Ethers.js and the development cycle: BeInCrypto

Here is the GitHub repository for the library.

What are JavaScript libraries?

Before we delve deeper into ethers.js, let’s take a closer look at JavaScript libraries. These libraries are pre-written sets of JavaScript code that can automate specific common tasks. Using libraries like ethers.js can speed up the DApp creation process and even speed up other blockchain-specific interactions.

Why do we need JavaScript libraries in Ethereum?

Ethereum has evolved into a decentralized software development platform. From smart contracts to DeFi applications to DApps, coding is integral to the Ethereum ecosystem. That is exactly why Ethereum-tailored JavaScript libraries like ethers.js exist. Using these libraries, developers can connect to the network, deploy and interact with smart contracts, and easily manage blockchain data.

Did you know? Ethers.js isn’t the only known Ethereum Javascript library. Another prominent one is Web3.js, founded by the Ethereum Foundation. Web3.js is known for its comprehensive collection of documentation and is meant for the more complex DApps.

Why is ethers.js important?

As mentioned earlier, ethers.js is aimed at developers engaging with the Ethereum blockchain. As for the importance, this Richard Moore-developed library, marketed under the name “Ethers,” is useful for the following jobs:

  1. Simplifying several Ethereum transactions
  2. Offers access to comprehensive documentation and resources
  3. Facilitating DApp development
Ethers.js ecosystem and the roles it can assume:BIC
Ethers.js ecosystem and the roles it can assume: BeInCrypto

Here is a quick example of the code snippet used to fetch the current balance of an Ethereum account. Let us read the code first and understand how ethers.js makes life easier:

const { ethers } = require(‘ethers’);

// Connect to the Ethereum network

const provider = new ethers.providers.JsonRpcProvider(‘https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY’);

// Specify the account address

const accountAddress = ‘0xABC123…’;

// Fetch and display the balance

provider.getBalance(accountAddress).then((balance) => {

    // Convert the balance from Wei to Ether

    const balanceInEther = ethers.utils.formatEther(balance);

    console.log(`Balance: ${balanceInEther} ETH`);

});

In this example, you can clearly see how the command — ethers.providers.JsonRpcProvider — invokes an Infura endpoint, and getBalance fetches the balance. You do not need to deal directly with Ethereum’s JSON RPC or the Remote Procedure Call. In this case, you can think of ethers.js as a translator that makes Ethereum easier and more familiar to you. 

Still unsure as to the significance of ethers.js? Here is a quick analogy.

Think of ethers.js as an old library card. Remember those cards had catalogs, allowing you to find the right book by locating the aisle and then the shelf number? This is what ethers.js aims to do. It simplifies and organizes Ethereum’s massive capabilities, allowing developers to find exactly what they need. 

All Ethers.js versions explained

Over the years, several Ethers.js versions have surfaced, each introducing a new feature or a bug fix. Also, the versioning follows the standard semantics, like v1.2.3, where the first number signifies the major and the second and third numbers denote minor and patch. We shall only consider the major version upgrades for now — changes that might not be backward compatible. 

  • Version 1.x (Legacy): This was the initial release, followed by features related to transaction signing, wallet management, and more.
  • Version 2.x (Ethers Wallet): Focussed on wallet utilities and features, including secure storage of private keys.
  • Version 3.x (Ethers provider): Introduced abstractions for connecting to Ethereum nodes. Different types of players were accommodated, including Infura, WebSockets, and more.
  • Version 4.x (Ethers contract): Smart contract-led properties were expanded upon, with more utilities for encoding and decoding data, event filters, and more.
  • Version 5.x: Offers a modular architecture, enhanced support for ENS, comprehensive error handling, and more. 
  • Version 6.x: Inclusion of ES6 features, BigInt introduction, overloading accessibility, and more. 
Ethers.js architecture and components: BIC
Ethers.js architecture and components: BeInCrypto

You can find more details about each version by viewing Ethers.js’ original documentation.

Redbelly Intern, Builder: X

Getting started with ethers.js

Before you plan to leverage the potential of ethers.js, it is necessary to know at what stage of DApp or smart contract development it is invoked. Here is a quick breakdown for those who need to know and understand these elements from scratch.

“Web3.js is beginner-friendly and more concise than ethers.js.

Ethers.js, on the other hand, gives more options and is new; it is a little bit more complex than Web3.js.”


degenBRo, blockchain developer and the Founder of Solidity Finance: As told to BeInCrypto

To get started, you first need to open the computer and set up the dev environment. This includes Node.js and the Integrated Development Environment. Note that JavaScript usually runs on the browser, but with Node.js, the same can be run on the computer. It is the Node.js runtime environment that installs Javascript libraries like the ethers.js.

As for IDE, which a software developer needs to test, you can consider VS Code, Sublime Text, or anything else.

Installing ethers.js support

The next step is to install Ethers, the library hosting ethers.js. 

npm install ethers

Then, you need to use Ethers to connect to the Ethereum wallet, as interaction with the blockchain will require this step for validating credentials. You can use the installed Ethers library for this. Here is the sample command:

/Related

More Articles

const { ethers } = require(‘ethers’);

// Connect to the MetaMask wallet

const provider = new ethers.providers.Web3Provider(window.ethereum);

Once done, you can use the IDE to write down the solidity code and create smart contracts for DApps. Ethers.js will be used to deploy the same. You can even test the DApp or the contract locally, using environments like Truffle and Hardhat. Then, you deploy the contracts onto the Ethereum network, for which ethers.js is needed.

const contract = new ethers.ContractFactory(abi, bytecode, signer);

const deployedContract = await contract.deploy();

For the unversed abi, Bytecode, Signer are necessary terms for seamless smart contract development. Abi or the application binary interface is more like the label that helps the network recognize your smart contracts. Bytecode is the compiled or rather the network-ready version of the smart contract and the signer is the signature-generating entity.

Ethers.js for the front-end

Once the smart contract is deployed, you need to build the front end or the user interface of the DApp. For this, you can use Angular or React. You can even integrate Ethers.js within the front end to ensure that it can interact with Ethereum smart contracts. Here is the sample code for the same:

const provider = new ethers.providers.Web3Provider(window.ethereum);

const contract = new ethers.Contract(contractAddress, contractABI, provider.getSigner());

After this, you need to test the DApp on a testnet, say the likes of Rinkeby or Ropsten. Once you are happy, you can launch the DApp on the mainnet. Notice how many times throughout the process you need to interact with Ethers or ethers.js. 

Core features

Ethers.js comes across as a comprehensive Ethereum library. Here are some of the exclusive offerings that can make the lives of developers easy:

Providers

Ethers.js providers act as bridges between the Ethereum network and the DApp you are working on. This involves simplifying blockchain data querying and also helps broadcasting transactions. Infura is one of the providers that Ethers.js uses.

Here is the sample code for the same:

const { ethers } = require(‘ethers’);

// Connect using Infura

const provider = new ethers.providers.JsonRpcProvider(‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’);

// Check the current block number

provider.getBlockNumber().then((blockNumber) => {

    console.log(“Current block number:”, blockNumber);

});

Wallets

Ethers.js lets you manage wallets, allowing you to create new accounts, import existing accounts, securely manage private keys for signing transactions, and do more. 

Contracts

This component of Ethers.js’ existence supports object instantiation. This makes it easier to call specific contract functions, more like native Javascript methods. 

Ethers.js and smart contract interaction: BeInCrypto
Ethers.js and smart contract interaction: BeInCrypto

ENS Integration

Ethers.js can resolve ENS names to their Ethereum addresses and vice versa. This feature reduces the risk of errors. 

Here is a sample code snippet for this:

const { ethers } = require(‘ethers’);

const provider = new ethers.providers.JsonRpcProvider(‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’);

const ensName = ‘alice.eth’;

provider.resolveName(ensName).then((address) => {

    console.log(`${ensName} is resolved to ${address}`);

});

Besides the mentioned features, Ethers.js also boasts the following aspects or features, helping developers with Ethereum-specific direct access:

  • Signers
  • Utilities
  • Event listeners and filters (meant for activating real-time responses to blockchain actions)
  • Transactions
  • Multicall support
  • TypeScript support (meant for improving code reliability and overall developer experience)

A handful of perks of using Ethers.js:

How crypto publications can leverage Ethers.js

Media publications like BeInCrypto can leverage Ethers.js to create advanced and resourceful web3 tools from scratch. This way, it becomes possible to use blockchain or, rather, Ethereum-powered features to enhance usability. Here are the options that one can consider:

Data feeds

Ethers.js features can be used to integrate actual real-time crypto data feeds, like network statistics, gas fees, and more, to keep articles and resources evergreen. Here is a sample code for fetching the latest block number, say for Bitcoin, to track halving in real time.

const { ethers } = require(‘ethers’);

const provider = new ethers.providers.JsonRpcProvider(‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’);

provider.getBlockNumber().then((blockNumber) => {

    console.log(“Current block number:”, blockNumber);

    // Integrate this data into your publication’s platform for a real-time data feed

});

Interactive content

Publications can create bits of interactive content, allowing users to interact directly with smart contracts, participate in polls, or even play small games if needed.

Here is a sample code snippet to retrieve a milestone-specific greeting from a smart contract:

const { ethers } = require(‘ethers’);

const provider = new ethers.providers.Web3Provider(window.ethereum);

const contractAddress = ‘0x…’;

const contractABI = [

    “function getGreeting() view returns (string)”

];

const contract = new ethers.Contract(contractAddress, contractABI, provider);

async function displayGreeting() {

    const greeting = await contract.getGreeting();

    document.getElementById(‘greeting’).innerText = greeting;

}

A real-world example of how Ethers.js is deployed:

Decentralized publishing

Media publications can also consider decentralized publishing, where a remnant of an article is published on the blockchain network. This can help with censorship resistance and even content integrity. 

Here is a sample code where the article hash is stored online as the proof of publication:

const { ethers } = require(‘ethers’);

const wallet = new ethers.Wallet(‘YOUR_PRIVATE_KEY’, provider);

const contentHash = ethers.utils.id(“Article content here”);

const tx = await wallet.sendTransaction({

    to: ‘0xSomeStorageContractAddress’,

    data: contentHash // Assuming the contract accepts and stores this data

});

console.log(“Transaction hash (proof of publication):”, tx.hash);

These are only a handful of use cases for media publications. But there are other sectors that can leverage the power of ethers.js. These include:

  • Blockchain developers (expected)
  • Financial analysts working with DeFi metrics
  • Game developers
  • Content creators
  • Supply chain managers

And more.

Real-world applications of Ethers.js

Besides being useful in DeFi, NFT, and gaming projects, there are a few existing DApps that support the usage of Ethers.js. These include the following:

  • Uniswap: Ether.js interacts with Uniswap’s inherent smart contracts for executing trades, adding liquidity, and even querying pool statistics. In this case, DApp developers plan to build tools that interact with Uniswap, such as trading bots, portfolio management tools, and more.
  • Aave: DApp developers and other interested parties can leverage Ether.js functionalities to interact with Aave-specific smart contracts. This way, they can prime the front end for borrowing assets, depositing collateral, and doing more. 

Busting a few Ethers.js myths:

Security considerations

Using Ethers.js comes with a pretty extensive set of security considerations. Here are a few to follow:

  • It is advisable not to hardcode private keys inside the codebase of your application.
  • Every smart contract interaction should be preceded by testing and extensive auditing of the contracts.
  • Whenever you interact with smart contracts, use safe patterns like “call” for read-only tasks.
  • For optimizing ethers.js usage, you might consider request batching. This is where you can batch, say, read-only requests to minimize the number of network calls. It goes without saying that these optimization techniques can make the application highly scalable and cost-efficient.

Here is an example of how it works:

// Pseudocode for batching contract calls with Ethers.js (conceptual example)

const contract = new ethers.Contract(address, abi, provider);

const [value1, value2, value3] = await Promise.all([

    contract.viewFunction1(),

    contract.viewFunction2(),

    contract.viewFunction3()

]);

Ethers.js: a versatile tool

As demonstrated in this guide, Ethers.js is a versatile tool. While we have taken a quick look at its capabilities, the best way to completely understand Ethers.js is to delve deeper into the world of smart contracts, JavaScript, IDEs, DApps, and more. Additionally, joining the Ethereum and Ethers communities can also come in handy.

Frequently asked questions

How can developers use Ethers.js events?

What are the key utilities offered by Ethers.js?

What is the connection between Ethers.js and Web3.js?

Top crypto platforms | April 2024

Trusted

Disclaimer

In line with the Trust Project guidelines, the educational content on this website is offered in good faith and for general information purposes only. BeInCrypto prioritizes providing high-quality information, taking the time to research and create informative content for readers. While partners may reward the company with commissions for placements in articles, these commissions do not influence the unbiased, honest, and helpful content creation process. Any action taken by the reader based on this information is strictly at their own risk. Please note that our Terms and Conditions, Privacy Policy, and Disclaimers have been updated.

Ananda.png
Ananda Banerjee
Ananda Banerjee is a technical copy/content writer specializing in web3, crypto, Blockchain, AI, and SaaS — in a career spanning over 12 years. After completing his M.Tech in Telecommunication engineering from RCCIIT, India, Ananda was quick to pair his technical acumen with content creation in a career that saw him contributing to Towardsdatascience, Hackernoon, Dzone, Elephant Journal, Business2Community, and more. At BIC, Ananda currently contributes long-form content discussing trading,...
READ FULL BIO
Sponsored
Sponsored