DEV Community

hideckies
hideckies

Posted on • Edited on • Originally published at blog.hdks.org

Ethers.js Cheat Sheet

ethers.js is a library that interact with Ethereum Blockchain.

It is a very useful library but the official documentation was a little hard to read for me so I would like to summarize it for easy reference. (Focusing on what will be used often.)

*They are arranged in alphabetical order.


Accounts

Gets a list of accounts

const accounts = await provider.listAccounts();
Enter fullscreen mode Exit fullscreen mode

Example:

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

const accounts = await provider.listAccounts();
console.log(accounts[0]);
Enter fullscreen mode Exit fullscreen mode

Balance

Gets a blanace of address

const balance = await provider.getBalance(`address`);
Enter fullscreen mode Exit fullscreen mode

Example:

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

const address = "0x28d3...";

const balance = await provider.getBalance(address);

console.log(`The ${address} balance: ${balance.toString()}`);
Enter fullscreen mode Exit fullscreen mode

Connect (MetaMask)

Connects to Ethereum with MetaMask

const provider = new ethers.provider.Web3Provider(window.ethereum);
Enter fullscreen mode Exit fullscreen mode

Connect (RPC)

Connects to Ethereum with RPC

const provider = new ethers.provider.JsonRpcProvider(`url`);
Enter fullscreen mode Exit fullscreen mode

url for example:

Platform URL
Alchemy https://<network>.alchemyapi.io/v2/YOUR-API-KEY
Infura https://<network>.infura.io/v3/YOUR-PROJECT-ID

Contract

Create a contract instance by signer.

It does not work if the user does not have a wallet or is not connected.

const contract = new ethers.Contract(`address`, `abi`, `signer`);
Enter fullscreen mode Exit fullscreen mode

Example:

import Artifact from './Contract.json';

// Connect web3
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

const contractAddress = "0x9fE4...";

const contract = new ethers.Contract(
    contractAddress,
    Artifact.abi,
    signer
);

// Call a state-change method
const userAddress = "0x28d3...";
const dai = ethers.utils.parseUnits("1.0", 18);
await contract.transfer(userAddress, dai);
Enter fullscreen mode Exit fullscreen mode

Contract (Read-Only)

Create a contract instance by provider.

It can call Read-Only methods only. Instead, it also works if the user doesn't have a wallet or isn't connected.

const contract = new ethers.Contract(`address`, `abi`, `provider`);
Enter fullscreen mode Exit fullscreen mode

Example:

import Artifact from './Contract.json';

// For example here, interact with Alchemy JSON-RPC
const provider = new ethers.providers.JsonRpcProvider("https://eth-mainnet.alchemyapi.io/v2/<YOUR-API-KEY>");

const contractAddress = "0x9fE4...";

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

// Call a getter method
const contractName = await contract.name();
console.log(`Contract name is ${contractName}`);
Enter fullscreen mode Exit fullscreen mode

Contract Event Listener

Listens events emitted in contract.

contract.on(`event`, `listener`);
Enter fullscreen mode Exit fullscreen mode

Example:

contract.on("TransferedFrom", (from, to) => {
    console.log(`Token transfered from ${from} to ${to}`);
});

contract.on("Minted", (tokenId) => {
    console.log(`Token #${tokenId} minted`);
});

Enter fullscreen mode Exit fullscreen mode

Convert (Ether -> Wei)

Returns BigNumber.

const wei = ethers.utils.parseEther(`ETH`);
Enter fullscreen mode Exit fullscreen mode

Example:

const weiBigNumber = ethers.utils.parseEther("0.2");
const wei = weiBigNumber.toString();

console.log("wei: ", wei);
Enter fullscreen mode Exit fullscreen mode

Convert (Wei -> Ether)

Returns string.

const ether = ethers.utils.formatEther(`wei`);
Enter fullscreen mode Exit fullscreen mode

Example:

const address = "0x28d319067E209fa43Ef46bF54343Dae4CEDd3824";
const balanceBigNumber = await ethers.providers.getBalance(address);

const balance = ethers.utils.formatEther(balanceBigNumber.toString());
console.log(`user balance: ${balance} Ether`);
Enter fullscreen mode Exit fullscreen mode

Install

npm install ethers
Enter fullscreen mode Exit fullscreen mode

Import

for CommonJS

const { ethers } = require('ethers');
Enter fullscreen mode Exit fullscreen mode

for ES Modules

import { ethers } from 'ethers';
Enter fullscreen mode Exit fullscreen mode

Network & Chain ID

Gets a connecting network and chain ID.

const network = await provider.getNetwork();
const chainId = network.chainId;
Enter fullscreen mode Exit fullscreen mode

Example:

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

const network = await provider.getNetwork();
const chainId = network.chainId;
Enter fullscreen mode Exit fullscreen mode

Chain ID List for example:

Chain ID Network
1 Mainnet
3 Ropsten
4 Rinkeby
5 Goerli
10 Optimism
42 Kovan
56 BSC
137 Polygon
42161 Arbitrum One
43114 Avalanche

Top comments (15)

Collapse
 
mmajudith profile image
mmajudith

Nice write up. Please did you know how i can validate erc721 token ID input field with ether.js?

Collapse
 
hideckies profile image
hideckies

Thank you. Um...I've never done that so I don't know, sorry.

Collapse
 
nazareth profile image
َ

Awesome. Btw, for ES Modules -> import { ethers } from 'ethers';
You have a typo there.

Collapse
 
hideckies profile image
hideckies

Oh thank you. Fixed;)

Collapse
 
ekamkohli profile image
ekamkohli • Edited

In Convert (Wei -> Ether), const balance = ethers.utils.formatEther(balance.toString());
Please change balance.toString() to balanceBigNumber.toString()

Thanks for providing this cheatsheet.

Collapse
 
hideckies profile image
hideckies

Oh I was careless. Thank you so much!

Collapse
 
baqirnekfar profile image
NekfarBaqir • Edited

I have connected with window.ethereum.request function and now I have a disconnect button, how can I do that?

Collapse
 
0xrajkumar profile image
Rajkumar

How we can write using rpc only ?

Collapse
 
hideckies profile image
hideckies

If you implement only with RPC, probably can't change states on blockchain.

Collapse
 
0xrajkumar profile image
Rajkumar

OK

Collapse
 
0xrajkumar profile image
Rajkumar

We can but we need private to do that, btw thanks

Collapse
 
kelviniot profile image
KelvinIOT

This is soo comprehensive & helpful, thanks for sharing man.... Also is it possible to call a contract in ethersJS without passing in the provider?

Collapse
 
hideckies profile image
hideckies

Thanks! You can do this by connecting from your wallet and passing the signer in parameter when initializing a new contract.

Collapse
 
dawsonbotsford profile image
Daws Bot

Strong list! To help folks even further, let's list all the popular chains you might need to connect to with their ID's:

Polygon: 137
Arbitrum One: 42161
Optimism: 10
Avalanche: 43114
BSC: 56

Collapse
 
hideckies profile image
hideckies

Thanks! Added them;)