Hardhat 教學

類似 Truffle 為一個智能合約開發 SDK。

安裝與初始化

專案結構

必須照著官方規定取名資料夾,分別為放合約以及部署script,與測試檔案,以及網路等 config。

https://hardhat.org/guides/project-setup.html#sample-hardhat-project

在本地測試與部屬

  1. 啟動本地節點

[可選] 如果沒有啟動節點與指定節點,預設都會使用 in-memory instance of Hardhat Network

2.部署合約

3.使用 console 測試功能

之後輸入

寫測試檔案

test/test.js

之後輸入

Artifacts

部署合約或 compile 後會產生此資料夾,裡面包含一些 json 檔案,為合約的 ABI

使用 Mainnet fork 測試

使用 mainnet 特定 block data 來測試合約

https://hardhat.org/hardhat-network/docs/guides/forking-other-networks

設置 hardhat.config.js 即可

之後可獲取當前主網地址餘額

貼上以下檔案到 /test 後,輸入 `npx hardhat test`

或是以下獲取主網特定地址的 USDC 餘額

測試檔案內設置區塊時間

部署合約

要先去 hardhat.config.ts 檔案設置網路設置

部署腳本 scripts/deploy.ts

之後輸入

https://github.com/wighawag/hardhat-deploy#hardhat-deploy-in-a-nutshell

Etherscan 驗證合約

設置hardhat config

不同網路有不同的 api key

之後輸入以下

測試單一檔案

可使用:https://hardhat.org/plugins/hardhat-watcher.html

會監聽檔案改變,自動跑測試,並且可在 config 寫要執行哪個檔案

相關連結

範例專案:https://github.com/symfoni/hardhat-react-boilerplate

常見問題

1.Error: call revert exception

2.Error HH12: Trying to use a non-local installation of Hardhat

3.TypeError: unsupported addressable value (argument="target", value=null, code=INVALID_ARGUMENT, version=6.11.1)

v6 之後要用 .target 取代 .address

Last updated

Was this helpful?