0
0
BlockchainHow-ToBeginner ยท 4 min read

How to Use Hardhat for Solidity Development

To use Hardhat for development, first install it with npm install --save-dev hardhat, then create a project using npx hardhat. You can write, compile, test, and deploy Solidity contracts using Hardhat's commands and plugins.
๐Ÿ“

Syntax

Hardhat commands help you manage your Solidity project. Key commands include:

  • npx hardhat: Initializes a new Hardhat project.
  • npx hardhat compile: Compiles Solidity contracts.
  • npx hardhat test: Runs tests on your contracts.
  • npx hardhat run scripts/deploy.js: Runs deployment scripts.

The hardhat.config.js file configures networks, compiler versions, and plugins.

bash
npm install --save-dev hardhat
npx hardhat
npx hardhat compile
npx hardhat test
npx hardhat run scripts/deploy.js
๐Ÿ’ป

Example

This example shows how to create a simple Hardhat project, compile a contract, and run a test.

javascript
// 1. Initialize project
// Run in terminal:
npm init -y
npm install --save-dev hardhat
npx hardhat

// 2. Sample contract: contracts/Greeter.sol
pragma solidity ^0.8.0;

contract Greeter {
    string private greeting;

    constructor(string memory _greeting) {
        greeting = _greeting;
    }

    function greet() public view returns (string memory) {
        return greeting;
    }
}

// 3. Compile contract
// Run in terminal:
npx hardhat compile

// 4. Test contract: test/sample-test.js
const { expect } = require("chai");

describe("Greeter", function () {
  it("Should return the greeting message", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy("Hello, Hardhat!");
    await greeter.deployed();

    expect(await greeter.greet()).to.equal("Hello, Hardhat!");
  });
});

// 5. Run tests
// Run in terminal:
npx hardhat test
Output
Greeter โœ“ Should return the greeting message (123ms) 1 passing (150ms)
โš ๏ธ

Common Pitfalls

Common mistakes when using Hardhat include:

  • Not installing dependencies before running commands.
  • Forgetting to specify the Solidity version in hardhat.config.js, causing compile errors.
  • Running tests without deploying contracts first.
  • Using outdated plugins or network configurations.

Always check your config file and install all required packages.

javascript
/* Wrong: Missing Solidity version in hardhat.config.js */
module.exports = {
  // solidity version missing
};

/* Right: Specify Solidity version */
module.exports = {
  solidity: "0.8.17"
};
๐Ÿ“Š

Quick Reference

CommandPurpose
npx hardhatInitialize a new Hardhat project
npx hardhat compileCompile Solidity contracts
npx hardhat testRun tests on contracts
npx hardhat run