【工具使用】利用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

posted @ 2021-12-03 20:06  ACai_sec  阅读(1269)  评论(0编辑  收藏  举报