Master Hardhat Console: Debug Smart Contracts Instantly
Learn how to streamline Ethereum smart contract debugging by using Hardhat’s interactive console, covering setup, querying chain state, interacting with deployed contracts, reading and writing functions, and advanced features like manual mining, all with practical code examples to boost development efficiency.
Overview
Hardhat console provides an interactive REPL connected to a local Hardhat network, allowing developers to query state and interact with contracts without writing separate scripts.
Prerequisites
Start a local node and launch the console:
npx hardhat node npx hardhat console --network localhostQuerying Chain State
Accounts
// Get signer objects
const signers = await ethers.getSigners();
console.log("First account:", signers[0].address);Note: getSigners() returns Signer objects that can sign transactions.
Balance
const balanceWei = await ethers.provider.getBalance(signers[0].address);
console.log("Balance (Wei):", balanceWei.toString());
console.log("Balance (Ether):", ethers.formatEther(balanceWei));Block number
const blockNumber = await ethers.provider.getBlockNumber();
console.log("Current block:", blockNumber);Interacting with a Deployed Contract
Assume a contract Greeter has been deployed with scripts/deploy.js and its address is known.
// scripts/deploy.js
async function main() {
const Greeter = await ethers.getContractFactory("Greeter");
const greeter = await Greeter.deploy("Hello, Hardhat!");
await greeter.deployed();
console.log("Greeter deployed to:", greeter.address);
}
main();Attach to the contract
const Greeter = await ethers.getContractFactory("Greeter");
const greeter = await Greeter.attach("0x5FbDB2315678afecb367f032d93F642f64180aa3");
console.log("Connected to Greeter at:", greeter.address);Read‑only call
const current = await greeter.greet();
console.log("Current greeting:", current);State‑changing call
const tx = await greeter.setGreeting("Hola, Hardhat Console!");
await tx.wait(); // wait for mining
console.log("Greeting updated, tx hash:", tx.hash);After the transaction is mined, read the new value:
const updated = await greeter.greet();
console.log("Updated greeting:", updated);Advanced Console Capabilities
Send ETH directly from the REPL using signer.sendTransaction.
Query past events with contract.queryFilter.
Control block production with Hardhat’s RPC methods such as evm_mine or evm_increaseTime.
Illustrations
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
