1.Hardhat概述
Hardhat是一个编译、部署、测试和调试以太坊应用的开发环境。它可以帮助开发人员管理和自动化构建智能合约和dApps过程中固有的重复性任务,并围绕这一工作流程轻松引入更多功能。它集成了合约的编译、运行和测试等核心功能,帮助开发人员快速的启动项目,搭建开发环境。
Hardhat优点:
- Hardhat 拥有大量插件,并允许自定义、灵活性和可扩展性。
- Hardhat 运行内置ether.js 5
- Hardhat 有良好的 console.log() 调试能力;会在调试时提供代码中发生的堆栈跟踪。
- Hardhat 提供原生Typescript支持,并且还有一个Vscode扩展,为 Vscode 编辑器添加了可靠的支持。
- Hardhat 带有一个内置的本地以太坊网络,称为Hardhat Network,用于在本地机器上运行和部署智能合约,是一个专为开发而设计的本地以太坊网络节点。
- Hardaht 可以fork网络节点到本地上模拟调用使用
2.Hardhat创建项目
在我们的工作空间里面为新项目创建一个文件夹:
mkdir test04
3.项目初始化
cd test04
npm init -y
初始化成功之后,在项目中会生成一个test04/package.json文件,打开package.json文件,内容如下:
{
"name": "test04",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
4.搭建开发环境
在test04/目录下面执行:
4.1安装Hardhat
npm install --save-dev hardhat
4.2运行Hardhat
npx hardhat
连续回车,不用做任何修改操作。
Hardhat 工程会默认下载 hardhat-toolbox 插件
及一些常规设置:
创建好的Hardhat工程包含文件有:
contracts
:智能合约目录scripts
:部署脚本文件test
:智能合约测试用例文件夹。hardhat.config.js
:配置文件,配置hardhat连接的网络及编译选项。
5.编写合约
合约开发推荐使用 VSCode 编辑器 + solidity 插件,在contracts
下新建一个合约文件件 Lock.sol
(*.sol
是 Solidity 合约文件的后缀名), 复制如下代码:
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.19;
// Uncomment this line to use console.log
// import "hardhat/console.sol";
contract Lock {
uint public unlockTime;
address payable public owner;
event Withdrawal(uint amount, uint when);
constructor(uint _unlockTime) payable {
require(
block.timestamp < _unlockTime,
"Unlock time should be in the future"
);
unlockTime = _unlockTime;
owner = payable(msg.sender);
}
function withdraw() public {
// Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal
// console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);
require(block.timestamp >= unlockTime, "You can't withdraw yet");
require(msg.sender == owner, "You aren't the owner");
emit Withdrawal(address(this).balance, block.timestamp);
owner.transfer(address(this).balance);
}
}
注意这里面的solidity版本号要与
hardhat.config.js文件配置的一致,否则在编译时会报错。
一个简易版的合约项目就搭建起来了,
接下来我们就可以进行合约的开发工作。