Banner

Hardhat 3

2026-11-17

下面是一份可直接照做的 Hardhat 3 入门教程。Hardhat 3 与 v2 差异较大:默认 ESM、插件需要显式注册、推荐使用 Ignition 部署、内置 Solidity 测试和覆盖率。

1. 环境准备

Hardhat 3 需要 Node.js 22+,以及 npm / pnpm / yarn。

node --version
npx --version

2. 初始化项目

mkdir hardhat-example
cd hardhat-example
npx hardhat --init

初始化时会让你选择版本和项目类型。新项目建议选择:

  • Version: Hardhat 3 Beta
  • Directory: .
  • Project type: 选择带 viem 或 ethers 的模板
  • Install dependencies: yes

完成后执行:

npx hardhat --help
npx hardhat test

如果测试通过,说明项目已可用。

3. 项目结构

初始化后典型结构如下:

hardhat-example/
├── contracts/
│   ├── Counter.sol
│   └── Counter.t.sol        # Solidity 测试
├── test/
│   └── Counter.ts           # TypeScript 测试
├── ignition/
│   └── modules/
│       └── Counter.ts       # Ignition 部署模块
├── scripts/
│   └── send-op-tx.ts        # 自定义脚本
├── hardhat.config.ts
└── package.json
目录用途
contracts/存放 Solidity 合约和 .t.sol 测试
test/存放 TypeScript / Solidity 测试
ignition/modules/声明式部署模块
scripts/自动化脚本、部署辅助脚本
hardhat.config.ts项目配置入口

4. 配置文件

Hardhat 3 不再使用 v2 那种隐式 require 插件方式,而是通过 defineConfig 和 plugins 数组显式注册。

import { defineConfig } from "hardhat/config";
import hardhatIgnitionViemPlugin from "@nomicfoundation/hardhat-ignition-viem";

export default defineConfig({
  plugins: [hardhatIgnitionViemPlugin],
  solidity: {
    version: "0.8.28",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200,
      },
    },
  },
  networks: {
    sepolia: {
      type: "http",
      chainType: "l1",
      url: configVariable("SEPOLIA_RPC_URL"),
      accounts: [configVariable("SEPOLIA_PRIVATE_KEY")],
    },
  },
});

敏感信息不要硬编码,推荐用内置 Keystore:

npx hardhat keystore set SEPOLIA_RPC_URL
npx hardhat keystore set SEPOLIA_PRIVATE_KEY

5. 编写合约

在 contracts/Counter.sol 中写一个简单合约:

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

contract Counter {
    uint256 public x;

    function inc(uint256 by) external {
        x += by;
    }
}

编译:

npx hardhat build

6. 编写测试

Hardhat 3 支持两类测试:

  • TypeScript 测试:放在 test/
  • Solidity 测试:放在 contracts/ 或 test/,文件可用 .t.sol

TypeScript 测试示例:

import { expect } from "chai";
import { network } from "hardhat";
import CounterModule from "../ignition/modules/Counter.js";

describe("Counter", function () {
  it("should increment x", async function () {
    const { ignition } = await network.connect();
    const { counter } = await ignition.deploy(CounterModule);

    await counter.inc(5n);
    expect(await counter.x()).toBe(5n);
  });
});

运行测试:

npx hardhat test
npx hardhat test test/Counter.ts
npx hardhat test contracts/Counter.t.sol

查看覆盖率:

npx hardhat test --coverage

覆盖率报告会输出到 coverage/,并生成 HTML 报告。

7. 使用 Ignition 部署

在 ignition/modules/Counter.ts 中定义部署模块:

import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

export default buildModule("Counter", (m) => {
  const counter = m.contract("Counter");
  return { counter };
});

部署到本地网络:

npx hardhat ignition deploy ignition/modules/Counter.ts

部署到 Sepolia:

npx hardhat ignition deploy ignition/modules/Counter.ts --network sepolia

如果需要在脚本中组合异步逻辑、条件判断或打印部署地址,可以用 scripts/:

import hre from "hardhat";
import CounterModule from "../ignition/modules/Counter.js";

async function main() {
  const connection = await hre.network.connect();
  const { counter } = await connection.ignition.deploy(CounterModule);
  console.log("Counter deployed to:", counter.address);
}

main().catch(console.error);

运行脚本:

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

8. 常用命令

npx hardhat --help
npx hardhat build
npx hardhat test
npx hardhat test --coverage
npx hardhat node
npx hardhat ignition deploy ignition/modules/Counter.ts
npx hardhat run scripts/deploy.ts

9. 从 Hardhat 2 迁移时要注意

  • 项目需改为 ESM,package.json 中设置 "type": "module"。
  • 旧配置建议重命名为 hardhat.config.old.js 作为参考。
  • 插件必须 import 并加入 plugins 数组。
  • hardhat-deploy、solidity-coverage 等 v2 插件不一定直接兼容,需要确认是否有 Hardhat 3 替代方案。
  • 自定义 task 写法从 task() 改为 task().setInlineAction().build()。
20