Hardhat创建、编译、测试智能合约

部署环境

操作系统:Win10

前提条件

安装Nodejs(版本在v14+),可参考:安装 Nodejs (CentOS7 与 Windows)_ling1998的博客-优快云博客

安装hardhat并展示样例

(1)创建并进入目录

F:\>mkdir hardhatdemo
F:\>cd hardhatdemo

(2)初始化项目

F:\hardhatdemo>npm init --yes  #初始化项目,--yes跳过提示信息
Wrote to F:\hardhatdemo\package.json:

{
  "name": "hardhatdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

此时项目根目录中生成package.json文件

(3)安装hardhat

F:\hardhatdemo>npm install --save-dev hardhat

added 298 packages in 44s

53 packages are looking for funding
  run `npm fund` for details

安装时间较长,耐心等待吧。

安装成功生成node-modules依赖包目录,里面包含许多依赖包

此安装并非顺利,出现了许多问题,但当时未解决,第二天再试突然就成功了,出现的错误可参见:Hardhat安装与相关插件报错记录_ling1998的博客-优快云博客

既然成功了,那就继续吧。

(4)启动项目

F:\hardhatdemo>npx hardhat
888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

Welcome to Hardhat v2.9.3

? What do you want to do? ...
> Create a basic sample project
  Create an advanced sample project
  Create an advanced sample project that uses TypeScript
  Create an empty hardhat.config.js
  Quit

通过键盘上的上下键选择”Create a basic sample project“ ,确认项目根目录及确认增加.gitignore,连续回车确认即可。

888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

Welcome to Hardhat v2.9.3

√ What do you want to do? · Create a basic sample project
√ Hardhat project root: · F:\hardhatdemo      #回车
√ Do you want to add a .gitignore? (Y/n) · y  #回车

You need to install these dependencies to run the sample project:
  npm install --save-dev "hardhat@^2.9.3" "@nomiclabs/hardhat-waffle@^2.0.0" "ethereum-waffle@^3.0.0" "chai@^4.2.0" "@nomiclabs/hardhat-ethers@^2.0.0" "ethers@^5.0.0"

Project created
See the README.md file for some example tasks you can run.

完成后,项目目录生成目录结构如下: 

contracts目录: 存储合约源文件

scripts目录:     存储测试文件

test目录:         存储自动化脚本文件

hardhat.config.js文件:配置文件

(5)安装插件Ehter.js 与Waffle

上一步中启动项目提示信息中出现

You need to install these dependencies to run the sample project:

npm install --save-dev "hardhat@^2.9.3" "@nomiclabs/hardhat-waffle@^2.0.0" "ethereum-waffle@^3.0.0" "chai@^4.2.0" "@nomiclabs/hardhat-ethers@^2.0.0" "ethers@^5.0.0"

最新依赖版本命令(不加版本号):

npm install --save-dev @nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers

这需要安装相应的插件,直接拷贝上面命令,执行时间有些长,而且有时会报错,可再次执行尝试

F:\hardhatdemo>npm install --save-dev "hardhat@^2.9.3" "@nomiclabs/hardhat-waffle@^2.0.0" "ethereum-waffle@^3.0.0" "chai@^4.2.0" "@nomiclabs/hardhat-ethers@^2.0.0" "ethers@^5.0.0"
npm WARN deprecated ganache-core@2.13.2: ganache-core is now ganache; visit https://trfl.io/g7 for details
npm WARN deprecated ganache-core@2.13.2: ganache-core is now ganache; visit https://trfl.io/g7 for details
npm WARN deprecated testrpc@0.0.1: testrpc has been renamed to ganache-cli, please use this package from now on.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated @ensdomains/ens@0.4.5: Please use @ensdomains/ens-contracts
npm WARN deprecated @ensdomains/resolver@0.2.4: Please use @ensdomains/ens-contracts

added 1107 packages, and audited 1409 packages in 17m

115 packages are looking for funding
  run `npm fund` for details

54 vulnerabilities (11 moderate, 42 high, 1 critical)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

(6)编译合约

F:\hardhatdemo>npx hardhat compile
Downloading compiler 0.8.4
Compiled 2 Solidity files successfully

此时项目根目录生成2个目录

 (7)测试(ether.js&waffle)

F:\hardhatdemo>npx hardhat test


  Greeter
Deploying a Greeter with greeting: Hello, world!
Changing greeting from 'Hello, world!' to 'Hola, mundo!'
    √ Should return the new greeting once it's changed (3728ms)


  1 passing (4s)

编译及测试自己的合约

(1)创建并进入目录

F:\hardhatdemo>cd ..    #返回上一级目录

F:>mkdir hardhatmyself  #创建自己合约目录

F:>cd hardhatmyself     #进入目录

(2) 初始化项目

F:\hardhatmyself>npm init -yes
Wrote to F:\hardhatmyself\package.json:

{
  "name": "hardhatmyself",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

项目目录生成文件package.json

(3)安装hardhat

F:\hardhatmyself>npm install --save-dev hardhat

added 298 packages, and audited 299 packages in 16m

53 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

安装时间较长,有时10+分钟,有时1小时,超过半小时建议,重新尝试。安装完一次以后可以一直使用。

(4)启动项目

F:\hardhatmyself>npx hardhat
888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

Welcome to Hardhat v2.9.3

? What do you want to do? ...
  Create a basic sample project
  Create an advanced sample project
  Create an advanced sample project that uses TypeScript
> Create an empty hardhat.config.js
  Quit

通过键盘上的上下键选择”Create an empty hardhat.config.js",回车即可。 

F:\hardhatmyself>npx hardhat
888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888

Welcome to Hardhat v2.9.3

√ What do you want to do? · Create an empty hardhat.config.js
Config file created

发现项目目录中增加配置文件 hardhat.config.js

(5)安装插件

F:\hardhatmyself>npm install --save-dev @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai
npm WARN deprecated ganache-core@2.13.2: ganache-core is now ganache; visit https://trfl.io/g7 for details
npm WARN deprecated ganache-core@2.13.2: ganache-core is now ganache; visit https://trfl.io/g7 for details
npm WARN deprecated testrpc@0.0.1: testrpc has been renamed to ganache-cli, please use this package from now on.
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated @ensdomains/ens@0.4.5: Please use @ensdomains/ens-contracts
npm WARN deprecated @ensdomains/resolver@0.2.4: Please use @ensdomains/ens-contracts

added 1107 packages, and audited 1409 packages in 3m

115 packages are looking for funding
  run `npm fund` for details

54 vulnerabilities (11 moderate, 42 high, 1 critical)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

安装时间较长,若半小时还没反应,重新执行安装命令。 

(6)编写合约

创建合约目录contracts

F:\hardhatmyself>mkdir contracts

创建合约文件hello.sol,文件名与合约名相同,内容为:

// SPDX-License-Identifier: Apache-2.0
pragma solidity^0.8.0;

 /**
   * @title hello
   * @dev test in Remix env
   * @custom:dev-run-script prictice/hello.js
   */
contract hello {
    string public message;

    constructor(string memory _msg) {
        message = _msg;
    }

    function getMsg() public view returns (string memory) {
        return message;
    }

    function setMsg(string memory _msg) public {
        message = _msg;
    }
}

(7)编译合约

查看配置文件中的编译版本,调整与合约中编译版本匹配 

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.4",
};

编译合约尝试了一下0.8.0至0.8.7,只有0.8.3与0.8.4版本编译通过,其它版本都报错,所以建议先在0.8.3与0.8.4版本编译

编译命令npx hardhat compile默认编译contracts目录下的合约文件(.sol)

# 0.8.0 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.0
Error HH501: Couldn't download compiler version 0.8.0. Please check your connection.

For more info go to https://hardhat.org/HH501 or run Hardhat with --show-stack-traces

# 0.8.1 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.1
DocstringParsingError: Documentation tag @custom:dev-run-script not valid for contracts.
 --> contracts/hello.sol:4:2:
  |
4 |  /**
  |  ^ (Relevant source part starts here and spans across multiple lines).


Error HH600: Compilation failed

For more info go to https://hardhat.org/HH600 or run Hardhat with --show-stack-traces

# 0.8.2 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.2
Error HH501: Couldn't download compiler version 0.8.2. Please check your connection.

For more info go to https://hardhat.org/HH501 or run Hardhat with --show-stack-traces

# 0.8.3 (成功)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.3
Compiled 1 Solidity file successfully

# 0.8.4 (成功)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.4
Compiled 1 Solidity file successfully

# 0.8.5 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.5
Error HH501: Couldn't download compiler version 0.8.5. Please check your connection.

For more info go to https://hardhat.org/HH501 or run Hardhat with --show-stack-traces

# 0.8.6 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.6
Error HH501: Couldn't download compiler version 0.8.6. Please check your connection.

For more info go to https://hardhat.org/HH501 or run Hardhat with --show-stack-traces

# 0.8.7 (失败)
F:\hardhatmyself>npx hardhat compile
Downloading compiler 0.8.7
Error HH501: Couldn't download compiler version 0.8.7. Please check your connection.

For more info go to https://hardhat.org/HH501 or run Hardhat with --show-stack-traces

项目目录生成 artifacts与cache

(8)测试合约

 配置文件hardhat.config.j中添加引用插件waffle,如下所示(第一行): 

require("@nomiclabs/hardhat-waffle");
/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.4",
};

创建测试目录test

创建测试脚本文件sample-test-hello.js,编写测试脚本内容如下:

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

describe("Hello", function(){
  it("Should return the new hello once it's changed", async function(){
    const Hello = await ethers.getContractFactory("hello");
    const hello = await Hello.deploy("hello ,tracy, I am testing");
    await hello.deployed();
    console.log("hell address:", hello.address);

    //expect(await hello.getMsg());

    console.log("origin getMsg:", await hello.getMsg());
    const setMsg = await hello.setMsg("new Msg, hello, I am here");

    await setMsg.wait();
    //expect(await hello.getMsg());
    console.log("new getMsg:", await hello.getMsg());
  });
});

测试命令npx hardhat test默认执行test目录下的js脚本文件

F:\hardhatmyself>npx hardhat test


  Hello
hell address: 0x5FbDB2315678afecb367f032d93F642f64180aa3
origin getMsg: hello ,tracy, I am testing
new getMsg: new Msg, hello, I am here
    √ Should return the new hello once it's changed (700ms)


  1 passing (709ms)

折腾许久,终于成功了,按这个思路继续进行其它合约脚本测试。

注:若hardhat项目已存在,可使用npm update 更新下载依赖包

参考文档:概述 | Hardhat | 为专业人士开发的以太坊开发环境 by Nomic Labs

<think>好的,用户现在想了解如何将Web3.js作为Hardhat插件使用,特别是更新后的hardhat-web3-v4。我需要先回顾之前的对话,用户之前询问过DFS的Java实现,现在转向了区块链开发工具,可能是在进行智能合约开发的学习或项目。 首先,用户的需求分为两部分:介绍和步骤。我需要确保覆盖最新的兼容性更新,并详细说明每个步骤。用户可能已经有一定的Hardhat基础,但需要确认安装和配置是否正确,特别是依赖项的安装。 接下来,我需要考虑用户可能的背景。他们可能正在从其他工具迁移到Hardhat,或者刚开始使用Hardhat,需要指导如何集成Web3.js。用户提到的步骤包括创建项目、安装依赖、编写合约、编译部署、测试交互。我需要分步骤解释,确保每个环节都清晰,特别是hardhat-web3-v4的配置部分。 在步骤①中,创建项目可能需要初始化并选择TypeScript或JavaScript,但用户可能更熟悉JS,所以示例中使用JavaScript更合适。步骤②的依赖项要准确,包括hardhat-web3-v4、web3、以及可能的其他如ethers,但用户明确提到Web3.js,所以重点在web3和插件。 编写合约部分需要简单示例,比如一个Storage合约,方便后续测试编译和部署时,要说明配置文件的修改,尤其是插件的引入和网络设置。部署脚本中使用web3.js的方式可能需要详细说明,尤其是如何获取账户和发送交易。 测试部分要展示如何用Web3.js编写测试用例,使用Hardhat测试框架,可能涉及异步函数和合约方法调用。需要注意合约地址的处理,可能在部署后动态获取。 用户可能遇到的问题包括插件配置错误、依赖版本冲突、部署时的账户锁定等,所以在注意事项里需要提到这些点,比如安装指定版本,处理本地节点,以及测试时的账户解锁。 最后,对比Web3.js和Ethers.js可以帮助用户理解选择的原因,但用户可能已经决定使用Web3.js,所以这部分作为补充即可。需要确保所有代码示例正确,特别是Hardhat配置和部署脚本中的语法正确,比如使用require而不是import,如果用户使用JavaScript的话。 还要检查所有步骤是否连贯,是否存在遗漏,例如是否需要在配置文件中添加网络设置,或者是否需要启动本地节点进行部署测试。需要提醒用户启动本地节点(如npx hardhat node)并在部署时连接到该网络。 总之,需要提供一个全面、逐步的指南,确保用户能够顺利集成hardhat-web3-v4,并使用Web3.js进行合约的部署和测试,同时指出常见问题和解决方案。</think>--- ### Hardhat + Web3.js 集成指南(v4 兼容版) --- #### 一、核心更新介绍 **hardhat-web3-v4** 插件现已正式支持 **Web3.js 4.x** 版本,主要升级包括: 1. 兼容 **Hardhat 2.12+** 最新版 2. 支持 **TypeScript 5.0+** 类型系统 3. 优化了与 **Hardhat Network** 的交互性能 4. 提供 **Web3.js** 与 **Ethers.js** 的混合使用方案 --- #### 二、详细操作步骤 ##### 1. 创建 Hardhat 项目 ```bash mkdir my-web3-project cd my-web3-project npm init -y npx hardhat init ``` 选择 **Create a JavaScript project**(推荐)或 TypeScript 项目 ##### 2. 安装依赖项 ```bash npm install --save-dev hardhat-web3-v4@latest npm install web3 @nomicfoundation/hardhat-toolbox ``` ##### 3. 配置 `hardhat.config.js` ```javascript require("@nomicfoundation/hardhat-toolbox"); require("hardhat-web3-v4"); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.19", networks: { localhost: { url: "http://127.0.0.1:8545", chainId: 31337 } } }; ``` ##### 4. 编写智能合约(示例) ```solidity // contracts/SimpleStorage.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SimpleStorage { uint256 private value; function store(uint256 _value) public { value = _value; } function retrieve() public view returns (uint256) { return value; } } ``` ##### 5. 编译与部署脚本 ```javascript // scripts/deploy.js const Web3 = require('web3'); const hre = require('hardhat'); async function main() { const web3 = new Web3(hre.config.networks.localhost.url); // 获取测试账户 const [account] = await web3.eth.getAccounts(); // 部署合约 const Contract = await hre.ethers.getContractFactory("SimpleStorage"); const contract = await Contract.deploy(); console.log("合约地址:", contract.address); console.log("部署账户:", account); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` ##### 6. 测试用例(Web3.js 实现) ```javascript // test/simpleStorage.test.js const { expect } = require("chai"); const Web3 = require('web3'); const hre = require('hardhat'); describe("SimpleStorage", function () { let web3; let contract; before(async () => { web3 = new Web3(hre.config.networks.localhost.url); const accounts = await web3.eth.getAccounts(); // 部署合约 const Contract = await hre.ethers.getContractFactory("SimpleStorage"); const deployed = await Contract.deploy(); contract = new web3.eth.Contract(Contract.interface, deployed.address); }); it("应正确存储和读取数值", async () => { const testValue = 42; const accounts = await web3.eth.getAccounts(); // 写入操作 await contract.methods.store(testValue).send({ from: accounts[0] }); // 读取验证 const result = await contract.methods.retrieve().call(); expect(Number(result)).to.equal(testValue); }); }); ``` --- #### 三、关键操作命令 | 操作 | 命令 | |----------------------|-------------------------------| | 启动本地节点 | `npx hardhat node` | | 编译合约 | `npx hardhat compile` | | 部署到本地网络 | `npx hardhat run scripts/deploy.js --network localhost` | | 运行测试 | `npx hardhat test` | --- #### 四、注意事项 1. **版本兼容性**: - Node.js ≥ 16.x - Web3.js 4.x - Hardhat ≥ 2.12.0 2. **混合使用建议**: ```javascript // 同时使用 Web3.js 和 Ethers.js const { ethers } = require("hardhat"); const Web3 = require('web3'); // Ethers 适用于部署和简单交互 // Web3 适合需要细粒度控制的场景 ``` 3. **常见问题处理**: - **账户锁定错误**:在本地节点启动后执行 `npx hardhat unlock --network localhost` - **类型冲突**:在 `tsconfig.json` 中添加 `"skipLibCheck": true` - **版本冲突**:使用 `npm ls web3` 检查依赖树 --- #### 五、最佳实践建议 1. **环境分离策略**: ```javascript // 根据环境切换 Provider const web3 = new Web3( process.env.NODE_ENV === "production" ? process.env.INFURA_URL : "http://localhost:8545" ); ``` 2. **合约交互优化**: ```javascript // 使用 Web3.js 的批量请求 const batch = new web3.BatchRequest(); batch.add( contract.methods.retrieve().call.request({}, (err, result) => { if (!err) console.log("Result:", result); }) ); batch.execute(); ``` --- #### 六、与 Ethers.js 对比 | 特性 | Web3.js | Ethers.js | |-------------------|-----------------------|-----------------------| | API 风格 | 回调优先 | Promise 优先 | | 类型支持 | 需额外安装 @types/web3 | 内置 TypeScript 支持 | | 合约抽象 | 手动生成 ABI | 自动生成完整接口 | | 交易监控 | 需手动轮询 | 提供事件监听器 | | 本地节点集成 | 需要配置 Provider | 与 Hardhat 深度集成 | --- 通过本指南,您可以快速在 Hardhat 项目中集成 Web3.js v4,充分利用其成熟的生态系统和细粒度控制能力,同时享受 Hardhat 的现代化开发体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值