智能合约之hardhat使用

407 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情

前言

Hardhat 是以太坊软件的开发环境。它由用于编辑、编译、调试和部署智能合约和 dApp 的不同组件组成,所有这些组件协同工作以创建完整的开发环境。

它帮助开发人员管理和自动化构建智能合约和dApp的过程中固有的重复任务,以及轻松地围绕此工作流程引入更多功能,并且内置了开发专用以太坊网络,这意味着从根本上进行编译和测试。

官方文档 hardhat.org/hardhat-run…

使用步骤

确认电脑环境已经安装了yarn或者npm

  1. mkdir hardhat-simple 新建一个目录
  2. yarn init 初始化yarn工程
  3. yarn add --dev hardhat 安装hardhat库
  4. yarn hardhat 初始化一个hardhat工程

image.png

image.png

image.png

执行yarn hardhat compile 可编译contracts文件夹下面的合约,artifacts文件夹是合约编译的所有信息

image.png

image.png

增加一个合约文件,继续执行yarn hardhat compile 可以看到新增的合约也会被一起编译,如下图SimpleStorage。

image.png

部署合约

// imports
const { ethers } = 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}`)

  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}`)
}


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

执行 yarn hardhat run scripts/deploy.js 可部署合约,运行结果如下

image.png

hardhat.config.js 配置文件可以设置指定网络来部署合约

networks:{
 hardhat: {},
 rospten: {
   url: RINKEBY_RPC_URL,
   accounts: [PRIVATE_KEY],
   chainId: 3,
 },
}

执行 yarn hardhat run scripts/deploy.js --network rospten 可以部署到rospten 测试网络。 如下图,由于是部署到测试网,所以可能会比较慢

Deployed contract to: 0xC93f856d110f511E6dFBE8d32ed77F87cce07694

访问 ropsten.etherscan.io/address/0xC… 可以查看到我们部署的合约地址

image.png

image.png

总结

hardhat工具确实可以很大的方便了我们的合约编译、开发还有自动化测试,是一个集成化很多功能的工具,值得我们学会使用。