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


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

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

    1

    • 在.env文件中新增ETHERSCAN_API_KEY
    ETHERSCAN_API_KEY=API_KEY【刚才注册的key】
    
    • 1
    • hardhat.config.js中新增配置
    const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY
    
    module.exports = {
      etherscan: {
        apiKey: ETHERSCAN_API_KEY
      }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 覆盖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)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 验证合约

    如果用的使用了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.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    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}`)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    运行及结果展示:

    (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.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    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 = {}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 在hardhat.config.js中新增配置
    require("./tasks/block-number")
    
    • 1
    • 运行yarn hardhat命令
    // 可以看到出现了任务
    AVAILABLE TASKS:
      block-number          Prints the current block number
    
    • 1
    • 2
    • 3
    • 运行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.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 在hardhat.config.js中新增网络配置
    module.exports = {
      networks: {
        localhost: {
          url: "http://127.0.0.1:8545/",
          chainId: 31337
        }
      }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 新启动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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 切换到node窗口可看到本地交易信息

    2

    • 在新启动的shell窗口中运行yarn hardhat console --network localhost我们即可在控制台与合约交互

    3

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

  • 相关阅读:
    Linux性能学习(4.6):网络_孤儿连接、半连接状态、RTS复位报文简述
    YOLO目标检测——人体行为数据集【含对应voc、coco和yolo三种格式标签】
    前端笔记_OAuth规则机制下实现个人站点接入qq三方登录
    【python】将python脚本打包成可执行的.exe文件 推荐使用auto-py-to-exe
    单播与多播mac地址
    JAVA毕业设计WEB儿童运动馆业务信息系统计算机源码+lw文档+系统+调试部署+数据库
    手把手教你制作登录、注册界面 SpringBoot+Vue.js(cookie的灵活运用,验证码功能)
    NNDL 实验六 卷积神经网络
    Xcode 真机调试之Unable to install “xxx“,Code: -402653103
    Liunx上JSON处理工具jq
  • 原文地址:https://blog.csdn.net/SJshenjian/article/details/127460364