Hardhat是一个编译、部署、测试和调试以太坊应用的开发环境。
Hardhat内置了Hardhat网络,这是一个专为开发设计的本地以太坊网络。主要功能有Solidity调试,跟踪调用堆栈、 console.log() 和交易失败时的明确错误信息提示等
# 创建项目目录
mkdir hardhat-tutorial
cd hardhat-tutorial# 初始化node.js环境
npm init# 安装 hardhat
npm install --save-dev hardhat
npx hardhat
编写代码,注意目录,文件名
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.9;contract Computed{uint x;function add(uint y) public view returns(uint){return x + y;}function readd(uint y) public view returns(uint){return add(y);}}
编译
npx hardhat compile
编译成功后
# 安装工具
npm install --save-dev @nomicfoundation/hardhat-toolbox
创建测试文件 computed.js,注意文件夹和文件名
const { expect } = require("chai");describe("Computed contract", function () {it("Deployment Computed compute result", async function () {// ether.js里getSigners 表示账户const [owner] = await ethers.getSigners();// ether.js里getContractFactory 是部署合约的抽象类const Computed = await ethers.getContractFactory("Computed");// 部署合约const hardhatComputed = await Computed.deploy();// 调用合约函数const result = await hardhatComputed.add(2);expect( result == 2 );});
});
#执行测试npx hardhat test
// Computed.sol 里添加pragma solidity ^0.8.9;//添加内容
import "hardhat/console.sol";contract Computed{uint x;function add(uint y) public view returns(uint){// 打印日志console.log("start add",msg.sender,x,y);return x + y;}function readd(uint y) public view returns(uint){return add(y);}
}
执行结果
新建目录,文件 deploy.js
async function main() {const [deployer] = await ethers.getSigners();console.log("Deploying contracts with the account:", deployer.address);console.log("Account balance:", (await deployer.getBalance()).toString());const Token = await ethers.getContractFactory("Computed");const token = await Token.deploy();console.log("Token address:", token.address);}main().then(() => process.exit(0)).catch((error) => {console.error(error);process.exit(1);});
修改 hardhat.config.js
require("@nomicfoundation/hardhat-toolbox");// 到 https://www.alchemyapi.io, 创建dAPP,找到key , 替换 KEY
const ALCHEMY_API_KEY = "KEY";// 替换钱包私钥,记得这是Goerli测试网
// 打开小狐狸 Metamask 钱包
// 打开 Account Details > 导出 Private Key
// 注意: 不要往测试网里转主网(真实账号)的eth
const GOERLI_PRIVATE_KEY = "YOUR GOERLI PRIVATE KEY";module.exports = {solidity: "0.8.9",networks: {goerli: {url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,accounts: [GOERLI_PRIVATE_KEY]}}
};
以下2个可以 Goerli 水龙头可以领取 测试网的eth
部署:
npx hardhat run scripts/deploy.js --network Goerli
npx hardhat
hardhat.config.js 添加
require("@nomicfoundation/hardhat-toolbox");
参考:
3. Creating a new Hardhat project | Ethereum development environment for professionals by Nomic Foundation