🔨 Hardhat Tutorial

Complete Guide to Ethereum Development

Learn to build, test, and deploy smart contracts

What is Hardhat?

Hardhat is a de-facto local development environment for Ethereum software

npx hardhat compile # Runs the built-in compile task

Prerequisites

Use Windows PowerShell instead of Ubuntu for this tutorial

Required Software:

Download Links:

1Create Project Folders

Create separate folders for JavaScript and TypeScript projects:

# Create directories
mkdir Project_JScript
mkdir Project_TSCript
        

2Install Hardhat

# Install Hardhat locally
npm install --save-dev hardhat

# For specific version
npm install --save-dev "hardhat@^2.12.0"

Initialize Hardhat Project

npx hardhat

This command brings up the project initialization menu:

Tip: To bring back the menu after installation, delete hardhat.config.js and run npx hardhat again

Project Structure

JavaScript Project:

contracts/
scripts/
test/
.gitignore
hardhat.config.js
package.json
README.md
                

TypeScript Project:

contracts/
scripts/
test/
typechain-types/
hardhat.config.ts
tsconfig.json
package.json
               

Configuration Files

JavaScript (hardhat.config.js):

require("@nomicfoundation/hardhat-toolbox");

module.exports = {
  solidity: "0.8.17",
};
        

TypeScript (hardhat.config.ts):

import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

const config: HardhatUserConfig = {
  solidity: "0.8.17",
};

export default config;

Compiling Smart Contracts

npx hardhat compile

Expected Output:

Downloading compiler 0.8.17
Compiled 1 Solidity file successfully
Common Error: Cannot find module '@nomicfoundation/hardhat-toolbox'
Solution: npm install --save-dev @nomicfoundation/hardhat-toolbox

Essential Dependencies

Install these modules for comprehensive smart contract testing:

npm install --save-dev @nomicfoundation/hardhat-toolbox
npm install --save-dev @typechain/hardhat --legacy-peer-deps
npm install --save-dev hardhat-gas-reporter --legacy-peer-deps
npm install --save-dev solidity-coverage --legacy-peer-deps

Testing Commands:

npx hardhat test
npx hardhat test test/my-tests.ts

Setting up Local Hardhat Network

Use a new terminal for network setup
$ npx hardhat node

This starts a standalone local Hardhat network with:

Deploying to Local Network

JavaScript Deployment:

npx hardhat run --network localhost scripts/deploy.js

TypeScript Deployment:

npx hardhat run --network localhost scripts/deploy.ts

Success Output:

Compiled 1 Solidity file successfully
Lock with 1 ETH and unlock timestamp 1706936380 deployed to 0x5FbDB2315678afecb367f032d93F642f64180aa3
        

Testnet Configuration (Goerli)

Update your hardhat.config.js for Goerli deployment:

require("@nomicfoundation/hardhat-toolbox");

const ALCHEMY_API_KEY = "YOUR_ALCHEMY_KEY";
const GOERLI_PRIVATE_KEY = "YOUR_PRIVATE_KEY";

module.exports = {
  solidity: "0.8.17",
  etherscan: {
    apiKey: "YOUR_ETHERSCAN_API_KEY",
  },
  networks: {
    goerli: {
      url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
      accounts: [GOERLI_PRIVATE_KEY]
    }
  }
};
   

Extracting MetaMask Private Key

  1. Click on the identicon in the top right
  2. Select the account you'd like to export
  3. Click on the menu (three dots) → "Account Details"
  4. Click "Export Private Key"
  5. Enter your wallet password and click "Confirm"
  6. Copy and save your private key securely
  7. Click "Done" to close
⚠️ NEVER put real Ether into testing accounts!

Deploying to Testnets

Required Setup:

Deployment Commands:

# Deploy to Goerli
npx hardhat run scripts/deploy.ts --network goerli

# Deploy to Sepolia
npx hardhat run scripts/deploy.js --network sepolia

# Deploy to Mainnet (be careful!)
npx hardhat run scripts/deploy.ts --network mainnet
       

Sepolia Testnet Setup

const ALCHEMY_API_KEY = "YOUR_SEPOLIA_KEY";
const SEPOLIA_PRIVATE_KEY = "YOUR_PRIVATE_KEY";

module.exports = {
  solidity: "0.8.18",
  networks: {
    sepolia: {
      url: `https://eth-sepolia.g.alchemy.com/v2/${ALCHEMY_API_KEY}`,
      accounts: [SEPOLIA_PRIVATE_KEY]
    }
  }
};
    
Sepolia Faucet: https://www.alchemy.com/faucets/ethereum-sepolia
Note: You need 0.001 real ETH in your wallet to use the faucet

OpenZeppelin Integration

Installation:

npm install @openzeppelin/contracts

Sample NFT Contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyNFT is ERC721URIStorage, Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    
    constructor() ERC721("MyNFT", "NFT") {}
    
    function mintNFT(address recipient, string memory tokenURI)
        public onlyOwner returns (uint256) {
        _tokenIds.increment();
        uint256 newItemId = _tokenIds.current();
        _mint(recipient, newItemId);
        _setTokenURI(newItemId, tokenURI);
        return newItemId;
    }
}
   

Common Issues & Solutions

🔧 Insufficient Funds Error:

// Reduce locked amount in deploy.ts
const lockedAmount = ethers.utils.parseEther("0.05"); // Instead of 1 ETH

🔧 Missing Menu After Installation:

  1. Delete scripts and contracts folders
  2. Run npx hardhat --verbose
  3. Delete hardhat.config.js
  4. Run npx hardhat again

🔧 Debug Deployment Issues:

npx hardhat run scripts/deploy.ts --network goerli --show-stack-traces

📚 Additional Resources

Official Documentation:

Key Tools:

🎉 Congratulations!

You've learned how to:

Ready to build amazing dApps! 🚀

1 / 19