How to configure `truffle test` to fork the main/rinkeby chain as its local chain?

The smart contract I want to unit test instantiates IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D). Obviously this contract does not exist on the local chain that is spawned by truffle test.

The solution seems to be to test on a local chain that is a fork of the main/rinkeby chain? How does one configure truffle test to run as such?

Thanks 😀

Edit 1

I have tried the following configuration, however it doesn’t work yet:

module.exports = {
    networks: {
        development: {
            fork: "https://eth-rinkeby.alchemyapi.io/v2/{myKey}",
            network_id: 4
        },
    }
}

It returns the following error:

$ npx truffle test
> Something went wrong while attempting to connect to the network. Check your network configuration.

Could not connect to your Ethereum client.
Please check that your Ethereum client:
    - is running
    - is accepting RPC connections (i.e., "--rpc" option is used in geth)
    - is accessible over the network
    - is properly configured in your Truffle configuration file (truffle-config.js)

Truffle v5.3.6 (core: 5.3.6)
Node v14.16.0

Edit 2

Filed in a Github issue on the trufflesuite/truffle repo in the meantime.

Answer

You can fork Rinkeby or the Mainnet pretty easily using Ganache-CLI. Read this article for a detailed explanation https://blockheroes.dev/test-smart-contracts-on-mainnet/

The simplest command is:

ganache-cli --fork https://eth-rinkeby.alchemyapi.io/v2/{myKey}

But you can personalize it by specifying:

  • the block number from where you want to fork
  • an address you want to unlock and from where you want to get funds
  • preferred network id etc..

ganache-cli --fork https://eth-rinkeby.alchemyapi.io/v2/{myKey} --unlock {wealthyAddress} --networkId 999

Make sure you keep this fork running on a separate window.

And the network configuration would look like this:

networks:{
  myfork: {
      host: "127.0.0.1",    
      port: 8545,           
      network_id: "999",    
 },
}

truffle test --network myfork

Attribution
Source : Link , Question Author : Maxime Dupré , Answer Author : Ioana Roceanu

Leave a Comment