7.区块链系列之hardhat框架部署合约

news/2024/8/19 12:36:14

先前讲解的本地部署只能合约的方式编码较多,现在我们介绍目前比较流行的智能合约框架hardhat

1.环境准备

yarn init
yarn add --dev hardhat
yarn hardhat
npm install --save-dev @nomicfoundation/hardhat-toolbox

2. 新建并编译SimpleStorage.sol

  • 在hardhat框架conracts目录下新建SimpleStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.8;

contract SimpleStorage {
    uint256 favoriteNumber;

    struct People {
        uint256 favoriteNumber;
        string name;
    }

    // uint256[] public anArray;
    People[] public people;

    mapping(string => uint256) public nameToFavoriteNumber;

    function store(uint256 _favoriteNumber) public {
        favoriteNumber = _favoriteNumber;
    }

    function retrieve() public view returns (uint256) {
        return favoriteNumber;
    }

    function addPerson(string memory _name, uint256 _favoriteNumber) public {
        people.push(People(_favoriteNumber, _name));
        nameToFavoriteNumber[_name] = _favoriteNumber;
    }
}
  • 修改配置文件solidity版本为0.8.8
module.exports = {
  solidity: "0.8.8"
};
  • 开始编译yarn hardhat compile
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat compile
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat compile
Downloading compiler 0.8.8
Compiled 1 Solidity file successfully
Done in 5.70s.
  • 安装代码美化依赖
yarn add --dev prettier prettier-plugin-solidity

新建.prettierrc文件

{
  "tabWidth": 4,
  "useTabs": false,
  "semi": false,
  "singleQuote": false
}

新建.prettierignore文件

node_modules
package.json
img
artifacts
cache
coverage
.env
.*
README.md
coverage.json

3.修改deploy.js并部署

将以下代码覆盖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}`)
}

// main
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error)
    process.exit(1)
})

执行 yarn hardhat run scripts/deploy.js部署合约

(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
Done in 3.67s.

在hardhat.config.js中,我们添加defaultNetwork: "hardhat",这是未指定网络时默认的配置

module.exports = {
  defaultNetwork: "hardhat",
  ...
};

指定具体网络为hardhat

(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat run scripts/deploy.js --network hardhat
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat run scripts/deploy.js --network hardhat
Deploying contract...
Deployed contract to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Done in 3.51s.

4. 部署至GOERLI测试网络

  • 新建.env文件

配置如下内容为测试网信息,详见之前文章

GOERLI_RPC_URL=XXXXX
PRIVATE_KEY=XXXXXXX

覆盖deploy.js内容如下

require("@nomicfoundation/hardhat-toolbox");
require("dotenv").config()

const GOERLI_RPC_URL = process.env.GOERLI_RPC_URL
const PRIVATE_KEY = process.env.PRIVATE_KEY

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  defaultNetwork: "hardhat",
  networks: {
    hardhat: {},
    goerli: {
      url: GOERLI_RPC_URL,
      accounts: [PRIVATE_KEY],
      // https://chainlist.org/zh
      chainId: 5
    }
  },
  solidity: "0.8.8"
};
// 安装依赖
npm install dotenv --save
(base) PS D:\blockchain\blockchain\hardhat-simple-storage-fcc> yarn hardhat run scripts/deploy.js --network goerli
yarn run v1.22.19
$ D:\blockchain\blockchain\hardhat-simple-storage-fcc\node_modules\.bin\hardhat run scripts/deploy.js --network goerli
Deploying contract...
Deployed contract to: 0x4fC6FAe2C80adFd7beF5F6AeF2d8E59F2f3e1265
Done in 30.15s.

访问该地址发现部署成功https://goerli.etherscan.io/address/0x4fC6FAe2C80adFd7beF5F6AeF2d8E59F2f3e1265

1

所有代码已提交至https://gitee.com/SJshenjian/blockchain/tree/master/hardhat-simple-storage-fcc

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


http://lihuaxi.xjx100.cn/news/101249.html

相关文章

【GlobalMapper精品教程】012:WGS84转2000地理坐标系与平面坐标系

本文以案例的形式,讲解在Globalmapper中文版V23.0平台中,WGS84与2000地理坐标系、2000平面坐标系(有带号和无带号)和UTM投影之间的互转。 文章目录 1. 地理坐标WGS84→地理坐标CGCS20002. 地理坐标WGS84→平面投影坐标CGCS20002.1 有带号20002.2 无带号20003. WGS84、CHINA…

9.高级内存管理单元

本章内容仍将涉及内存和物理页的分配/回收算法,虽然初级内存管理单元一节,已经实现了对物理内存信息的检测,并初步实现了物理页的分配功能,但这些功能不够强大,不足以支撑整个系统内核的正常运行,因此需通过…

Python判断中使用多个and和or的优先级与踩坑

tags: Python Debug 一个问题 最近刷力扣,想试试 Python 新支持的海象操作符, 其实就是能在语句中赋值, 类似下面这样: if (n:len(nums)):return False但是当出现下面这种情况的时候, 赋值就会失败: if True or (a:1):print(a)NameError: name a is not defined 出现这个错…

[附源码]Java计算机毕业设计SSM服装创意定制管理系统

项目运行 环境配置: Jdk1.8 Tomcat7.0 Mysql HBuilderX(Webstorm也行) Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。 项目技术: SSM mybatis Maven Vue 等等组成,B/S模式 M…

【科学文献计量】Custom node icons使用图片自定义网络图中的节点过程详解并封装函数直接调用

Custom node icons使用图片自定义网络图中的节点过程详解并封装函数直接调用 0 版本信息1 官方示例2 案例详解2.1 加载图片数据2.2 生成网络图节点和边缘2.3 调整网络图布局2.4 坐标系转换2.5 设置图片的大小和中心位置2.6 把图片放置在对应的节点上3 函数封装3.2 封装13.2 封装…

CLIFF

又发现了华为的一个神器啊 咱来说说哦 华为诺亚提出的刷榜3维人体重建领域的工作CLIFF,在 AGORA 排行榜(SMPL 算法赛道)上排名第一,吓人哈.. 论文链接:https://arxiv.org/abs/2208.00571 代码地址:https://github.c…

【Netty】三、Netty心跳检测与断线重连

Netty心跳检测一、Netty心跳检测与断线重连案例客户端代码NettyClientNettyClientHandler服务端代码NettyServerNettyServerChannelInitializerNettyServerHandler测试一、Netty心跳检测与断线重连案例 需求: 1、客户端利用空闲状态给服务端发送心跳ping命令&#…

java算法 API

数组 创建数组 int[] arrnew int[6]; int[] arrnew int[array.size()] ; 数组排序 int nums[] Arrays.sort(nums)数组求长度 nums.length求char[] a 长度 a.length定位 a[i]比较两个数组是否相等 Arrays.equals(ary, ary1))String 获取其长度 s.length()定位某个元素 s.ch…