区块链——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代码地址:项目地址

### 关于WeBASE-Front部署智能合约区块链的操作步骤 #### 准备工作 为了成功利用 WeBASE-Front 部署智能合约到区块链环境,需先完成一系列准备工作。这包括安装并配置好 FISCO BCOS 节点以及启动 WeBASE 中间件服务平台的相关组件,如管理平台 (WeBASE-Web),节点管理系统 (WeBASE-Node-Manager),签名服务 (WeBASE-Sign)[^1]。 #### 启动WeBASE-Front前置服务 确保已经下载了 WeBASE-Front 并解压至合适位置之后,在命令行工具中进入 `WeBASE-Front` 的根目录下的 `dist` 文件夹内执行如下指令来赋予脚本可执行权限,并运行该服务: ```bash chmod u+x *.sh bash start.sh ``` 上述命令会初始化 WeBASE-Front 前置服务器,使其处于监听状态以便接收来自客户端的应用请求[^3]。 #### 编写与编译Solidity智能合约 编写 Solidity 智能合约文件(.sol), 使用 Remix IDE 或者其他支持 Solidity 开发的语言编辑器进行编码。完成后通过 Truffle Suite, Hardhat 等框架对 .sol 文件做进一步编译处理得到 ABI 和字节码文件,这是后续上传合同时所需的资源之一[^4]。 #### 利用WeBASE-Front界面部署智能合约 登录 WeBASE Web 控制台后找到对应的菜单项用于提交新创建的智能合约。按照页面提示填写必要参数,比如合约名称、版本号等基本信息;接着上传之前准备好的 ABI 及二进制代码文件作为附件。确认无误点击发送按钮即完成了整个流程中的最后一步——向指定的目标网络广播交易消息以实现智能合约的实际部署动作[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值