Published on

Intro to Ethers.js


Recently, I just jumped into the blockchain world a few months ago. I am not good at solidity. I am more confident with my JavaScript skill, so I find that Ethers.js is familiar and easy to understand when read together with solidity and smart contract.

I also completed this course - Introduction to Ethers.js by Chainshot. I learned so many things then I decided to jot notes about Ethers.js

The official ethers documentation is helpful, but sometimes it isn't easy to read, so I decided to take notes on what I currently use.


yarn add --dev ethers

Connect a wallet.

import { ethers } from 'ethers';
const { Wallet } = ethers;

// create a wallet instance using a private key.
const wallet1 = new Wallet('0x...');

// create a wallet instance using 12 seed phrases.
const wallet2 = Wallet.fromMnemonic('one two three four...');

Connect to Metamask (Provider)

import { ethers } from 'ethers';

// window.ethereum injected by metamask extension.
const provider = new ethers.providers.Web3Provider(window.ethereum);

// MetaMask requires requesting permission to connect users accounts
await provider.send('eth_requestAccounts', []);

// get current account.
const signer = provider.getSigner();

// list accounts
const accounts = await window.ethereum.request({ method: 'eth_accounts' });
const accounts2 = await provider.listAccounts();

Connect to JSON RPC

import { ethers, utils } from 'ethers';

const RPC_URL = process.env.YOUR_PRC_URL;

const provider = new ethers.providers.JsonRpcProvider(RPC_URL);

// Query data on blockchain
// Get Balance
const balance = await provider.getBalance('0xchai.eth');
const balanceInEth = utils.formatEther(balance);
// 0.041 eth

Send a transaction

const { ethers } from 'ethers';
const signer = await provider.getSigner();

const tx = signer.sendTransaction({
    to: "0xchai.eth",
    value: ethers.utils.parseEther("0.1")

For RPC Node Privder I used Alchemy and Infura depend on a network.

Connect a Contract.

const { ethers } from 'ethers';

const contractAddress = '';
const contractAbi = 'ABI_FILE';

const RPC_URL = process.env.YOUR_PRC_URL;
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);

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

// Option 1: Connect to signer for permission to send a transaction save to blockchain
const signer = await provider.getSigner();
const contractWithSigner = contract.connect(signer);

// Option 2: using private key wallet.
const wallet = new ethers.Wallet(process.env.DEPLOYER_PRIVATE_KEY, provider);

const contractWithWallet = new ethers.Contract(contractAddress, contractAbi, wallet);

Connect a Contract (Hardhat)

yarn add --dev hardhat @nomiclabs/hardhat-ethers
// no need, if you run with npx hardhat environment. `hre` will be global variable.
const hre = require('hardhat');

// signer with hardhat (first account in hardhat.config.js)
const [signer] = await hre.ethers.getSigners();

// signer with ethers.js
const signer = await ethers.getSigner();

const contract = await hre.ethers.getContractAt('ContractName', 'address', signer);

Listening to the event.

const contract = await hre.ethers.getContractAt('contractName', 'address', 'signer');

contract.on('EventName', (data) => {
  console.log(data); // data including log.

Formatting and Parsing Ether

const { utils, BigNumber } = require('ethers');

const value = BigNumber.from('1000000000000000000');
utils.formatEther(value); // same as formatUnits(value, 'ethers')
// '1.0'
utils.formatUnits(value, 'ether');
// '1.0'

// { BigNumber: "1000000000000000000" }

utils.parseUnits('1.0', 'ether');
// { BigNumber: "1000000000000000000" }

Formatting and Parsing bytes32

const { ethers, utils } = require('ethers');
// const { utils } = ethers; // same as `const { utils } = require('ethers')`

const text = 'This is Chai';
const stringBytes32 = utils.formatBytes32String(text);
// output : 0x5468697320697320436861690000000000000000000000000000000000000000

const bytes32 = '0x5468697320697320436861690000000000000000000000000000000000000000';
const text2 = utils.parseBytes32String(bytes32);
// output: "This is Chai"

I am still learning and hope to learn something new every day.

Happy Coding ❤️