Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Hardhat

Learn Hardhat - 10 Code Examples & CST Typing Practice Test

Hardhat is a JavaScript/TypeScript-based Ethereum development environment and framework. It enables developers to compile, deploy, test, and debug smart contracts efficiently on Ethereum and EVM-compatible networks.

View all 10 Hardhat code examples →
Hardhat Minimal Smart Contract DeploymentHardhat Call Contract FunctionHardhat Get AccountsHardhat Estimate GasHardhat Deploy with ParametersHardhat Listen to EventsHardhat Read Contract VariableHardhat Transfer EtherHardhat Deploy Multiple ContractsHardhat Upgradeable Contract Deployment

Learn HARDHAT with Real Code Examples

Updated Nov 25, 2025

Explain

Hardhat provides a local Ethereum network for development, enabling fast testing and debugging.

Integrates with Solidity compiler to build smart contracts and generate artifacts.

Supports scripts for deployment, contract interaction, and automated testing.

Provides a flexible plugin system for tasks like ethers.js integration, gas reporting, and contract verification.

Widely used in DeFi, NFT projects, and backend DApp development.

Core Features

Tasks and scripts for custom operations

Hardhat Network for instant blockchain simulation

Console logging for smart contract debugging

Testing framework integration (Mocha/Chai)

Contract deployment and verification automation

Basic Concepts Overview

Project - Hardhat workspace with contracts, scripts, and tests

Task - CLI commands for custom operations

Hardhat Network - local Ethereum simulation

Artifact - compiled contract and ABI

Plugin - extends Hardhat functionality

Project Structure

contracts/ - Solidity source code

scripts/ - deployment and interaction scripts

test/ - unit and integration tests

hardhat.config.js - configuration

artifacts/ - compiled contracts and ABIs

Building Workflow

Write Solidity smart contracts in contracts/ folder

Compile using `npx hardhat compile`

Run tests using `npx hardhat test`

Deploy contracts via scripts

Interact with contracts using Hardhat console or scripts

Difficulty Use Cases

Beginner: deploy simple token contract

Intermediate: test DeFi contract interactions

Advanced: deploy multi-contract systems

Expert: integrate frontend with deployed contracts

Auditor: debug contract behavior and transaction flow

Comparisons

Hardhat vs Truffle: Hardhat is faster and plugin-based, Truffle is monolithic

Hardhat vs Brownie: Hardhat JS/TS-focused, Brownie Python-focused

Hardhat vs Web3.py: Hardhat manages full dev workflow, Web3.py is library only

Hardhat vs Foundry: Hardhat JS ecosystem, Foundry Rust/solidity-native

Hardhat vs Remix: Remix is web-based IDE, Hardhat is local development framework

Versioning Timeline

2018 - Hardhat initial release by Nomic Labs

2019 - Hardhat Network introduced

2020 - Plugin system introduced

2021 - TypeScript support and extended tasks

2022-2025 - Enhanced mainnet forking and CI/CD integration

Glossary

Hardhat Network: local blockchain simulator

Task: custom CLI operation

Artifact: compiled contract data

Plugin: extend Hardhat functionality

Forking: simulate mainnet state locally

Installation Setup

Install Node.js 16+

Initialize project with `npm init`

Install Hardhat via `npm install --save-dev hardhat`

Run `npx hardhat` to create project structure

Verify compilation and sample script execution

Environment Setup

Install Node.js 16+

Initialize project with npm

Install Hardhat and dependencies

Configure network settings in hardhat.config.js

Verify compilation and run sample deployment script

Config Files

hardhat.config.js - main configuration

package.json - project dependencies

scripts/ - deployment and interaction scripts

test/ - unit and integration tests

artifacts/ - compiled contracts

.env - secrets and keys

Cli Commands

npx hardhat -> interact with Hardhat CLI

npx hardhat compile -> compile contracts

npx hardhat test -> run tests

npx hardhat node -> start local Hardhat Network

npx hardhat run scripts/deploy.js -> deploy contracts

Internationalization

Docs primarily in English

Community translations emerging

Plugins may provide multi-language support

Used globally for Ethereum projects

Compatible with Unicode contract metadata

Accessibility

Requires JS/TS knowledge

Supported on multiple OS platforms

Well-documented with tutorials

Community support via Discord, GitHub

Easy integration with other tools in JS ecosystem

Ui Styling

Not directly handled

Integrate with frontend frameworks for visualization

Render transaction or contract state

Console outputs for debugging

Plugins can extend reporting features

State Management

Contract state managed on Hardhat Network or Ethereum

Local blockchain reset on network restart

Read/write operations via scripts

Simulate multi-user transactions

Monitor event logs and artifacts

Data Management

Artifacts store compiled contracts and ABI

Script parameters manage deployment and interaction

Transaction receipts logged for verification

Plugin data for gas and performance metrics

Forked mainnet preserves real state for testing

Architecture

Node.js-based CLI and scripting environment

Hardhat Network simulates Ethereum blockchain locally

Artifacts folder stores compiled contracts and ABIs

Plugins extend functionality (ethers.js, gas reporter, etc.)

Tasks define reusable command-line operations

Rendering Model

Hardhat scripts -> Node.js execution

Solidity contracts compiled -> artifacts

Transactions simulated/executed on Hardhat Network

Tasks define CLI operations

Plugins extend core functionality and logging

Architectural Patterns

Plugin-based modular architecture

Task-driven scripting

Local network simulation

Artifact-based contract management

Integration with frontend/backends

Real World Architectures

DeFi protocol testing and deployment

NFT marketplace development

Automated smart contract pipelines

Transaction monitoring and alerting

Frontend-backend DApp integration

Design Principles

Plugin-based extensibility

Fast local blockchain simulation

Integration with JS/TS frontends

Automated testing and scripting

Flexible configuration and task management

Scalability Guide

Use forked networks for realistic testing

Automate batch deployments and testing

Leverage plugins for gas and performance reporting

Modularize scripts for complex projects

Integrate with CI/CD pipelines for scalable workflow

Migration Guide

Convert Truffle scripts to Hardhat tasks

Adjust deployment scripts for Hardhat Network

Update plugin integrations

Test contracts on Hardhat Network before mainnet

Integrate frontend via ethers.js or web3.js

Performance Notes

Local Hardhat Network is fast and instant

Supports forked mainnet for testing real contracts

Automated tests run efficiently with Mocha

Parallel execution of tasks improves speed

Gas estimation may vary slightly from mainnet

Security Notes

Test contracts extensively on Hardhat Network before mainnet

Use private keys securely in environment variables

Avoid storing secrets in scripts

Verify contract bytecode before deployment

Plugins may affect security; choose trusted ones

Monitoring Analytics

Track local network transaction status

Analyze contract events and logs

Generate automated test reports

Integrate with CI/CD dashboards

Monitor gas usage and performance metrics

Code Quality

Follow JS/TS best practices

Use modular scripts and tasks

Write tests for all contracts

Use plugins for reporting and verification

Document deployment and interaction workflows

Practical Examples

ERC20/ERC721 token deployment

DeFi protocol contract testing

NFT marketplace simulation

Automated contract interaction scripts

Transaction tracing and debugging

Troubleshooting

Check Solidity compiler version

Verify Hardhat network connection

Resolve plugin version conflicts

Debug using `console.log` in contracts

Monitor transaction simulation in Hardhat Network

Testing Guide

Run local Hardhat Network for testing

Write unit tests in test/ folder

Use Mocha/Chai assertions

Fork mainnet for realistic contract state testing

Check transaction events and logs

Deployment Options

Local Hardhat Network for development

Testnet deployment via deployment scripts

Mainnet deployment using Hardhat tasks

Automated CI/CD scripts

Plugin-assisted verification on Etherscan

Tools Ecosystem

Hardhat CLI

Hardhat Network

Ethers.js and Web3.js integration

Waffle for testing

Gas reporter and plugin ecosystem

Integrations

Ethereum mainnet and testnets

EVM-compatible chains (Polygon, BSC, Avalanche)

JS/TS frontend frameworks

Continuous integration pipelines

DeFi, NFT, and DApp projects

Productivity Tips

Use Hardhat tasks to automate repetitive work

Fork mainnet for realistic testing

Combine plugins for gas and verification reporting

Modularize scripts and tests

Leverage console logging for debugging contracts

Challenges

Handling plugin conflicts

Managing network configurations

Debugging complex contract interactions

Gas optimization in local network

Ensuring mainnet compatibility from local tests

Learning Path

Learn JavaScript/TypeScript basics

Understand Ethereum accounts, gas, and transactions

Install Hardhat and configure project

Practice writing deployment scripts and tests

Integrate with frontend or backend apps

Skill Improvement Plan

Week 1: JS/TS and Node.js fundamentals

Week 2: Hardhat setup and compiling contracts

Week 3: Writing scripts and tasks

Week 4: Automated testing and debugging

Week 5: Deploy full DApp and integrate frontend

Interview Questions

What is Hardhat and why is it used?

How do you deploy a contract using Hardhat?

Explain Hardhat Network and its benefits

How do you write tests in Hardhat?

How do plugins extend Hardhat functionality?

Cheat Sheet

npx hardhat -> initialize or run tasks

hardhat.config.js -> project configuration

scripts/ -> deployment scripts

contracts/ -> Solidity contracts

test/ -> automated tests

Books

Mastering Ethereum Development with Hardhat

Building DeFi and NFT DApps

Automated Smart Contract Testing with Hardhat

JavaScript for Ethereum Developers

Hardhat Plugin Cookbook

Tutorials

Getting started with Hardhat

Compile, test, and deploy Solidity contracts

Hardhat Network local simulation

Writing deployment and interaction scripts

Integrate Hardhat with frontend DApps

Official Docs

https://hardhat.org/getting-started/

https://github.com/NomicFoundation/hardhat

Community Links

Hardhat GitHub

Nomic Labs Discord

Ethereum StackExchange

Reddit r/ethdev

YouTube Hardhat tutorials

Community Support

Hardhat GitHub

Ethereum StackExchange

Nomic Labs Discord

Reddit r/ethdev

YouTube Hardhat tutorials

Monetization

DeFi and NFT project deployments

Backend automation scripts

Subscription-based monitoring solutions

Analytics dashboards

Smart contract auditing tools

Future Roadmap

Better TypeScript support

Expanded mainnet forking and snapshotting

Enhanced plugin ecosystem

Integration with layer-2 solutions

Community-driven tutorials and templates

When Not To Use

Non-EVM blockchains

Pure Python backend workflows

Projects not using Node.js or JS/TS

Simple scripts not needing local blockchain simulation

Quick one-off testing without full framework

Final Summary

Hardhat is a comprehensive Ethereum development framework.

Provides compilation, deployment, testing, and debugging tools.

Node.js/JS/TS ecosystem integration with plugins.

Local Hardhat Network enables fast testing and debugging.

Ideal for DeFi, NFT, and DApp development on Ethereum.

Faq

Can Hardhat deploy to testnets?

Yes - via scripts using Infura/Alchemy keys

Does Hardhat support TypeScript?

Yes - native TS support is available

Can Hardhat fork mainnet?

Yes - using Hardhat Network with mainnet fork

Is Hardhat suitable for NFTs?

Yes - can deploy and test ERC721 contracts

Can Hardhat be used in CI/CD?

Yes - scripts and tests can be fully automated

Code Sample Descriptions

1

Hardhat Minimal Smart Contract Deployment

// contracts/Counter.sol
pragma solidity ^0.8.0;

contract Counter {
    uint256 public count = 0
    function increment() public { count += 1 }
}

// scripts/deploy.js
async function main() {
    const [deployer] = await ethers.getSigners()
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.deploy()
    await counter.deployed()
    console.log('Counter deployed to:', counter.address)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

A minimal example showing how to deploy a simple smart contract using Hardhat scripts.

Let’s Try →
2

Hardhat Call Contract Function

async function main() {
    const [deployer] = await ethers.getSigners()
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.attach('0xYourContractAddress')
    await counter.increment()
    const value = await counter.count()
    console.log('Counter value:', value)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Call a deployed smart contract function using Hardhat runtime environment.

Let’s Try →
3

Hardhat Get Accounts

async function main() {
    const accounts = await ethers.getSigners()
    accounts.forEach((account, i) => console.log(`Account ${i}: ${account.address}`))
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Retrieve and display the list of accounts provided by Hardhat network.

Let’s Try →
4

Hardhat Estimate Gas

async function main() {
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.attach('0xYourContractAddress')
    const gasEstimate = await counter.estimateGas.increment()
    console.log('Estimated gas:', gasEstimate)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Estimate gas for a contract method call using Hardhat.

Let’s Try →
5

Hardhat Deploy with Parameters

// contracts/Greeting.sol
pragma solidity ^0.8.0;

contract Greeting {
    string public message
    constructor(string memory _msg) { message = _msg }
}

// scripts/deploy.js
async function main() {
    const Greeting = await ethers.getContractFactory('Greeting')
    const greeting = await Greeting.deploy('Hello Hardhat')
    await greeting.deployed()
    console.log('Greeting deployed at:', greeting.address)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Deploy a contract with constructor parameters using Hardhat.

Let’s Try →
6

Hardhat Listen to Events

async function main() {
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.attach('0xYourContractAddress')
    counter.on('Incremented', (newValue) => {
        console.log('Counter incremented to:', newValue)
    })
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Listen to events emitted by a contract using Hardhat provider.

Let’s Try →
7

Hardhat Read Contract Variable

async function main() {
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.attach('0xYourContractAddress')
    const value = await counter.count()
    console.log('Counter value:', value)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Read a public variable from a deployed contract using Hardhat.

Let’s Try →
8

Hardhat Transfer Ether

async function main() {
    const [sender, receiver] = await ethers.getSigners()
    const tx = await sender.sendTransaction({ to: receiver.address, value: ethers.parseEther('1') })
    await tx.wait()
    console.log('Ether transferred')
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Send Ether from one account to another on Hardhat local network.

Let’s Try →
9

Hardhat Deploy Multiple Contracts

async function main() {
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await Counter.deploy()
    await counter.deployed()
    const Greeting = await ethers.getContractFactory('Greeting')
    const greeting = await Greeting.deploy('Hi there')
    await greeting.deployed()
    console.log('Contracts deployed')
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Deploy multiple contracts sequentially in Hardhat script.

Let’s Try →
10

Hardhat Upgradeable Contract Deployment

const { upgrades } = require('hardhat')
async function main() {
    const Counter = await ethers.getContractFactory('Counter')
    const counter = await upgrades.deployProxy(Counter, [0])
    await counter.deployed()
    console.log('Upgradeable Counter deployed at:', counter.address)
}

main().catch((error) => { console.error(error); process.exitCode = 1 })

Deploy an upgradeable contract using Hardhat and OpenZeppelin upgrades plugin.

Let’s Try →

Frequently Asked Questions about Hardhat

What is Hardhat?

Hardhat is a JavaScript/TypeScript-based Ethereum development environment and framework. It enables developers to compile, deploy, test, and debug smart contracts efficiently on Ethereum and EVM-compatible networks.

What are the primary use cases for Hardhat?

Compiling and deploying Solidity smart contracts. Running local Ethereum test networks. Automated testing of smart contracts. Debugging and logging transactions. Scripted contract interactions and deployments

What are the strengths of Hardhat?

Fast local blockchain simulation. Easy Solidity compilation and deployment. Highly extensible with plugins. Debugging and stack traces for contracts. Integrates seamlessly with JS/TS frontends

What are the limitations of Hardhat?

Requires JavaScript/TypeScript knowledge. Primarily Ethereum/EVM-focused. Local network state resets on restart (ephemeral). Some plugins may have version compatibility issues. Less Python integration compared to Web3.py

How can I practice Hardhat typing speed?

CodeSpeedTest offers 10+ real Hardhat code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.