A beginer’s guide: Four ways to play with `ethers.js`

Four quick notes on how to set up a playround for ethers.js. web3.js is almost the same.

Quick notes even first time web3 developers with front-end experience can go through in less than an hour.

ethers.js / web3.js is “Ethereum JavaScript API”:

a…


This content originally appeared on DEV Community and was authored by fangjun

Four quick notes on how to set up a playround for ethers.js. web3.js is almost the same.

Quick notes even first time web3 developers with front-end experience can go through in less than an hour.

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

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.formatEther(balance)

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

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

Add mainnet in hardhat.config.ts :

    mainnet: {
      url: process.env.ALCHEMY_URL || "",
    },

Enter hardhat console by running:

yarn hardhat console --network mainnet

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()

3. Write script use ethers.js

Add file playeth.ts and run from command line.

touch playeth.ts

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()

Run playeth.ts script:

node playeth.ts
//blocknumber 14088543
//balance of ethers.eth 0.082826475815887608

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

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

STEP 2: Install ethers

yarn add ethers

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

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 athurize 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.


This content originally appeared on DEV Community and was authored by fangjun


Print Share Comment Cite Upload Translate Updates
APA

fangjun | Sciencx (2022-01-27T17:22:37+00:00) A beginer’s guide: Four ways to play with `ethers.js`. Retrieved from https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/

MLA
" » A beginer’s guide: Four ways to play with `ethers.js`." fangjun | Sciencx - Thursday January 27, 2022, https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/
HARVARD
fangjun | Sciencx Thursday January 27, 2022 » A beginer’s guide: Four ways to play with `ethers.js`., viewed ,<https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/>
VANCOUVER
fangjun | Sciencx - » A beginer’s guide: Four ways to play with `ethers.js`. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/
CHICAGO
" » A beginer’s guide: Four ways to play with `ethers.js`." fangjun | Sciencx - Accessed . https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/
IEEE
" » A beginer’s guide: Four ways to play with `ethers.js`." fangjun | Sciencx [Online]. Available: https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/. [Accessed: ]
rf:citation
» A beginer’s guide: Four ways to play with `ethers.js` | fangjun | Sciencx | https://www.scien.cx/2022/01/27/a-beginers-guide-four-ways-to-play-with-ethers-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.