区块链——hardhat使用

一、引入hardhat

yarn add --dev hardhat
// 引入验证合约的插件
yarn add --dev @nomicfoundation/hardhat-verify

二、创建hardhat项目

yarn hardhat

三、编写我们的合约

在这里插入图片描述

四、编译我们的合约

yarn hardhat compile

五、编写脚本部署合约以及验证合约

在这里插入图片描述

// 获取hardhat环境对象
const hre = require("hardhat")
// 获取ethers
const { ethers, network } = hre
// network是运行脚本时当前的网络配置
console.log(network)
async function main() {
  // 从ethers中获取合约生成工厂
  const SimpleStorageFactory = await ethers.getContractFactory("SimpleStorage")
  console.log("Deploying contract...")
  // 部署合约
  const simpleStorage = await SimpleStorageFactory.deploy()
  // 等待合约部署完毕,后面出现其他的区块后,再验证合约
  await simpleStorage.deploymentTransaction().wait(6)
  // 获取合约地址
  const contractAddress = await simpleStorage.getAddress()
  console.log(`Deployed contract to: ${contractAddress}`)
  // 验证合约
  await verifyCode(contractAddress)
}

/**
 * @param {合约地址} contractAddress
 * @param {合约构造函数参数} args
 */
async function verifyCode(contractAddress, args) {
  console.log("Verifying contract...")
  await hre.run("verify:verify", {
    address: contractAddress,
    constructorArguments: args,
  })
}

main()
  .then(() => process.exit(0))
  .catch((err) => {
    console.log(err)
  })

六、配置hardhat

require("@nomicfoundation/hardhat-toolbox")
// 用来验证我们发布的合约
require("@nomicfoundation/hardhat-verify")
require("dotenv").config()
require("./task/blockNumber")

task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
  const accounts = await hre.ethers.getSigners()

  for (const account of accounts) {
    console.log(account.address)
  }
})

const SEPOLIA_RPC_URL = process.env.SEPOLIA_RPC_URL
const SEPOLIA_PRIVARY_KEY = process.env.SEPOLIA_PRIVARY_KEY
const SEPOLIA_CHAIN_ID = process.env.SEPOLIA_CHAIN_ID
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  // 表示默认使用hardhat网络
  defaultNetwork: "hardhat",
  // 也可以添加其他网络
  networks: {
    hardhat: {},
    sepolia: {
      url: SEPOLIA_RPC_URL,
      accounts: [SEPOLIA_PRIVARY_KEY],
      chainId: Number(SEPOLIA_CHAIN_ID),
    },
    localhost: {
      url: "http://127.0.0.1:8545/",
      chainId: 31337,
    },
  },
  solidity: "0.8.24",
  // 配置etherscan
  etherscan: {
    // Your API key for Etherscan
    // Obtain one at https://etherscan.io/
    apiKey: ETHERSCAN_API_KEY,
  },
}

七、命令行运行脚本

// 我们的脚本在scripts目录下,如果没有–network则使用上面配置的默认网络hardhat
yarn hardhat run scripts/deploy.js --network sepolia

八、测试代码

const { expect, assert } = require("chai")
const hre = require("hardhat")
const {
  time,
  loadFixture,
} = require("@nomicfoundation/hardhat-toolbox/network-helpers")

describe("SimpleStorage", function () {
  // 在it之前需要做什么事情,我们肯定需要先部署我们的合约
  const deployContractFunc = async () => {
    const contractFactory = await hre.ethers.getContractFactory("SimpleStorage")
    const simpleStorage = await contractFactory.deploy()
    return { contractFactory, simpleStorage }
  }

  // 展示it assert用法
  it("合约初始化时favoriteNumber应该是0", async () => {
    // 定义我们的预期值
    const expectValue = "0"
    const { simpleStorage } = await loadFixture(deployContractFunc)
    const favorateNumber = await simpleStorage.retrieve()
    assert.equal(favorateNumber.toString(), expectValue)
  })

  // 展示it expect用法
  it("合约初始化时favoriteNumber应该不是0", async () => {
    // 定义我们的预期值
    const expectValue = "0"
    const { simpleStorage } = await loadFixture(deployContractFunc)
    const favorateNumber = await simpleStorage.retrieve()
    expect(favorateNumber).to.not.equal(expectValue)
  })
})

本地启动节点:yarn hardhat node
运行测试代码:yarn hardhat test test/SimpleStorage.js --network localhost

九、测试时输出gas

1.计算gas使用的库
yarn add --dev hardhat-gas-reporter
2.在hardhat.config.js中添加
require(“hardhat-gas-reporter”)

module.exports = {
...
// 计算gas使用
 gasReporter: {
   enabled: true,
   // outputFile: "./gas-report.txt",
  noColors: true,
   currency: "USD",
  coinmarketcap: COINMARKET_API_KEY,
  token: "MATIC",
 },
}

十、使用hardhat-deploy部署合约

1、安装依赖

yarn add --dev hardhat-deploy
// 如果使用了ether.js,我们还需要导入下面的包
yarn add --dev @nomiclabs/hardhat-ethers hardhat-deploy-ethers ethers

2、在hardhat-config.js中添加require(“hardhat-deploy”)

在这里插入图片描述

3、创建deploy文件夹,在文件夹下写脚本,因为hardhat-deploy会根据文件名顺序执行脚本,所以我们一般命名为00-xxx.js,01-xxx.js

4、项目git代码地址:项目地址

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值