Blockchain and Web3 course Β· Module 4: ethers.js & viem
Ethers.js - Your Hammer in the Tool Forge
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 ethersCore 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. Which command correctly installs ethers.js in a project?
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:
Tasks after this lesson
- QuestionInstalling ethers.js
- QuestionThe Role of Provider in ethers.js
- QuestionJsonRpcProvider
- QuestionDifference Between Provider and Signer
- Put in orderCreating a Provider
- Coding taskBasic Provider
- Click in orderImporting ethers.js
- Put in orderJsonRpcProvider Syntax
- Coding taskReading the Balance
- QuestionProvider Methods
- QuestionCreating a Wallet
- Coding taskWallet with a Private Key
- Put in orderConverting ETH Units
- QuestionparseEther
- Coding taskUnit Conversion
- Click in orderparseEther Syntax
- QuestionSending Transactions
- Put in orderTransaction Structure
- Coding taskSending ETH
- QuestionWhat is ABI?
- Put in orderCreating a Contract Instance
- Coding taskReading from a Contract
- QuestionRead vs Write Functions
- Coding taskWriting to a Contract
- QuestionListening for Events
- Click in orderListening Syntax
- Coding taskEvent Listener
- Put in orderQuerying Historical Events
- QuestionIntroduction to viem
- QuestionClient in viem
- Coding taskCreating a Public Client
- Put in orderWallet Client in viem
- Coding taskReading the Balance in viem
- QuestionError Handling
- Put in orderTry-Catch in Transactions
- Click in orderError Types
- QuestionComparing the Libraries
- QuestionestimateGas
- Put in orderAddress Validation
- QuestionSigning Messages
- Project to submitFinal Project
- QuestionBest practices
- ConversationCompleting the Lab