# 如何用Alchemy和Ganache Fork主链(eth/bsc)


By [vip668.eth](https://paragraph.com/@vip668) · 2022-09-26

---

为什么要fork主链？
-----------

简单说就是为了降低开发成本，用链上的数据和本地的账户，做一些开发测试等一系列操作。

准备工作
----

申请主网的api：去alchemy或者infura注册一个账户，申请主网的api，这里用alchemy举例：

·

注册账户：[https://auth.alchemyapi.io/signup](https://auth.alchemyapi.io/signup)

·

·

创建APP：[https://dashboard.alchemy.com/，随便填个名字，选择Ethereum](https://dashboard.alchemy.com/%EF%BC%8C%E9%9A%8F%E4%BE%BF%E5%A1%AB%E4%B8%AA%E5%90%8D%E5%AD%97%EF%BC%8C%E9%80%89%E6%8B%A9Ethereum) Mainnet，创建。

·

·

获取API：创建完成后，点VIEW KEY按钮，可以看到。这里用HTTPS的地址

Ganache客户端：[https://trufflesuite.com/ganache/，](https://trufflesuite.com/ganache/%EF%BC%8C%E8%BF%99%E6%98%AF%E4%B8%80%E4%B8%AA%E5%AE%A2%E6%88%B7%E7%AB%AF%EF%BC%8C%E4%B9%9F%E5%8F%AF%E4%BB%A5%E7%94%A8%E5%91%BD%E4%BB%A4%E8%A1%8C)下载完直接安装

Ganache CLI（命令行）：[https://github.com/trufflesuite/ganache-cli-archive](https://github.com/trufflesuite/ganache-cli-archive)

用npm install -g ganache-cli 或 yarn global add ganache-cli 安装都可以

配置
--

### Ganache客户端 和 命令行方式选一种就可以

Ganache客户端方式：命令行方式：

ganache-cli --fork [https://eth-mainnet.g.alchemy.com/v2/{你的key}@{区块高度}](https://eth-mainnet.g.alchemy.com/v2/%7B%E4%BD%A0%E7%9A%84key%7D@%7B%E5%8C%BA%E5%9D%97%E9%AB%98%E5%BA%A6%7D)

如果找不到ganache-cli命令，在安装cli的时候，能看到安装路径，可以cd到目录，运行ganache-cli

也可以将ganache-cli的bin目录添加到系统PATH中，如

vim ~/.bash\_profile  

  

添加，在安装ganache-cli时可以看到

export PATH=$PATH:/{你的ganache目录}/bin

  

保存退出,使文件生效

source ~/.bash\_profile测试

const Web3 = **require**('web3')const rpcURL = '[http://127.0.0.1:8545](http://127.0.0.1:8545)' _//Ganache本地配置的地址_const web3 = new Web3(rpcURL)const address = '0x6e9B9Ecc9f3B331F2E79629e87a6f1Ba7Fe8DEA0' _//钱包地址_

web3.eth.**getBalance**(address, (err, wei) => { 

    balance = web3.utils.**fromWei**(wei, 'ether') 

    console.**log**(balance)})

  

[https://mirror.xyz/0xshaw.eth/gBdeC\_rkdEGghoI4HDDwfw3c4lDNU0ZlCuR-m8iNw30](https://mirror.xyz/0xshaw.eth/gBdeC_rkdEGghoI4HDDwfw3c4lDNU0ZlCuR-m8iNw30)

---

*Originally published on [vip668.eth](https://paragraph.com/@vip668/alchemy-ganache-fork-eth-bsc)*
