Ethers.js — interacting with the Ethereum Blockchain

Lim Yee Han
2 min readNov 6, 2022

--

In this article, I would like to consolidate my understanding of Ethers.js, a commonly used library to interact with the Ethereum Blockchain.

Core components in Ethers.js

Source: Ethers.js — https://docs.ethers.io/v5/getting-started/

There are 3 main components in the Ether.js library:

  1. Provider — Abstraction for connecting to the Ethereum Network
  2. Signer/Wallet— Abstraction to authorize transactions (with the help of private keys)
  3. Contract — Abstraction of a smart contract deployed on the Ethereum Network

Provider vs Signers

If you are only reading data, use a provider. If you need to make transactions, or sign things, use a Signer.

Providers

There are 2 kinds of providers a developer could make use of:

  1. 3rd Party Node Providers (e.g. Alchemy, Infura)
const jsonRpcProvider = new ethers.providers.JsonRpcProvider("RPC_LINK")

2. Metamask

window.ethereum — Returns a Web3 provider injected by metamask if metamask is installed in browser

const web3Provider = new ethers.providers.Web3Provider(window.ethereum)

MetaMask requires permission to connect to users accounts

await web3Provider.send('eth_requestAccounts', [])

If account is not locked, no pop-ups will be shown. However, if account is locked:

Pop up prompting users to log in to metamask

Signers

Signers are generally needed to approve transactions that will modify data on-chain. If the operation is read-only, there is no need for a signer.

  1. Create wallets from node provider
const wallet = new ethers.Wallet(PRIVATE_KEY, jsonRpcProvider);

* Wallets are signers with private keys

2. Get signer from metamask

const web3signer = web3Provider.getSigner()

Common signer methods:

  1. getAddress()
  2. getBalance — usually followed by ethers.utils.formatEther(signer.getBalance()))

Contract

  1. Create abstraction of contract with wallet
const contract = new ethers.Contract(CONTRACT_ADDRESS, contract.abi, wallet);

2. Create abstraction of contract with web3signer

const contract = new ethers.Contract(CONTRACT_ADDRESS, contract.abi, web3signer)

Final Words

In essence, Ethers.js is a convenient tool to connect and interact with the Ethereum network. The wallet signers are used when Ethers.js knows the private keys directly. In the event it does not know the private keys, Ethers.js will request a signature from metamask (in the form of a pop-up), in order to sign transactions.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response