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
1 | const accounts = await provider.listAccounts(); |
Example:
1 | // Connect web3 |
Balance
Gets a blanace of address
1 | const balance = await provider.getBalance(`address`); |
Example:
1 | // Connect web3 |
Connect (MetaMask)
Connects to Ethereum with MetaMask
1 | const provider = new ethers.providers.Web3Provider(window.ethereum); |
Connect (RPC)
Connects to Ethereum with RPC
1 | const provider = new ethers.providers.JsonRpcProvider(`url`); |
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.
1 | const contract = new ethers.Contract(`address`, `abi`, `signer`); |
Example:
1 | import Artifact from './Contract.json'; |
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.
1 | const contract = new ethers.Contract(`address`, `abi`, `provider`); |
Example:
1 | import Artifact from './Contract.json'; |
Contract Event Listener
Listens events emitted in contract.
1 | contract.on(`event`, `listener`); |
Example:
1 | contract.on("TransferedFrom", (from, to) => { |
Convert (Ether -> Wei)
Returns BigNumber
.
1 | const wei = ethers.utils.parseEther(`ETH`); |
Example:
1 | const weiBigNumber = ethers.utils.parseEther("0.2"); |
Convert (Wei -> Ether)f
Returns string
.
1 | const ether = ethers.utils.formatEther(`wei`); |
1 | const address = "0x28d319067E209fa43Ef46bF54343Dae4CEDd3824"; |
Install
1 | npm install ethers |
Import
for CommonJS
1 | const { ethers } = require('ethers'); |
for ES Modules
1 | import { ethers } from 'ethers'; |
Network & Chain ID
Gets a connecting network and chain ID.
1 | const network = await provider.getNetwork(); |
Example:
1 | // Connect web3 |
Chain ID List for example:
1 — Mainnet
3 — Ropsten
4 — Rinkeby
5 — Goerli
10 — Optimism
42 — Kovan
56 — BSC
137 — Polygon
42161 — Arbitrum One
43114 — Avalanche