šŸŽ‰ 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
šŸ’¼ Servicesā„¹ļø Aboutāœ‰ļø ContactView Pricing Plansfrom $10

Hardhat Development Environment

Blockchain Development🟢 Free Lesson

Hardhat Development Environment

Overview

Hardhat is the most popular Ethereum development environment, providing compilation, testing, deployment, and debugging tools for smart contracts.

ā„¹ļø

Hardhat's plugin system makes it highly extensible. Most functionality comes from community plugins like hardhat-ethers, hardhat-waffle, and hardhat-gas-reporter.

Architecture

Hardhat ArchitectureHardhatRuntimeCompilationTestingDeploymentDebuggingPluginsTasksNetworksConfig

Project Setup

Installation

# Initialize new project
npx hardhat init

# Or with TypeScript
mkdir my-project && cd my-project
npm init -y
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
npx hardhat init

Project Structure

Architecture Diagram
my-project/
ā”œā”€ā”€ contracts/           # Solidity contracts
│   ā”œā”€ā”€ Token.sol
│   └── interfaces/
ā”œā”€ā”€ test/                # Test files
│   ā”œā”€ā”€ Token.test.js
│   └── Token.test.ts
ā”œā”€ā”€ scripts/             # Deployment scripts
│   └── deploy.js
ā”œā”€ā”€ tasks/               # Custom tasks
│   └── accounts.js
ā”œā”€ā”€ typechain-types/     # Generated TypeScript types
ā”œā”€ā”€ artifacts/           # Compiled contracts
ā”œā”€ā”€ cache/               # Compilation cache
ā”œā”€ā”€ coverage/            # Test coverage reports
ā”œā”€ā”€ hardhat.config.ts    # Configuration
ā”œā”€ā”€ package.json
└── tsconfig.json

Configuration

hardhat.config.ts

import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-verify";
import "hardhat-gas-reporter";
import "solidity-coverage";
import "hardhat-deploy";
import * as dotenv from "dotenv";

dotenv.config();

const config: HardhatUserConfig = {
  solidity: {
    version: "0.8.19",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
      viaIR: true,
    },
  },
  
  networks: {
    hardhat: {
      forking: {
        url: process.env.MAINNET_RPC_URL || "",
        blockNumber: 18000000, // Pin block for consistency
      },
    },
    goerli: {
      url: process.env.GOERLI_RPC_URL || "",
      accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
      chainId: 5,
    },
    mainnet: {
      url: process.env.MAINNET_RPC_URL || "",
      accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [],
      chainId: 1,
    },
  },
  
  gasReporter: {
    enabled: process.env.REPORT_GAS === "true",
    currency: "USD",
    coinmarketcap: process.env.COINMARKETCAP_API_KEY,
  },
  
  etherscan: {
    apiKey: process.env.ETHERSCAN_API_KEY,
  },
  
  typechain: {
    outDir: "typechain-types",
    target: "ethers-v6",
  },
};

export default config;

Configuration Options

OptionPurposeDefault
solidity.versionCompiler version0.8.x
optimizer.enabledEnable optimizerfalse
optimizer.runsOptimization runs200
networks.*.urlRPC endpoint-
networks.*.accountsPrivate keys[]
gasReporter.enabledGas reportingfalse

Compilation

Compile Contracts

# Compile all contracts
npx hardhat compile

# Clean and recompile
npx hardhat clean && npx hardhat compile

# Compile with specific version
npx hardhat compile --force

Compiler Configuration

// hardhat.config.ts
solidity: {
  compilers: [
    {
      version: "0.8.19",
      settings: {
        optimizer: { enabled: true, runs: 200 },
      },
    },
    {
      version: "0.7.6",
      settings: {
        optimizer: { enabled: true, runs: 200 },
      },
    },
  ],
  overrides: {
    "contracts/Complex.sol": {
      version: "0.8.19",
      settings: {
        optimizer: { enabled: true, runs: 1000 },
        viaIR: true,
      },
    },
  },
},

Compilation Output

Architecture Diagram
Compiling 2 files with 0.8.19
Compilation finished
  - Token.sol: Token.json, Token.d.json
  - Vault.sol: Vault.json, Vault.d.json

Artifacts: artifacts/contracts/
TypeChain: typechain-types/

Testing

JavaScript Tests

javascript
// test/Token.test.js
const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Token", function () {
  let token;
  let owner;
  let addr1;
  let addr2;

  beforeEach(async function () {
    [owner, addr1, addr2] = await ethers.getSigners();
    
    const Token = await ethers.getContractFactory("Token");
    token = await Token.deploy("MyToken", "MTK", 1000000);
    await token.deployed();
  });

  describe("Deployment", function () {
    it("Should set the right name and symbol", async function () {
      expect(await token.name()).to.equal("MyToken");
      expect(await token.symbol()).to.equal("MTK");
    });

    it("Should assign the total supply to the owner", async function () {
      const ownerBalance = await token.balanceOf(owner.address);
      expect(await token.totalSupply()).to.equal(ownerBalance);
    });
  });

  describe("Transfers", function () {
    it("Should transfer tokens between accounts", async function () {
      await token.transfer(addr1.address, 100);
      expect(await token.balanceOf(addr1.address)).to.equal(100);

      await token.connect(addr1).transfer(addr2.address, 50);
      expect(await token.balanceOf(addr2.address)).to.equal(50);
    });

    it("Should fail if sender doesn't have enough tokens", async function () {
      const initialOwnerBalance = await token.balanceOf(owner.address);
      
      await expect(
        token.connect(addr1).transfer(owner.address, 1)
      ).to.be.revertedWith("ERC20: insufficient balance");

      expect(await token.balanceOf(owner.address)).to.equal(initialOwnerBalance);
    });
  });
});

TypeScript Tests

// test/Token.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { Token } from "../typechain-types";
import { SignerWithAddress } from "@nomicfoundation/hardhat-ethers/signers";

describe("Token", function () {
  let token: Token;
  let owner: SignerWithAddress;
  let addr1: SignerWithAddress;
  let addr2: SignerWithAddress;

  beforeEach(async function () {
    [owner, addr1, addr2] = await ethers.getSigners();
    
    const Token = await ethers.getContractFactory("Token");
    token = await Token.deploy("MyToken", "MTK", 1000000);
    await token.waitForDeployment();
  });

  describe("Deployment", function () {
    it("Should set the right name and symbol", async function () {
      expect(await token.name()).to.equal("MyToken");
      expect(await token.symbol()).to.equal("MTK");
    });
  });

  describe("Transfers", function () {
    it("Should transfer tokens between accounts", async function () {
      const transferAmount = ethers.parseEther("100");
      
      await token.transfer(addr1.address, transferAmount);
      expect(await token.balanceOf(addr1.address)).to.equal(transferAmount);
    });
  });
});

Run Tests

# Run all tests
npx hardhat test

# Run specific file
npx hardhat test test/Token.test.ts

# Run with gas reporting
REPORT_GAS=true npx hardhat test

# Run with coverage
npx hardhat coverage

# Run in parallel
npx hardhat test --parallel

Deployment Scripts

Basic Deployment

javascript
// scripts/deploy.js
const { ethers } = require("hardhat");

async function main() {
  const [deployer] = await ethers.getSigners();
  
  console.log("Deploying contracts with:", deployer.address);
  console.log("Balance:", ethers.formatEther(await ethers.provider.getBalance(deployer.address)));

  const Token = await ethers.getContractFactory("Token");
  const token = await Token.deploy("MyToken", "MTK", 1000000);
  await token.waitForDeployment();

  const tokenAddress = await token.getAddress();
  console.log("Token deployed to:", tokenAddress);

  // Verify on Etherscan
  console.log("Waiting for block confirmations...");
  await token.deploymentTransaction()?.wait(6);

  await hre.run("verify:verify", {
    address: tokenAddress,
    constructorArguments: ["MyToken", "MTK", 1000000],
  });
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Hardhat Deploy Plugin

// deploy/001_deploy_token.ts
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { DeployFunction } from "hardhat-deploy/types";

const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  const { deployments, getNamedAccounts } = hre;
  const { deploy } = deployments;
  const { deployer } = await getNamedAccounts();

  const result = await deploy("Token", {
    from: deployer,
    args: ["MyToken", "MTK", 1000000],
    log: true,
  });

  console.log("Token deployed to:", result.address);
};

export default func;
func.tags = ["Token"];

Deployment Scripts

# Deploy to specific network
npx hardhat run scripts/deploy.js --network goerli
npx hardhat run scripts/deploy.js --network mainnet

# Using hardhat-deploy
npx hardhat deploy
npx hardhat deploy --network goerli

# Verify contract
npx hardhat verify --network mainnet CONTRACT_ADDRESS "Arg1" "Arg2"

Plugins

Essential Plugins

PluginPurposeInstallation
@nomicfoundation/hardhat-toolboxAll-in-one toolkitIncluded by default
@nomicfoundation/hardhat-verifyContract verificationnpm i -D @nomicfoundation/hardhat-verify
hardhat-gas-reporterGas reportingnpm i -D hardhat-gas-reporter
solidity-coverageTest coveragenpm i -D solidity-coverage
hardhat-deployDeployment managementnpm i -D hardhat-deploy
@openzeppelin/hardhat-upgradesUpgradeable contractsnpm i -D @openzeppelin/hardhat-upgrades

Plugin Configuration

// hardhat.config.ts
import "@nomicfoundation/hardhat-toolbox";
import "@nomicfoundation/hardhat-verify";
import "hardhat-gas-reporter";
import "solidity-coverage";

const config: HardhatUserConfig = {
  // ... other config
  
  gasReporter: {
    enabled: true,
    currency: "USD",
    gasPrice: 21,
    coinmarketcap: process.env.COINMARKETCAP_API_KEY,
    excludeContracts: ["Migrations"],
  },
  
  etherscan: {
    apiKey: {
      mainnet: process.env.ETHERSCAN_API_KEY,
      goerli: process.env.ETHERSCAN_API_KEY,
    },
  },
};

Mainnet Forking

Fork Configuration

// hardhat.config.ts
const config: HardhatUserConfig = {
  networks: {
    hardhat: {
      forking: {
        url: process.env.MAINNET_RPC_URL || "",
        blockNumber: 18000000, // Pin to specific block
        enabled: true,
      },
    },
  },
};

Fork Testing Example

// test/ForkTest.test.ts
import { expect } from "chai";
import { ethers } from "hardhat";
import { impersonateAccount } from "@nomicfoundation/hardhat-network-helpers";

describe("Fork Testing", function () {
  it("Should interact with mainnet contracts", async function () {
    // Impersonate a whale account
    const whaleAddress = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"; // Vitalik
    await impersonateAccount(whaleAddress);
    
    const whale = await ethers.getSigner(whaleAddress);
    const balance = await ethers.provider.getBalance(whaleAddress);
    console.log("Whale balance:", ethers.formatEther(balance));
    
    // Interact with Uniswap, Aave, etc.
    const uniswapRouter = await ethers.getContractAt(
      "IUniswapV2Router",
      "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
    );
    
    // Test your contract against real protocol state
  });
});

Fork Benefits

BenefitDescriptionUse Case
Real StateUses actual mainnet dataProtocol integration
Testnet TokensUse real token contractsDeFi testing
No DeploymentSkip contract deploymentQuick testing
ReproduciblePin to block numberConsistent results

Debugging

Hardhat Console

# Start interactive console
npx hardhat console --network localhost

# In console
> const Token = await ethers.getContractFactory("Token")
> const token = await Token.deploy("Test", "TST", 1000000)
> await token.deployed()
> await token.totalSupply()

Debugging Tasks

# Trace transaction
npx hardhat trace --hash 0x...

# Impersonate account
npx hardhat impersonate-account --address 0x...

# Set balance
npx hardhat set-balance --address 0x... --amount 1000000000000000000

# Mine blocks
npx hardhat mine --blocks 10

Logging in Tests

// Using hardhat console.log
import "hardhat/console.sol";

contract Token {
    function transfer(address to, uint256 amount) public {
        console.log("Transfer from:", msg.sender);
        console.log("Transfer to:", to);
        console.log("Amount:", amount);
        // ... logic
    }
}

Gas Reporting

Gas Reporter Output

Architecture Diagram
  Token
    Deployment
      āœ“ Should set the right name and symbol (150ms)
    Transfers
      āœ“ Should transfer tokens between accounts (120ms)

  Gas usage for Token:
  ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
  │ Contract                        │ Method       │ Min Gas   │ Max Gas   │
  ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¼ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
  │ Token                           │ transfer     │ 52,000    │ 52,000    │
  │ Token                           │ approve      │ 46,000    │ 46,000    │
  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”“ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Gas Optimization

FunctionBeforeAfterSavings
transfer52,00048,0007.7%
approve46,00044,0004.3%
mint65,00060,0007.7%

CI/CD Integration

GitHub Actions

# .github/workflows/test.yml
name: Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "18"
          
      - name: Install dependencies
        run: npm ci
        
      - name: Compile contracts
        run: npx hardhat compile
        
      - name: Run tests
        run: npx hardhat test
        
      - name: Run coverage
        run: npx hardhat coverage
        
      - name: Run gas reporter
        run: REPORT_GAS=true npx hardhat test

Real-World Example: Compound Finance

Testing Strategy

Test TypePurposeCoverage
UnitIndividual functions100%
IntegrationContract interactionsCritical paths
ForkProtocol integrationDeFi operations
FuzzEdge casesProperty testing

Trade-offs

DecisionOption AOption BRecommendation
LanguageJavaScriptTypeScriptTypeScript for type safety
TestingMocha/ChaiForgeUse both for coverage
DeploymentScriptshardhat-deployhardhat-deploy for complex
NetworkTestnetForkFork for integration tests

Interview Questions

  1. Explain the difference between hardhat test and hardhat coverage. When would you use each?

    hardhat test runs tests quickly for development. hardhat coverage instruments contracts to measure code coverage, showing which lines/branches are tested. Use test during development, coverage before commits to ensure comprehensive testing.

  2. How does mainnet forking work and what are its benefits for testing?

    Mainnet forking creates a local copy of mainnet state at a specific block. Benefits: test against real protocol state, use actual token contracts, no testnet deployment needed, reproducible results with pinned blocks.

  3. Describe the Hardhat plugin ecosystem and how to extend Hardhat's functionality.

    Hardhat uses a plugin architecture where plugins extend core functionality via tasks, fixtures, and network helpers. Install plugins via npm, import in config, and they automatically extend Hardhat. Examples: hardhat-ethers adds ethers.js integration, hardhat-gas-reporter adds gas reporting.

Quiz Questions

  1. What is the default directory for compiled contract artifacts?

    • A) dist/
    • B) build/
    • C) artifacts/
    • D) out/

    Answer: C - Hardhat outputs compiled artifacts to the artifacts/ directory.

  2. How do you enable optimizer in Hardhat configuration?

    • A) optimizer: true
    • B) optimizer: { enabled: true }
    • C) enableOptimizer: true
    • D) optimize: true

    Answer: B - Set optimizer: { enabled: true, runs: 200 } in solidity settings.

  3. What command runs test coverage in Hardhat?

    • A) hardhat test --coverage
    • B) hardhat coverage
    • C) hardhat test:coverage
    • D) hardhat run coverage

    Answer: B - Run npx hardhat coverage to generate coverage reports.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
ā˜†ā˜†ā˜†ā˜†ā˜†
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement