本文最后更新于 2024-03-24,本文发布时间距今超过 90 天, 文章内容可能已经过时。最新内容请以官方内容为准

One-stop with Hardhat (Hardhat 操作总结)

简介

Hardhat 是一个以太坊开发环境,专为智能合约开发、部署、测试和调试而设计。它提供了一套工具,使得与以太坊网络的交互变得更加简单高效。

环境准备

  • 安装 Node.js (版本 v18.16.0 以上)
  • 安装 npm (Node.js 包管理器)

创建 Hardhat 项目

  1. 创建项目目录

    mkdir my-hardhat-project
    cd my-hardhat-project
    
  2. 初始化 npm 项目

    npm init -y
    
  3. 安装 Hardhat 依赖

    npm install --save-dev hardhat
    
  4. 初始化 Hardhat 配置文件

    npx hardhat
    

    选择 “Create a JavaScript project” 以生成 hardhat.config.js 文件。

编写智能合约

contracts/ 目录下创建智能合约文件,例如 Add.sol:

pragma solidity ^0.8.9;

contract Add {
    function add(uint a, uint b) public pure returns(uint) {
        return a + b;
    }
}

编译智能合约

使用以下命令编译所有合约:

npx hardhat compile

部署智能合约

  1. 编写部署脚本 scripts/deploy.js:

    const hre = require("hardhat");
    
    async function main() {
        const add = await hre.ethers.deployContract("Add");
        await add.waitForDeployment();
        console.log(`Add deployed to ${add.address}`);
    }
    
    main().catch((error) => {
        console.error(error);
        process.exitCode = 1;
    });
    
  2. 部署到本地网络:

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

测试智能合约

  1. 创建测试文件 tests/Add.js:

    const { expect } = require("chai");
    
    describe("Add", function () {
        it("should return the sum of two numbers", async function () {
            const Add = await ethers.getContractFactory("Add");
            const add = await Add.deploy();
    
            const result = await add.add(2, 3);
            expect(result).to.equal(5);
        });
    });
    
  2. 运行测试:

    npx hardhat test
    

任务与插件

Hardhat 允许创建自定义任务,例如打印账户列表:

// hardhat.config.js
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
    const accounts = await hre.ethers.getSigners();

    for (const account of accounts) {
        console.log(account.address);
    }
});

运行自定义任务:

npx hardhat accounts

控制台 (没啥必要)

Hardhat 提供了一个交互式 JavaScript 控制台,可以通过以下命令访问:

npx hardhat console

运行时环境 (HRE)

Hardhat 运行时环境是 Hardhat 框架及其依赖的总称。它允许在脚本、任务和测试中使用 Hardhat 功能。

Fork 网络

Hardhat 支持 Fork 网络,可以创建目标网络的分叉链。配置 hardhat.config.js 中的 forking 选项:

networks: {
  hardhat: {
    forking: {
      url: "https://mainnet.infura.io/v3/<key>",
      blockNumber: 14390000 // 指定分叉的区块号
    }
  }
}

模拟账户

Hardhat Network 允许模拟任何地址,即使没有私钥也可以发送交易。

额外资源