hardhat初始化的结构:
contracts 写sol合约的文件夹
node_modules 依赖,@是官方团队
scripts 与合约交互
test 测试代码
.gitgnore 忽略上传
hardhat.config.js 编写所有脚本的入口,配置文件
readme.md
配置常见问题:
运行yarn hardhat时无法出现选项菜单,以为配置存储在了错误的位置。解决:npx hardhat --verbose 查看配置所在位置,删除后重新执行yarn hardhat
出现无法运行的时候,执行npm install,重新安装依赖
执行yarn hardhat 出现内容 AvAILABLE TASKS,可以运行的不同命令
yarn hardhat compile 进行编译 编译后多出artifacts文件(编译后的文件)
编译时候报错,提示(这些文件中的Solidity version pragma语句与配置中配置的任何编译器都不匹配。更改pragma或在hardhat配置中配置其他编译器版本。)hardhat.config.js里的module.exports的solidity改为对应solidity的版本 ,contracts下的sol文件用了那个版本,hardhat.config.js就要配置什么版本的sol范围
build-info文件下是编译的底层信息
contracts下是编译后的json文件
F2,快速重命名
Ctrl+P 快速搜索,输入>是命令面板
scripts文件夹下面编写部署脚本,创建deploy.js
运行 yarn hardhat run scripts/deploy.js
注意,有些教程里写 await simpleStorage.deployed(),以及simpleStorage.address 提示方法不存在,这里这两个方法废弃了,使用最新的.waitForDeployment()等待部署完成,simpleStorage.target获取合约地址
//imports
const { ethers } = require("hardhat");
//async main
async function main() {
const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage") //构建部署合约
console.log("Deploying contract...")
const simpleStorage = await SimpleStorageFactory.deploy(); //进行部署
await simpleStorage.waitForDeployment(); // 等待部署完成
console.log("Contract deployed at address:", simpleStorage.target); //查看合约地址
}
//main
main()
.then(() => process.exit(0)) //部署成功执行0
.catch((error) => {
console.error(error);
process.exit(1); //部署异常执行1
});
const {ethers} = require("hardhat")
从hardhat导入封装的ethers
也可以用const {ethers} = require("ethers")但是ethers无法知道artifacts已经建议好的sol,hardhat-ethers知道
yarn add -dev prettier prettier-plugin-solidity 添加格式排版文件
.prettierrc 创建,
{
"tabWidth": 4,
"useTabs": false,
"semi": false,
"singleQuote": false
}
.prettierignore 不要格式那些内容
node_modules
package.json
img
artifacts
cache
coverage
.env
.*
README.md
coverage.json