This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a Hardhat Ignition module that deploys that contract.
Try running some of the following tasks:
npx hardhat help
npx hardhat test
REPORT_GAS=true npx hardhat test
npx hardhat node
npx hardhat ignition deploy ./ignition/modules/Lock.js第六章总结 关于hardhat的学习 使用脚本和task来部署,交互和我们的智能合约
- 已安装 Node.js(建议 ≥ 18)
- 本地已安装 pnpm/npm/yarn(下文以 npm 为例)
- 一个 Sepolia 的 RPC Endpoint(如 Alchemy/Infura)
- 准备一个测试网账户私钥(钱包里需有少量测试 ETH)
- 申请 Etherscan API Key(用于合约验证)
推荐使用 Hardhat Toolbox(内置常用插件,包含 verify 能力)。此外使用 dotenv 管理环境变量。
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox dotenv如果你的项目没有使用 toolbox,也可以单独安装验证插件:
npm install --save-dev @nomicfoundation/hardhat-verify在项目根目录新建 .env 文件,填入以下变量:
# Sepolia
SEPOLIA_RPC_URL=https://sepolia.infura.io/v3/<YOUR_INFURA_KEY>
PRIVATE_KEY=0x<你的账户私钥,带0x前缀>
ETHERSCAN_API_KEY=<你的Etherscan API Key>
# 用于脚本逻辑判断的链 ID(Sepolia=11155111)
CHAIN_ID=11155111
# 可选:开启 gas 报告
REPORT_GAS=true切记不要把 .env 提交到 Git(.gitignore 中忽略)。
要点:
sepolia网络设置包括url、accounts、chainIdetherscan.apiKey用来授权验证请求- 工具箱(toolbox)已提供
verify任务;也可单独 require@nomicfoundation/hardhat-verify
你的部署脚本核心流程如下(已结合 Ethers v6 API):
- 获取合约工厂:
ethers.getContractFactory("SimpleStorage") - 部署合约:
SimpleStorage.deploy() - 等待部署完成:
waitForDeployment() - 获取合约地址:
getAddress() - 根据网络与 API Key 判断是否进行 Etherscan 验证
- 等待若干块确认再验证(常见做法 >= 6 块)
- 调用合约读写方法(
retrieve、store)
run("verify:verify", params)调用的是 Hardhat 的“内部子任务”,对应命名空间verify下的verify子任务。- 命令行方式则使用顶级任务:
npx hardhat verify --network <net> <address> [constructorArgs...] - 在脚本中使用
try/catch包裹,便于:- 已验证的情况(错误信息包含 "already verified")给出友好提示
- 其他错误打印出来,便于排查
字符串方法回顾:
e.message:错误对象的消息文本toLowerCase():转小写,忽略大小写差异includes("already verified"):判断是否包含子串
- 编译:
npx hardhat compile- 本地网络(可选):
npx hardhat node- 部署到 Sepolia:
npx hardhat run scripts/deploy.js --network sepolia部署完成后,脚本会:
- 打印合约地址
- 在满足条件时自动等待 6 个确认并进行 Etherscan 验证
- 测试
retrieve/store的读写调用
论外 关于从wsl:ubuntu注册拉取github仓库的命令 git init git add . git commit -m "first commit" git config --global user.name "wuqin76" git config --global user.email "[email protected]" git config --global user.name git config --global user.email git config --list git commit -m "first commit" git remote add origin https://github.com/wuqin76/smart_cotract_learning.git git branch -M main git push -u origin main 更新仓库命令 git add . git commit -m "你的更新说明" git push