一、引入hardhat
yarn add --dev hardhat
// 引入验证合约的插件
yarn add --dev @nomicfoundation/hardhat-verify
二、创建hardhat项目
yarn hardhat
三、编写我们的合约
四、编译我们的合约
yarn hardhat compile
五、编写脚本部署合约以及验证合约
// 获取hardhat环境对象
const hre = require("hardhat")
// 获取ethers
const { ethers, network } = hre
// network是运行脚本时当前的网络配置
console.log(network)
async function main() {// 从ethers中获取合约生成工厂const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage")console.log("Deploying contract...")// 部署合约const simpleStorage = await SimpleStorageFactory.deploy()// 等待合约部署完毕,后面出现其他的区块后,再验证合约await simpleStorage.deploymentTransaction().wait(6)// 获取合约地址const contractAddress = await simpleStorage.getAddress()console.log(`Deployed contract to: ${contractAddress}`)// 验证合约await verifyCode(contractAddress)
}/*** @param {合约地址} contractAddress* @param {合约构造函数参数} args*/
async function verifyCode(contractAddress, args) {console.log("Verifying contract...")await hre.run("verify:verify", {address: contractAddress,constructorArguments: args,})
}main().then(() => process.exit(0)).catch((err) => {console.log(err)})
六、配置hardhat
require("@nomicfoundation/hardhat-toolbox")
// 用来验证我们发布的合约
require("@nomicfoundation/hardhat-verify")
require("dotenv").config()
require("./task/blockNumber")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)}
})const SEPOLIA_RPC_URL = process.env.SEPOLIA_RPC_URL
const SEPOLIA_PRIVARY_KEY = process.env.SEPOLIA_PRIVARY_KEY
const SEPOLIA_CHAIN_ID = process.env.SEPOLIA_CHAIN_ID
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {// 表示默认使用hardhat网络defaultNetwork: "hardhat",// 也可以添加其他网络networks: {hardhat: {},sepolia: {url: SEPOLIA_RPC_URL,accounts: [SEPOLIA_PRIVARY_KEY],chainId: Number(SEPOLIA_CHAIN_ID),},localhost: {url: "http://127.0.0.1:8545/",chainId: 31337,},},solidity: "0.8.24",// 配置etherscanetherscan: {// Your API key for Etherscan// Obtain one at https://etherscan.io/apiKey: ETHERSCAN_API_KEY,},
}
七、命令行运行脚本
// 我们的脚本在scripts目录下,如果没有–network则使用上面配置的默认网络hardhat
yarn hardhat run scripts/deploy.js --network sepolia
八、测试代码
const { expect, assert } = require("chai")
const hre = require("hardhat")
const {time,loadFixture,
} = require("@nomicfoundation/hardhat-toolbox/network-helpers")describe("SimpleStorage", function () {// 在it之前需要做什么事情,我们肯定需要先部署我们的合约const deployContractFunc = async () => {const contractFactory = await hre.ethers.getContractFactory("SimpleStorage")const simpleStorage = await contractFactory.deploy()return { contractFactory, simpleStorage }}// 展示it assert用法it("合约初始化时favoriteNumber应该是0", async () => {// 定义我们的预期值const expectValue = "0"const { simpleStorage } = await loadFixture(deployContractFunc)const favorateNumber = await simpleStorage.retrieve()assert.equal(favorateNumber.toString(), expectValue)})// 展示it expect用法it("合约初始化时favoriteNumber应该不是0", async () => {// 定义我们的预期值const expectValue = "0"const { simpleStorage } = await loadFixture(deployContractFunc)const favorateNumber = await simpleStorage.retrieve()expect(favorateNumber).to.not.equal(expectValue)})
})
本地启动节点:
yarn hardhat node
运行测试代码:yarn hardhat test test/SimpleStorage.js --network localhost
九、测试时输出gas
1.计算gas使用的库
yarn add --dev hardhat-gas-reporter
2.在hardhat.config.js中添加
require(“hardhat-gas-reporter”)module.exports = { ... // 计算gas使用gasReporter: {enabled: true,// outputFile: "./gas-report.txt",noColors: true,currency: "USD",coinmarketcap: COINMARKET_API_KEY,token: "MATIC",}, }
十、使用hardhat-deploy部署合约
1、安装依赖
yarn add --dev hardhat-deploy
// 如果使用了ether.js,我们还需要导入下面的包
yarn add --dev @nomiclabs/hardhat-ethers hardhat-deploy-ethers ethers