Blockchain and Web3 course Β· Module 4: ethers.js & viem

Ethers.js - Your Hammer in the Tool Forge

3 min read Β·
In this lesson5

Welcome to the Tool Forge! Atlas here. Today we'll forge your first hammer - ethers.js - the most powerful library for interacting with Ethereum.

What is Ethers.js?

Ethers.js is a JavaScript/TypeScript library for interacting with the Ethereum blockchain. It's like a universal key to all the tunnels and chambers in the Crypt.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    ETHERS.JS ARCHITECTURE                        β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚                                                                  β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”       β”‚
β”‚   β”‚    Your     │────▢│  Provider   │────▢│  Ethereum   β”‚       β”‚
β”‚   β”‚ Application β”‚     β”‚   (Gate)    β”‚     β”‚   Network   β”‚       β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β”‚          β”‚                                                       β”‚
β”‚          β”‚            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                           β”‚
β”‚          └───────────▢│   Signer    β”‚ (signing TXs)             β”‚
β”‚                       β”‚  (Warrior)  β”‚                           β”‚
β”‚                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                           β”‚
β”‚                              β”‚                                   β”‚
β”‚                              β–Ό                                   β”‚
β”‚                       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                           β”‚
β”‚                       β”‚   Wallet    β”‚ (Signer + Provider)       β”‚
β”‚                       β”‚  (Vault)    β”‚                           β”‚
β”‚                       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                           β”‚
β”‚                                                                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Installation

# npm
npm install ethers

# yarn
yarn add ethers

# pnpm
pnpm add ethers

Core Concepts

1. Provider - Gateway to the Network

A Provider is a connection to the Ethereum network (read-only):

import { ethers } from "ethers";

// Connection via public RPC
const provider = new ethers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/YOUR-API-KEY");

// Infura
const infuraProvider = new ethers.InfuraProvider("mainnet", "YOUR-API-KEY");

// Alchemy
const alchemyProvider = new ethers.AlchemyProvider("mainnet", "YOUR-API-KEY");

// For the Sepolia testnet
const sepoliaProvider = new ethers.JsonRpcProvider("https://eth-sepolia.g.alchemy.com/v2/YOUR-API-KEY");

2. Signer - Warrior with a Seal

A Signer can sign transactions:

// Signer with a private key
const privateKey = "0x...";
const signer = new ethers.Wallet(privateKey, provider);

// Signer's address
console.log("Address:", signer.address);

3. Wallet - Vault (Signer + Provider)

A Wallet is a combination of Signer + Provider:

// Creating a new wallet
const newWallet = ethers.Wallet.createRandom();
console.log("Address:", newWallet.address);
console.log("Private Key:", newWallet.privateKey);
console.log("Mnemonic:", newWallet.mnemonic.phrase);

// Import from private key
const wallet = new ethers.Wallet(privateKey, provider);

// Import from mnemonic
const walletFromMnemonic = ethers.Wallet.fromPhrase("word1 word2 word3...", provider);

Basic Operations

Checking balance:

const balance = await provider.getBalance("0x742d35Cc6634C0532925a3b844Bc9e7595f8fE8c");
console.log("Balance:", ethers.formatEther(balance), "ETH");

Fetching block information:

const blockNumber = await provider.getBlockNumber();
const block = await provider.getBlock(blockNumber);
console.log("Block:", block);

Sending ETH:

const tx = await wallet.sendTransaction({
  to: "0x...",
  value: ethers.parseEther("0.1")
});
await tx.wait();
console.log("TX Hash:", tx.hash);

Summary

  • Ethers.js - the main Web3 library
  • Provider - connection to the network (read-only)
  • Signer - transaction signing
  • Wallet - Provider + Signer
  • Basic operations: balance, block, send
Code for this lesson: index.js
// ethers.js - basics
// In a real project: import { ethers } from "ethers";

// ethers.js simulation
const ethers = {
  // Formatting
  formatEther: (wei) => (Number(wei) / 1e18).toString(),
  parseEther: (eth) => BigInt(Math.floor(Number(eth) * 1e18)),
  formatUnits: (value, decimals) => (Number(value) / Math.pow(10, decimals)).toString(),
  parseUnits: (value, decimals) => BigInt(Math.floor(Number(value) * Math.pow(10, decimals))),

  // Addresses
  isAddress: (address) => /^0x[a-fA-F0-9]{40}$/.test(address),
  getAddress: (address) => {
    if (!ethers.isAddress(address)) throw new Error("Invalid address");
    return address.toLowerCase();
  },

  // Utils
  id: (text) => "0x" + Array.from(text).reduce((h, c) =>
    ((h << 5) - h + c.charCodeAt(0)) & 0xffffffff, 0
  ).toString(16).padStart(64, '0'),

  keccak256: (data) => ethers.id(data)
};

console.log("=== ETHERS.JS BASICS ===\n");

// Formatting
console.log("Formatting:");
const weiAmount = "1500000000000000000"; // 1.5 ETH
console.log(`  Wei: ${weiAmount}`);
console.log(`  ETH: ${ethers.formatEther(weiAmount)}`);

const ethAmount = "2.5";
console.log(`\n  ETH: ${ethAmount}`);
console.log(`  Wei: ${ethers.parseEther(ethAmount).toString()}`);

// Tokens (USDC has 6 decimals)
console.log("\nTokens (USDC, 6 decimals):");
const usdcAmount = "1000000"; // 1 USDC
console.log(`  Raw: ${usdcAmount}`);
console.log(`  Formatted: ${ethers.formatUnits(usdcAmount, 6)} USDC`);

// Addresses
console.log("\nAddresses:");
const addr = "0x742d35Cc6634C0532925a3b844Bc9e7595f1dE3a";
console.log(`  Address: ${addr}`);
console.log(`  isAddress: ${ethers.isAddress(addr)}`);
console.log(`  Checksummed: ${ethers.getAddress(addr)}`);

// Keccak256
console.log("\nKeccak256:");
console.log(`  keccak256("hello"): ${ethers.keccak256("hello")}`);

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which command correctly installs ethers.js in a project?

  2. 2. What is the main role of Provider in ethers.js?

These are 2 of 18 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps for creating a connection to the Ethereum network using ethers.js:

  • Code editor

    Implement a network connection via Infura or Alchemy

  • Click in order

    Arrange the correct import of the ethers.js library

  • Horizontal ordering

    Arrange the correct order for creating a JsonRpcProvider:

  • Code editor

    Implement a function that reads an account's balance

  • Code editor

    Create a Wallet and connect it to the network

  • Vertical ordering

    Arrange the Ethereum units from smallest to largest:

  • Code editor

    Implement unit conversions

  • Click in order

    Arrange the correct parseEther call for 1 ETH

  • Vertical ordering

    Arrange the steps for sending an ETH transaction:

  • Code editor

    Implement sending ETH

  • Horizontal ordering

    Arrange the elements needed to create a contract instance:

  • Code editor

    Implement reading a token balance

  • Code editor

    Implement an ERC20 token transfer

  • Click in order

    Arrange the correct listener for the Transfer event

  • Code editor

    Implement a listener for the Transfer event

  • Vertical ordering

    Arrange the steps for querying past events:

  • Code editor

    Implement createPublicClient

  • Horizontal ordering

    What is needed to create a Wallet Client in viem?

  • Code editor

    Implement getBalance in viem

  • Vertical ordering

    Arrange the structure for error handling in a transaction:

  • Click in order

    Arrange the condition that checks for an insufficient funds error

  • Horizontal ordering

    Arrange the Ethereum address validation function:

  1. QuestionInstalling ethers.js
  2. QuestionThe Role of Provider in ethers.js
  3. QuestionJsonRpcProvider
  4. QuestionDifference Between Provider and Signer
  5. Put in orderCreating a Provider
  6. Coding taskBasic Provider
  7. Click in orderImporting ethers.js
  8. Put in orderJsonRpcProvider Syntax
  9. Coding taskReading the Balance
  10. QuestionProvider Methods
  11. QuestionCreating a Wallet
  12. Coding taskWallet with a Private Key
  13. Put in orderConverting ETH Units
  14. QuestionparseEther
  15. Coding taskUnit Conversion
  16. Click in orderparseEther Syntax
  17. QuestionSending Transactions
  18. Put in orderTransaction Structure
  19. Coding taskSending ETH
  20. QuestionWhat is ABI?
  21. Put in orderCreating a Contract Instance
  22. Coding taskReading from a Contract
  23. QuestionRead vs Write Functions
  24. Coding taskWriting to a Contract
  25. QuestionListening for Events
  26. Click in orderListening Syntax
  27. Coding taskEvent Listener
  28. Put in orderQuerying Historical Events
  29. QuestionIntroduction to viem
  30. QuestionClient in viem
  31. Coding taskCreating a Public Client
  32. Put in orderWallet Client in viem
  33. Coding taskReading the Balance in viem
  34. QuestionError Handling
  35. Put in orderTry-Catch in Transactions
  36. Click in orderError Types
  37. QuestionComparing the Libraries
  38. QuestionestimateGas
  39. Put in orderAddress Validation
  40. QuestionSigning Messages
  41. Project to submitFinal Project
  42. QuestionBest practices
  43. ConversationCompleting the Lab