Hardhat 是一个开源的智能合约开发环境,它提供了强大的功能来帮助开发者构建、测试和部署以太坊智能合约。以下是关于 Hardhat 的文档,帮助您更好地了解和使用这个工具。

快速开始

安装 Hardhat

要开始使用 Hardhat,首先需要安装 Node.js 和 npm。然后,您可以通过以下命令安装 Hardhat:

npm install -g hardhat

创建一个新项目

创建一个新的 Hardhat 项目,使用以下命令:

npx hardhat init

这将在当前目录下创建一个名为 hardhat 的文件夹,并初始化一些基本文件。

配置

配置文件

Hardhat 使用一个名为 hardhat.config.js 的配置文件来设置项目参数。以下是一个基本的配置文件示例:

require("hardhat/config");

module.exports = {
  networks: {
    localhost: {
      url: "http://127.0.0.1:8545",
    },
  },
  solidity: {
    compilers: [
      {
        version: "0.8.0",
        settings: {
          optimizer: {
            enabled: true,
            runs: 200,
          },
        },
      },
    ],
  },
};

网络配置

hardhat.config.js 文件中,您可以配置多个网络,以便在不同的环境中测试和部署您的智能合约。

开发

编写智能合约

在 Hardhat 项目中,智能合约通常存储在 contracts 文件夹中。以下是一个简单的智能合约示例:

// contracts/MyContract.sol

pragma solidity ^0.8.0;

contract MyContract {
    uint256 public count;

    function increment() public {
        count++;
    }
}

编译智能合约

要编译智能合约,使用以下命令:

npx hardhat compile

这将生成 .json 文件,其中包含编译后的合约代码和字节码。

部署智能合约

要部署智能合约,使用以下命令:

npx hardhat run scripts/deploy.js

这将在您配置的网络中部署合约,并返回合约地址。

测试

编写测试

在 Hardhat 项目中,测试通常存储在 test 文件夹中。以下是一个简单的测试示例:

// test/MyContract.test.js

const { ethers } = require("hardhat");
const { expect } = require("chai");

describe("MyContract", function () {
  it("should increment the count", async function () {
    const MyContract = await ethers.getContractFactory("MyContract");
    const instance = await MyContract.deploy();
    await instance.increment();
    expect(await instance.count()).to.equal(1);
  });
});

运行测试

要运行测试,使用以下命令:

npx hardhat test

这将在本地测试网络上运行所有测试。

扩展阅读

想要了解更多关于 Hardhat 的信息,可以访问官方文档

Hardhat Logo