前言
Fork主網意思是模擬具有與主網相同的狀態的網絡,但它將作為本地開發網絡工作。 這樣你就可以與部署的協議進行交互,並在本地測試復雜的交互。不用擔心分叉主網作為測試鏈會占很多內存。這些方法都不會將主網信息全部下載到本地,最多進行緩存,加快處理速度。所有關於主網的信息,都會通過 Provider 進行查詢,只有新的區塊會保存在本地。
所需要用到的工具,具體的安裝過程在這篇文章中就不展開,請讀者自行安裝:
- ganache-cli
- remix
- matemask
- alchemy
Fork以太鏈分叉
首先,去alchemy
申請一個賬號,獲取alchemy provider
,如下圖所示。
然后在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
時候的分叉
交互
根據cmd中最后一行給出的地址127.0.0.1:8545
,將fork下來的分叉鏈添加到matemask上,其中鏈ID
matemask建議為1337
。
然后在cmd中挑選一個賬戶(初始金額為100ETH),將其添加到matemask的賬戶列表中。


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


連接成功,現在可以通過remix來操作賬戶與ganache-cli鏈進行交互了
隨機挑選一位幸運兒進行轉賬測試,成功!接下來就可以開始你的測試之旅了!
注意事項
當采用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
。