【工具使用】利用ganache-cli本地fork以太坊主鏈分叉


前言

Fork主網意思是模擬具有與主網相同的狀態的網絡,但它將作為本地開發網絡工作。 這樣你就可以與部署的協議進行交互,並在本地測試復雜的交互。不用擔心分叉主網作為測試鏈會占很多內存。這些方法都不會將主網信息全部下載到本地,最多進行緩存,加快處理速度。所有關於主網的信息,都會通過 Provider 進行查詢,只有新的區塊會保存在本地。

所需要用到的工具,具體的安裝過程在這篇文章中就不展開,請讀者自行安裝:

  • ganache-cli
  • remix
  • matemask
  • alchemy

Fork以太鏈分叉

首先,去alchemy申請一個賬號,獲取alchemy provider,如下圖所示。
image

然后在ganache-cli的github上可以找到他的參數調用方法:https://github.com/trufflesuite/ganache-cli-archive
其中關於fork分叉的描述為:

-f or --fork: Fork from another currently running Ethereum client at a given block. Input should be the HTTP location and port of the other client, e.g. http://localhost:8545. You can optionally specify the block to fork from using an @ sign: http://localhost:8545@1599200.

我們可以采用以下命令在本地fork以太坊分叉

ganache-cli --fork {alchemy provider}@{block number}

結果如下,現在已經成功fork了以太坊在區塊13730855時候的分叉
image

交互

根據cmd中最后一行給出的地址127.0.0.1:8545,將fork下來的分叉鏈添加到matemask上,其中鏈IDmatemask建議為1337
image
然后在cmd中挑選一個賬戶(初始金額為100ETH),將其添加到matemask的賬戶列表中。

添加賬戶 賬戶詳情

賬戶添加完成后,打開remix,當賬戶連接到ganache-cli鏈上時,選擇injectd Web3
image
在matemask上進行連接。

添加賬戶 賬戶詳情

連接成功,現在可以通過remix來操作賬戶與ganache-cli鏈進行交互了
image

隨機挑選一位幸運兒進行轉賬測試,成功!接下來就可以開始你的測試之旅了!
image

注意事項

當采用infure作為provider,會在進行交互階段報錯Project ID does not have access to archive state
解決方法:https://hardhat.org/hardhat-network/guides/mainnet-forking.html#project-id-does-not-have-access-to-archive-state

"Project ID does not have access to archive state"
When using Infura without the archival add-on, you will only have access to the state of the blockchain from recent blocks. To avoid this problem, you can use either a local archive node or a service that provides archival data, like Alchemy (opens new window).

言簡意賅就是:用Alchemy作為provider


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM