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

By [0xshaw](https://paragraph.com/@0xshaw) · 2022-09-24

---

为什么要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的地址
    

![](https://storage.googleapis.com/papyrus_images/121e62393271bca3d10d382cdbf9ad4c72d6942d0d81a7cad8b34737dc81ca6d.png)

![](https://storage.googleapis.com/papyrus_images/40aa6b7ae7d26464dfaef7faa0333d464a37bd8d5194bef1649d13475ec2f4b7.png)

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客户端方式：

![](https://storage.googleapis.com/papyrus_images/685bdcd327e9af76e1a88f578b979afb136ccd572afc122ca529b39d860844c4.png)

![](https://storage.googleapis.com/papyrus_images/02a0d414864b1a9be9cfdfaee0a28fe3081b2cb8e198db6fbcc449f69097ffe1.png)

![](https://storage.googleapis.com/papyrus_images/3e7f0152f46cffac738050f5ef4ad4368ccd6410bcd1b45f5c738d70f6c1c63b.png)

![](https://storage.googleapis.com/papyrus_images/045c4902f174dc22d81a1c7a8638254601b3d9db014474a551b30711cca28666.png)

命令行方式：

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
    

![](https://storage.googleapis.com/papyrus_images/e1ef4d101d809092fc28f3607512c60bf9e423837f13dadc007598b700b334a9.png)

测试

    const Web3 = require('web3')
    const rpcURL = '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)
    })
    

欢迎关注Twitter：[https://twitter.com/ishawzuo](https://twitter.com/ishawzuo)

---

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