lemooljiang avatar

使用hardhat布署合约 / 学习智能合约#58

lemooljiang

Published: 19 Sept 2022 › Updated: 19 Sept 2022使用hardhat布署合约  / 学习智能合约#58

使用hardhat布署合约 / 学习智能合约#58

前几天在布署合约时遇到了很扎心的问题:总是在最后一步不成功!尝试了所有的可能性,最后归结于工具(truffle)的问题了,因为我用Remix时是可以布署成功的。

搜索了一些其它布署工具,hardhat的呼声挺高的,就拿来尝试下。看了下它的使用手册,走了一遍流程,布署了下合约,竞发现相当丝滑!竞是一步就成功啰!

教程在这,写得不错。和truffle类似,也有编译和布署这些,总体很相似。

安装

npm install --save-dev hardhat 
//"hardhat": "^2.11.2"

/
npx hardhat
Create an empty hardhat.config.js

编译布署合约

//编译合约
npx hardhat compile

//一些需要用到的依赖
npm install --save-dev @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai

npx hardhat run scripts/deploy.js --network <network-name>
npx hardhat run scripts/deploy.js --network mumbai

文件结构

hardhat.jpg

如上图所示,文件结构大概如此。设置下deploy.jsconfig.js就基本差不多。合约文件放在contracts就可以。

配置

config.js配置

/** @type import('hardhat/config').HardhatUserConfig */
require("@nomiclabs/hardhat-waffle");
var key = "2fe81fxxxx";  //私钥

module.exports = {
  solidity: "0.8.17",

  networks: {
    mumbai: {
      url: `https://rpc-mumbai.maticvigil.com`,
      accounts: [`0x${key}`]
    },
  }
};

deploy.js配置

async function main() {

    const [deployer] = await ethers.getSigners();
  
    console.log(
      "Deploying contracts with the account:",
      deployer.address
    );
    
    console.log("Account balance:", (await deployer.getBalance()).toString());
  
    //所需布署的合约名,文件位于contracts中
    const Contract = await ethers.getContractFactory("FirstContract");
    const contracted = await Contract.deploy();
  
    console.log("contract address:", contracted.address);
  }
  
main()
.then(() => process.exit(0))
.catch(error => {
    console.error(error);
    process.exit(1);
});

hardhat布署合约一步就成功了!和truffle相比,真是好用太多!有些后悔没有早点更换工具,白白浪费了数天时间。有时候人的依赖性还是不能太高,该变的时候就要求变!

Leave 使用hardhat布署合约 / 学习智能合约#58 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #smartcontract posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang