8.区块链系列之hardhat框架部署合约(二)

编程入门 行业动态 更新时间:2024-10-11 19:25:09

8.<a href=https://www.elefans.com/category/jswz/34/1769670.html style=区块链系列之hardhat框架部署合约(二)"/>

8.区块链系列之hardhat框架部署合约(二)

现在我们来实践hardhat部署合约中的其他更多技术要点

1. 代码方式验证合约
  • 注册/, 如下图添加拷贝API_KEY

  • 在.env文件中新增ETHERSCAN_API_KEY
ETHERSCAN_API_KEY=API_KEY【刚才注册的key】
  • hardhat.config.js中新增配置
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEYmodule.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-tracesyarn 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.

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 valueconst 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: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80Account #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我们即可在控制台与合约交互

欢迎关注公众号算法小生或沈健的技术博客shenjian.online

更多推荐

8.区块链系列之hardhat框架部署合约(二)

本文发布于:2024-02-27 09:06:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1705963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区块   合约   框架   系列之   hardhat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!