8.区块链系列之hardhat框架部署合约(二)
现在我们来实践hardhat部署合约中的其他更多技术要点
1. 代码方式验证合约
- 注册
https://etherscan.io/
, 如下图添加拷贝API_KEY
- 在.env文件中新增
ETHERSCAN_API_KEY
ETHERSCAN_API_KEY=API_KEY【刚才注册的key】
- hardhat.config.js中新增配置
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY
module.exports = {
etherscan: {
apiKey: ETHERSCAN_API_KEY
}
};
- 覆盖deploy.js
// imports
const { ethers, run, network } = require("hardhat")
// async main
async function main() {
const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
console.log("Deploying contract...")
const simpleStorage = await SimpleStorageFactory.deploy()
await simpleStorage.deployed()
console.log(`Deployed contract to: ${simpleStorage.address}`)
if (network.config.chainId === 5 && process.env.ETHERSCAN_API_KEY) {
console.log("Waiting for block confirmations...")
await simpleStorage.deployTransaction.wait(6)
await verify(simpleStorage.address, [])
}
}
const verify = async (contractAddress, args) => {
console.log("Verifying contract...")
try {
await run("verify:verify", {
address: contractAddress,
constructorArguments: args,
})
} catch (e) {
if (e.message.toLowerCase().includes("already verified")) {
console.log("Already Verified!")
} else {
console.log(e)
}
}
}
// main
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error)
process.exit(1)
})
- 验证合约
如果用的使用了clash代理的话开启Tun模式,否则可能会报Connect Timeout Error
yarn hardhat run scripts/deploy.js --network goerli
或
yarn hardhat verify --network goerli 0x2e3C64c769DAbAC7587dEa70cA23164EEE3d9596 --show-stack-traces
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat verify --network goerli 0x2e3C64c769DAbAC7587dEa70cA23164EEE3d9596 --show-stack-traces
Nothing to compile
Successfully submitted source code for contract
contracts/SimpleStorage.sol:SimpleStorage at 0x2e3C64c769DAbAC7587dEa70cA23164EEE3d9596
for verification on the block explorer. Waiting for verification result...
Successfully verified contract SimpleStorage on Etherscan.
https://goerli.etherscan.io/address/0x2e3C64c769DAbAC7587dEa70cA23164EEE3d9596#code
Done in 30.38s.
2. 通过hardhat与合约交互
在deploy.js的main方法中新增如下代码
async function main() {
......
const currentValue = await simpleStorage.retrieve()
console.log(`Current Value is: ${currentValue}`)
// Update the current value
const transactionResponse = await simpleStorage.store(7)
await transactionResponse.wait(1)
const updatedValue = await simpleStorage.retrieve()
console.log(`Updated Value is: ${updatedValue}`)
}
运行及结果展示:
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat run scripts/deploy.js
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat run scripts/deploy.js
Deploying contract...
Deployed contract to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Current Value is: 0
Updated Value is: 7
Done in 3.62s.
3.自定义hardhat任务
- 新建tasks/block-number.js
const { task } = require("hardhat/config")
task("block-number", "Prints the current block number").setAction(
async (taskArgs, hre) => {
const blockNumber = await hre.ethers.provider.getBlockNumber()
console.log(`Current block number: ${blockNumber}`)
}
)
module.exports = {}
- 在hardhat.config.js中新增配置
require("./tasks/block-number")
- 运行
yarn hardhat
命令
// 可以看到出现了任务
AVAILABLE TASKS:
block-number Prints the current block number
- 运行
yarn hardhat block-number --network goerli
查看最新区块号
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat block-number --network goerli
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat block-number --network goerli
Current block number: 7779125
Done in 14.01s.
4.hardhat本地节点
- 运行
yarn hardhat node
查看本地节点信息
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat node
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat node
Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
Accounts
========
WARNING: These accounts, and their private keys, are publicly known.
Any funds sent to them on Mainnet or any other live network WILL BE LOST.
Account #0: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
Account #1: 0x70997970C51812dc3A010C7d01b50e0d17dc79C8 (10000 ETH)
Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
- 在hardhat.config.js中新增网络配置
module.exports = {
networks: {
localhost: {
url: "http://127.0.0.1:8545/",
chainId: 31337
}
}
};
- 新启动shell窗口并运行
yarn hardhat run scripts/deploy.js --network localhost
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat run scripts/deploy.js --network localhost
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat run scripts/deploy.js --network localhost
Deploying contract...
Deployed contract to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Current Value is: 0
Updated Value is: 7
- 切换到node窗口可看到本地交易信息
- 在新启动的shell窗口中运行
yarn hardhat console --network localhost
我们即可在控制台与合约交互