Blockchain and Web3 course · Module 5: Wallets & Transactions
Wallets - Your Safe in the Crypt
In this lesson6
Welcome to the Vault of Safes! Atlas here. Today you'll learn to create and manage wallets - your personal safes in the underground city.
Creating a Wallet Programmatically
import { ethers } from "ethers";
// 1. Brand new wallet
const newWallet = ethers.Wallet.createRandom();
console.log("Address:", newWallet.address);
console.log("Private Key:", newWallet.privateKey);
console.log("Mnemonic:", newWallet.mnemonic?.phrase);
// 2. Import from private key
const privateKey = "0x...";
const walletFromKey = new ethers.Wallet(privateKey);
// 3. Import from seed phrase
const mnemonic = "witch collapse practice feed shame open despair creek road again ice least";
const walletFromMnemonic = ethers.Wallet.fromPhrase(mnemonic);
// 4. Connecting to a provider
const provider = new ethers.JsonRpcProvider("https://...");
const connectedWallet = newWallet.connect(provider);HD Wallet - Multiple Addresses from One Phrase
// Creating an HD Wallet
const mnemonic = ethers.Mnemonic.fromPhrase("witch collapse practice...");
const hdNode = ethers.HDNodeWallet.fromMnemonic(mnemonic);
// Address derivation (BIP-44 path: m/44'/60'/0'/0/index)
const wallet0 = hdNode.derivePath("m/44'/60'/0'/0/0");
const wallet1 = hdNode.derivePath("m/44'/60'/0'/0/1");
const wallet2 = hdNode.derivePath("m/44'/60'/0'/0/2");
console.log("Address 0:", wallet0.address);
console.log("Address 1:", wallet1.address);
console.log("Address 2:", wallet2.address);Checking Balance
const provider = new ethers.JsonRpcProvider("https://...");
const address = "0x742d35Cc6634C0532925a3b844Bc9e7595f8fE8c";
// Balance in wei
const balanceWei = await provider.getBalance(address);
console.log("Balance (wei):", balanceWei.toString());
// Balance in ETH
const balanceEth = ethers.formatEther(balanceWei);
console.log("Balance (ETH):", balanceEth);
// Unit conversions
const oneEth = ethers.parseEther("1.0"); // 1 ETH → wei
const oneGwei = ethers.parseUnits("1", "gwei"); // 1 gwei → weiSending Transactions
const wallet = new ethers.Wallet(privateKey, provider);
// Simple ETH transaction
const tx = await wallet.sendTransaction({
to: "0x...",
value: ethers.parseEther("0.1"),
// Optional:
gasLimit: 21000,
maxFeePerGas: ethers.parseUnits("30", "gwei"),
maxPriorityFeePerGas: ethers.parseUnits("2", "gwei"),
});
console.log("TX Hash:", tx.hash);
// Wait for confirmation
const receipt = await tx.wait();
console.log("Confirmed in block:", receipt?.blockNumber);Nonce - Transaction Order
// Get current nonce
const nonce = await provider.getTransactionCount(wallet.address);
console.log("Current nonce:", nonce);
// You can set the nonce manually
const tx = await wallet.sendTransaction({
to: "0x...",
value: ethers.parseEther("0.1"),
nonce: nonce, // manual setting
});Summary
- Creating wallets programmatically
- Import from private key and seed phrase
- HD Wallets - multiple addresses
- Checking balance
- Sending ETH
- Nonce and transaction ordering
Code for this lesson: index.js
// MetaMask detection & connection
// Simulation of window.ethereum
const mockEthereum = {
isMetaMask: true,
selectedAddress: null,
chainId: "0x1",
async request({ method, params }) {
switch (method) {
case "eth_requestAccounts":
this.selectedAddress = "0x742d35Cc6634C0532925a3b844Bc9e7595f1dE3a";
return [this.selectedAddress];
case "eth_accounts":
return this.selectedAddress ? [this.selectedAddress] : [];
case "eth_chainId":
return this.chainId;
case "wallet_switchEthereumChain":
this.chainId = params[0].chainId;
return null;
default:
throw new Error(`Method ${method} not supported`);
}
},
on(event, callback) {
console.log(`Listener registered: ${event}`);
}
};
// Simulation of global window.ethereum
const ethereum = mockEthereum;
async function connectWallet() {
console.log("=== METAMASK CONNECTION ===\n");
// 1. Check if MetaMask is installed
if (!ethereum || !ethereum.isMetaMask) {
console.log("MetaMask is not installed!");
console.log(" Download from: https://metamask.io");
return;
}
console.log("MetaMask detected!");
// 2. Connect (request accounts)
try {
console.log("\nConnecting to MetaMask...");
const accounts = await ethereum.request({
method: "eth_requestAccounts"
});
console.log("Connected!");
console.log(" Address:", accounts[0]);
// 3. Get chain ID
const chainId = await ethereum.request({ method: "eth_chainId" });
console.log(" Chain ID:", parseInt(chainId, 16));
} catch (error) {
if (error.code === 4001) {
console.log("User rejected the connection");
} else {
console.log("Error:", error.message);
}
}
}
connectWallet();
// Event listeners
ethereum.on("accountsChanged", (accounts) => {
console.log("Accounts changed:", accounts);
});
ethereum.on("chainChanged", (chainId) => {
console.log("Chain changed:", chainId);
// Reload recommended
});
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 type of wallet is safest for long-term storage of large amounts of cryptocurrency?
2. What distinguishes a 'hot wallet' from a 'cold wallet'?
These are 2 of 17 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the wallet types from most secure to least secure:
- Vertical ordering
Arrange the steps for installing and configuring MetaMask:
- Code editor
Implement a function that connects to MetaMask and returns the user's address:
- Horizontal ordering
Arrange the correct call to the eth_requestAccounts method:
- Code editor
Implement a function that checks whether MetaMask is available:
- Vertical ordering
Arrange the stages of a blockchain transaction's lifecycle:
- Click in order
Click the buttons in the correct order to create the 'to' parameter in the transaction:
- Horizontal ordering
Arrange the basic parameters of a transaction object:
- Code editor
Implement a function that sends 0.1 ETH to a given address:
- Code editor
Implement a conversion from ETH to Wei using ethers.js:
- Click in order
Click the buttons in the correct order to create the value parameter with a value of 0.1 ETH:
- Code editor
Implement a function that signs a text message:
- Horizontal ordering
Arrange the personal_sign method's parameters in the correct order:
- Code editor
Implement a function that verifies whether a signature was made by the owner of the address:
- Click in order
Click the buttons in the correct order describing the WalletConnect process:
- Vertical ordering
Arrange the steps for switching networks in MetaMask programmatically:
- Code editor
Implement a function that switches to the Polygon network:
- Horizontal ordering
Arrange the parameters required to add a new network:
- Code editor
Implement a function that fetches the recent transactions for an address:
- Code editor
Implement a function that waits for a transaction to be confirmed:
- Click in order
Click the buttons showing the most important wallet security rules:
- Vertical ordering
Arrange the steps for protecting against phishing:
- Code editor
Implement a listener that reacts to a change of the active account:
- Horizontal ordering
Arrange the call that listens for a network change:
Tasks after this lesson
- QuestionWallet Types
- QuestionHot vs Cold Wallet
- Put in orderOrder of Wallet Types by Security
- Put in orderInstalling MetaMask
- Coding taskConnecting a Wallet to a dApp
- QuestionMetaMask API
- Put in orderStructure of the eth_requestAccounts Call
- Coding taskChecking Wallet Connection
- Put in orderTransaction Lifecycle
- QuestionTransaction Parameters
- Click in orderClick the Transaction Parameters
- Put in orderBuilding a Transaction Object
- Coding taskSending an ETH Transaction
- QuestionThe 'data' Field in a Transaction
- Coding taskConverting ETH Values
- QuestionValue Units
- Click in orderClick the value Parameter
- QuestionSigning Messages
- Coding taskSigning Messages - personal_sign
- Put in orderStructure of the personal_sign Call
- Coding taskVerifying a Signature
- QuestionWalletConnect
- Click in orderClick the WalletConnect Steps
- Put in orderSwitching Networks
- Coding taskSwitching the Blockchain Network
- QuestionChain ID
- Put in orderAdding a Custom Network
- Coding taskFetching Transaction History
- QuestionTransaction Status
- Coding taskChecking Transaction Status
- QuestionNumber of Confirmations
- QuestionSeed Phrase (Recovery Phrase)
- Click in orderClick the Security Rules
- Put in orderPhishing Attacks
- QuestionRecognizing Phishing
- Coding taskMonitoring Wallet Events
- QuestionMetaMask Events
- Put in orderStructure of the chainChanged Handler
- QuestionEthereum Address Validation
- QuestionMultisig wallet
- Project to submitProject: Wallet Management System
- QuestionENS (Ethereum Name Service)
- ConversationModule Summary