智能合約開發(fā)、測試、部署全流程(實操篇)

前言

本文主要對hardhat框架實操的介紹,通過一個簡單的智能合約案例,用handhat把開發(fā)、測試、部署全流程過一遍。

前期準(zhǔn)備

  • 構(gòu)建工具:hardhat
  • 前端技術(shù)棧:React+Ethersjs+Web3UI Kit
  • 錢包:MetaMask
  • 合約層:Solidity
  • ehterscan區(qū)塊鏈瀏覽器

開始

項目構(gòu)建

# 合約部分
# 創(chuàng)建空文件夾
 mkdir Web3
# 進入工程目錄中
cd Web3
# 項目初始化
npm init
# 安裝hardhat
npm install --save-dev hardhat
# hardhat框架初始化選擇項目模板
npx hardhat init
# 下載項目插件
npm install --save-dev @nomicfoundation/hardhat-toolbox
# 運行校驗
# 在工程目錄下創(chuàng)建文件前端工程目錄
# <<<<<<<<<<<<<<<<<<<<<<<<<
# 前端部分
# 創(chuàng)建一個dapp項目用于編寫前端程序
 create-react-app dapp
# 進入dapp文件夾
cd dapp
# 安裝相應(yīng)的包
# ethers與合約交互
# @web3uikit/core @web3uikit/web3 @web3uikit/icons 錢包相關(guān)包
npm install  xxx

項目目錄結(jié)構(gòu)介紹

web3
   |_contracts//智能合約目錄
   |_test//合約測試目錄
   |_scripts//合約部署目錄
   |_artifacts//編譯合約自動生成
   |___build-info
   |___contracts//前端調(diào)用合約生成的json文件
   |_ignition//
   |_cache//
   |_deploy//部署合約文件目錄
   |_tasts//自定任務(wù)簡化流程
   |_front_end//前端項目工程目錄
   |_hardhat.config.js//hardhat配置文件
   |_helper-hardhat-config.js//hardhat集中常用變量匯總文件
   |_package.json//工程目錄

Hardhat常用指令

# 獲取所有指令
npx hardhat
# 獲取區(qū)塊網(wǎng)絡(luò)節(jié)點
npx hardhat node
# 編譯合約
npx hardhat compile
# 清除緩存并刪除所有工件
npx hardhat clean
# 測試合約
npx hardhat test
# 部署合約
npx hardhat run scripts/xx.js 
# 控制臺
npx hardhat console
# 查看所有指令
npx hardhat 

合約開發(fā)

// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.0.0
pragma solidity ^0.8.22;
import {ERC20} from  "@openzeppelin/contracts/token/ERC20/ERC20.sol"
import {ERC20Burnable} from  "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; 
import {ERC20Permit} from  "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; 
import {Ownable} from  "@openzeppelin/contracts/access/Ownable.sol";
contract MyToken is ERC20, ERC20Burnable, Ownable, ERC20Permit {
    constructor(address initialOwner)
        ERC20("MyToken", "MTK")
        Ownable(initialOwner)
        ERC20Permit("MyToken")
    {
        _mint(msg.sender, 1000 * 10 ** decimals());
    }
  //鑄造方法
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }
}
/**
* 合約說明:
* 使用openzeppelin庫快速構(gòu)建一個具備鑄造和銷毀的ERC20標(biāo)準(zhǔn)的代幣合約
* 代幣名稱 MyToken,符號 MTK,總量:1000MTK
* 方法:鑄造,銷毀,轉(zhuǎn)賬,授權(quán)...
*/

合約編譯

# 編譯合約指令
npx hardhat compile

合約測試

# 合約測試指令
npx hardhat test

合約測試樣例

說明:hardhat框架集成了chai測試的工具

const { ethers,getNamedAccounts,deployments} = require("hardhat");
const {assert,expect } = require("chai");
let firstAccount;
let nft;
// 部署合約
beforeEach(async function () {
  firstAccount = (await getNamedAccounts()).firstAccount;
  await deployments.fixture(["all"]);
  nft=await ethers.getContract("MyNFT",firstAccount);
});
// 測試單元 參數(shù)說明:測試單元命名
describe("xxx", async () => {
  it("mint nft", async function () {
    await nft.safeMint(firstAccount);
    let owner=await nft.ownerOf(0);
    expect(owner).to.equal(firstAccount);
  });
//.........
});

合約部署指令

# 部署合約
# 說明:部署一個在scripts目錄下的deploy.js 網(wǎng)絡(luò)節(jié)點
# network-name可以在hardhat.json中配置網(wǎng)絡(luò):localhost,
npx hardhat run scripts/xxx.js --network <network-name>
# 例如
npx hardhat run scripts/deploy.js 
 or 
npx hardhat run scripts/deploy.js --network localhost//指定網(wǎng)絡(luò)

合約部署樣例1

# 直接在scripts目錄下編寫部署腳本
const { ethers } = require("hardhat");

async function main() {
    const [deployer] = await ethers.getSigners();//獲取網(wǎng)絡(luò)節(jié)點賬號
    // console.log(deployer)
    console.log("Deploying contracts with the account:", deployer.address);
    const MyToken = await ethers.getContractFactory("MyToken");//獲取合約
    console.log(MyToken)//獲取合約實例
    const myToken = await MyToken.deploy();//部署合約
    console.log("Token address:", myToken.target);//打印合約地址

}
main().then(()=>{
    process.exit(0)
}).catch((err)=>{
console.error(err)
process.exit(1)
});
# 使用指令
npx hardhat run scripts/xxx.js --network 指定網(wǎng)絡(luò)節(jié)點

合約部署樣例2

# 在deploy目錄下部署腳本(推薦此操作)
# 使用hardhat部署插件hardhat-deploy
#1 在配置文件hardhat.confing.js中引入插件
require("hardhat-deploy");
require("@nomicfoundation/hardhat-ethers");
require("hardhat-deploy-ethers");
# 在deploy目錄下的部署文件:
// module.exports = async (hre) => {
//     const getNamedAccounts = hre.getNamedAccounts
//     const deployments = hre.deployments
//  }
const { network } =require("hardhat");

 module.exports = async ({getNamedAccounts,deployments}) => {
    const firstAccount = (await getNamedAccounts()).firstAccount;//獲取節(jié)點1
    const secondAccount = (await getNamedAccounts()).secondAccount;//獲取節(jié)點2
    const {deploy}= deployments//獲取部署實例
//部署合約
    const FundMe= await deploy("FundMe",{
        from: firstAccount,//節(jié)點
        args: [xx,xxx],//要傳的參數(shù)xx,xxx
        log: true,//是否打印log
        //waitConfirmations: confirmations,//等待的區(qū)塊數(shù)
    })
  //驗證合約是否成功的部署的鏈上
        await hre.run("verify:verify", {
            address: FundMe.address,
            constructorArguments: [xx,xxx],//合約要傳的參數(shù)xx,xxx
            });
 }
 module.exports.tags = ["all","fundme"];//在執(zhí)行部署指令時可選參數(shù)
# 例如
npx hardhat deploy --tag fundme or all
# 等同于
npx hardhat run scripts/funfme.js

自定義task樣例

# 說明
# 文件目錄
tasks
  |_deploy_nft.js
  |_index.js
  |_ deploy_tonken.js  
# deploy_nft.js代碼如下
const {task} = require("hardhat/config");//hardhat集成的插件
//參數(shù)說明,deploy-nft是指令名
task("deploy-fundme", "deploy-fundme").setAction(async (taskArgs, hre) => {
  const FundMeFactory = await ethers.getContractFactory("MyNFT");//獲取合約
  const fundMe = await FundMeFactory.deploy(300);//部署需要傳遞的參數(shù)
  await fundMe.waitForDeployment();//幾個區(qū)塊
  console.log(`address : ${fundMe.target}`)
  if(hre.network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY){
      console.log("Waiting for 5 confirmations")
      await fundMe.deploymentTransaction().wait(5) //等待5個區(qū)塊交易完成
      await verifyFundMe(fundMe.target, [300])
  }else{
      console.log("verification skipped..")
  }

});
async function verifyFundMe(factoryAddr,args){
  await hre.run("verify:verify", {
      address: factoryAddr,
      constructorArguments: [50],
      });
}
exports.default = {};
# deploy_token.js代碼同上簡單修改代碼即可
# index.js如下
exports.deployfundme=require("./deploy_nft.js")
exports.interactfundme=require("./deploy_token.js")
把自定task引入hardhat.config.js中
require(./tasks);
# 可以通過npx hardhat 查看是否生成
# 導(dǎo)入成功后
可以在控制臺面板中的AVAILABLE TASKS查看到
# deploy-token
npx hardhat deploy-fundme --network xxx  //如果有參數(shù)傳遞就后面跟參數(shù) 鍵名 鍵值
# deploy-nft 
同上修改一下關(guān)鍵參數(shù)即可

hardhat.config.js文件配置

require("@nomicfoundation/hardhat-toolbox");
require("@nomicfoundation/hardhat-verify");//驗證合約
// require("@chainlink/env-enc").config();//可以采用此包對.env常量進行加密處理
require("dotenv").config();//讀取.env的內(nèi)容
require("./tasks");//自定義task,作用主要快加高效的執(zhí)行自定指令,便于高效的開發(fā)。
//引入部署插件
require("hardhat-deploy");
require("@nomicfoundation/hardhat-ethers");
require("hardhat-deploy-ethers");
//讀取env的常量
process.env.PRIVATE_KEY = process.env.PRIVATE_KEY;
process.env.PRIVATE_KEY_1 = process.env.PRIVATE_KEY_1;
process.env.ALCHEMY_API_KEY = process.env.ALCHEMY_API_KEY;
process.env.ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY;
module.exports = {
  solidity: "0.8.27",
  defaultNetwork: "hardhat",
  mocha: {
    timeout: 300000//設(shè)置mocha的超時時間為300秒,解決集成測試時間不夠問題
  },
  networks: {
    // localhost: {
    //   url:'http://127.0.0.1:8545/',
    //   chainId: 31337,
    // },
    sepolia: {
      url: `https://sepolia.infura.io/v3/${process.env.ALCHEMY_API_KEY}`,
      accounts: [process.env.PRIVATE_KEY,process.env.PRIVATE_KEY_1],
      chainId: 11155111
    },
  },//網(wǎng)絡(luò)節(jié)點設(shè)置
  etherscan: {
    apiKey: {
      sepolia: process.env.ETHERSCAN_API_KEY
    }
  },//設(shè)置 Etherscan API 密鑰的,用于與 Etherscan 服務(wù)進行交互
  sourcify: {
    enabled: true
  },//啟動 Hardhat 插件 @nomicfoundation/hardhat-verify,用戶驗證部署在以太坊區(qū)塊鏈上的智能合約的源代碼
  namedAccounts: {
    firstAccount: {
      default: 0
    },
    secondAccount: {
      default: 1
    }
  },//通過名字獲取區(qū)塊節(jié)點
  gasReporter: {
    enabled: false,//控制gas報告的顯示
  }
};

前端調(diào)用合約

# 前端主要通過Ethers.js或者Web3.js和合約進行交互。
#關(guān)于Ehers.js庫的使用。
* Provider:提供者
* Signer:簽名者
* Contract:用于合約的獲取
* 其他(單位轉(zhuǎn)換,)
# 前端獲取合約
import myToken  from "../json/MyToken.json";//不是之后生成的json文件
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider();//獲取provider 
let TokenAddress="0x......"http://合約地址
let signer=await provider.signer();//獲取簽名
# 獲取合約 參數(shù):合約地址 合約abi,簽名如果是signer可讀寫,provider可讀
const contractWETH = new ethers.Contract(TokenAddress, myToken.abi, signer);
# 獲取合約后進行交互操作

插件篇

# 推薦工具
# hardhat-deploy合約部署相關(guān)的插件
# hardhat-gas-reporter部署合約后會生成一個gas費的報告文件

總結(jié)

以上就是使用hardhat構(gòu)建工具,把編寫的智能合約從開發(fā),測試,部署上鏈的整個流程。

  • 使用內(nèi)嵌測試包chai,快速驗證合約的可行性;
  • 使用到了hardhat-deploy插件,實現(xiàn)快速部署合約;
  • 使用@nomicfoundation/hardhat-verify,驗證合約是否成功上鏈;
  • 以及合約部署gas費消耗分析報告hardhat-gas-reporter。便于優(yōu)化合約;
  • 通過自定task,提高開發(fā)效率;
  • 開發(fā)中還會用到預(yù)言機chainlink相關(guān)的方法
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容