DEV Community

fangjun
fangjun

Posted on • Updated on

A beginner’s guide: 4 ways to play with `Ethers.js`

Four quick notes on how to set up a playround for Ethers.js. These are how-to guides that even first time web3 developers with front-end experience can go through in less than an hour.web3.js is almost the same.

Ethers.js / web3.js is "Ethereum JavaScript API":

a collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or WebSocket.(via web3.js docs)

To play with Ethers.js, there are tools needed:

  • Console: Node console, Truffle console, Hardhat console
  • Front-end framework: React / Next.js / Web3-React
  • Blockchain Providers: Infura, Alchemy, Metamask Provider
  • Wallet: MetaMask(browser extension wallet)

The relationship between Ethers.js and blockchain is:

  • Ethers.js Javascript API
  • (Provider + RPC Endpoint)
  • Blockchain network

"Provider" explained in Ethers.js docs:

A Provider is an abstraction of a connection to the Ethereum network, providing a concise, consistent interface to standard Ethereum node functionality.

To play with ethereum blockchain with the help of Ethers.js, we need to do it this way:

  1. get Ethers.js instance
  2. connect to provider
  3. play with it

You can find Ethers.js API docs at: https://docs.ethers.io/v5/api/


1. Interactive console - Node console

If you would like to use Node console, run:

mkdir playeth && cd playeth
yarn add ethers
Enter fullscreen mode Exit fullscreen mode

Open Node console by running node.

We will use Alchemy Provider: https://docs.ethers.io/v5/api/providers/api-providers/#AlchemyProvider

//node console
var ethers = require('ethers')
//using AlchemyProvider with shared project ID
const provider =new ethers.providers.AlchemyProvider()

//get current block number
await provider.getBlockNumber()

provider.network
//{
//  name: 'homestead',
//  chainId: 1,
//...
//}

// Get the balance of an account
balance = await provider.getBalance("ethers.eth")
ethers.utils.formatUnits(balance)
Enter fullscreen mode Exit fullscreen mode

2. Interactive console - Hardhat console

As web3 developers write smart contracts and DAPPs, we interact with blockchain using Hardhat or Truffle console. Hardhat and Truffle Suite both provide a development environment.

In hardhat console environment, there is an ether.js instance.

Install hardhat and create a project:

mkdir hheth && cd hheth
yarn hardhat
Enter fullscreen mode Exit fullscreen mode

Select option "Create an advanced sample project that uses TypeScript".

Add mainnet in hardhat.config.ts :

    mainnet: {
      url: process.env.ALCHEMY_URL || "",
    },
Enter fullscreen mode Exit fullscreen mode

Enter hardhat console by running:

yarn hardhat console --network mainnet
Enter fullscreen mode Exit fullscreen mode

In hardhat console, interact with ethereum mainnet with Ethers.js:

ethers.version
//'ethers/5.5.3'

const provider = new ethers.providers.AlchemyProvider()
await provider.getBlockNumber()

Enter fullscreen mode Exit fullscreen mode

3. Write script using Ethers.js

Add file playeth.ts and run from command line.

touch playeth.ts
Enter fullscreen mode Exit fullscreen mode

playeth.ts:

async function main(){

const ethers =require("ethers")
const provider = new ethers.providers.AlchemyProvider()

const blocknumber  =await provider.getBlockNumber()
console.log("blocknumber", blocknumber)

const balance = await provider.getBalance("ethers.eth")
console.log("balance of ethers.eth",ethers.utils.formatEther(balance))
}

main()
Enter fullscreen mode Exit fullscreen mode

Run playeth.ts script:

node playeth.ts
//blocknumber 14088543
//balance of ethers.eth 0.082826475815887608
Enter fullscreen mode Exit fullscreen mode

4. Simple DAPP: Using Ethers.js with Metamask

Ethers.js docs provides a good explanation of MetaMask:

MetaMask, which is a browser extension that provides:

  • A connection to the Ethereum network (a Provider)
  • Holds your private key and can sign things (a Signer)

STEP 1: Init Next.js project

We will using Next.js framework to start a sample project.

yarn create next-app playeth --typescript
cd playeth
yarn dev
Enter fullscreen mode Exit fullscreen mode

You can visit this project at: http://localhost:3000/

STEP 2: Install ethers

yarn add ethers
Enter fullscreen mode Exit fullscreen mode

STEP 3: Write a page

Change index.tsx to:

import type { NextPage } from 'next'
import styles from '../styles/Home.module.css'
import { ethers } from "ethers";
import { useEffect,useState } from 'react';

declare let window: any;
const Home: NextPage = () => {
  const [balance, setBalance] = useState<String | undefined>()
  const [address, setAddress] = useState<String | undefined>()

  useEffect(() => {
    //client side code
    if(!window.ethereum) return

    const provider = new ethers.providers.Web3Provider(window.ethereum)
    provider.getBalance("ethers.eth").then((result)=>{
      setBalance(ethers.utils.formatEther(result))
    })
  })

  function connect(){
    //client side code
    if(!window.ethereum) return

    const provider = new ethers.providers.Web3Provider(window.ethereum)
    window.ethereum.enable().then(()=>{
      const signer = provider.getSigner()
      signer.getAddress().then((result)=>{setAddress(result)})
    })
  }

  return (
    <div>
      <main className={styles.main}>
        <h1>Sample DAPP</h1>
        <h3>Eth balance: {balance}</h3>
        <p><button onClick={connect} >Connect</button></p>
        <h3>Address: {address}</h3>
      </main>

    </div>
  )
}

export default Home
Enter fullscreen mode Exit fullscreen mode

Run yarn dev and in your browser go to: http://localhost:3000/

What does this page do?

  1. This page gets Ethereum provider instance injected by MetaMask by const provider = new ethers.providers.Web3Provider(window.ethereum)

  2. This page will get balance of ethers.eth(address: https://etherscan.io/address/0x643aa0a61eadcc9cc202d1915d942d35d005400c) and show it on the page.

  3. When Connect button is clicked, the page call window.ethereum.enable() to ask MetaMask to enable connect. User needs to authorize connecting in Metamask popup dialog.

  4. When connected, the page gets MetaMask address and displays it.

If this page has been connected to MetaMask, connecting will be done automatically without a popup. You can disconnect it from MetaMask and try clicking Connect button again.

Please note that the above code snippet is just to illustrate the basic flow of using Ethers.js and MetaMask together.

If you would like to know more about MetaMask and its injected ethereum provider, you can refer to MetaMask docs:

MetaMask injects a global API into websites visited by its users at window.ethereum. This API allows websites to request users' Ethereum accounts, read data from blockchains the user is connected to, and suggest that the user sign messages and transactions.


Tutorial List:

1. A Concise Hardhat Tutorial(3 parts)

https://dev.to/yakult/a-concise-hardhat-tutorial-part-1-7eo

2. Understanding Blockchain with Ethers.js(5 parts)

https://dev.to/yakult/01-understanding-blockchain-with-ethersjs-4-tasks-of-basics-and-transfer-5d17

3. Tutorial : build your first DAPP with Remix and Etherscan (7 Tasks)

https://dev.to/yakult/tutorial-build-your-first-dapp-with-remix-and-etherscan-52kf

4. Tutorial: build DApp with Hardhat, React and Ethers.js (6 Tasks)

https://dev.to/yakult/a-tutorial-build-dapp-with-hardhat-react-and-ethersjs-1gmi

5. Tutorial: build DAPP with Web3-React and SWR

https://dev.to/yakult/tutorial-build-dapp-with-web3-react-and-swr-1fb0

6. Tutorial: write upgradeable smart contract (proxy) using OpenZeppelin(7 Tasks)

https://dev.to/yakult/tutorial-write-upgradeable-smart-contract-proxy-contract-with-openzeppelin-1916

7. Tutorial: Build a NFT marketplace DApp like Opensea(5 Tasks)

https://dev.to/yakult/tutorial-build-a-nft-marketplace-dapp-like-opensea-3ng9


If you find this tutorial helpful, follow me at Twitter @fjun99

Top comments (0)