I am trying to fork the ethereum mainnet at a past block number on brownie. But I dont see any way to do that in the brownie docs .
1 Answer
To fork a blockchain with brownie, you actually just need to create a network that uses a forked blockchain or uses a forking command.
Option 1: The built-in forked chain
Brownie actually comes packed with a forked feature:
$ brownie networks list
Brownie - Python development framework for Ethereum
The following networks are declared:
Ethereum
├─Mainnet (Infura): mainnet
├─Ropsten (Infura): ropsten
├─Rinkeby (Infura): rinkeby
├─Goerli (Infura): goerli
└─Kovan (Infura): kovan
Ethereum Classic
├─Mainnet: etc
└─Kotti: kotti
Development
├─Ganache-CLI: development
└─Ganache-CLI (Mainnet Fork): mainnet-fork <- This is the network!!
It uses your Infura key to fork mainnet to a forked ganache instance.
Note: I have found more success using Alchemy
Option 2: Add a new network that uses a forking command (recommended)
You can optionally add a network that automatically forks a blockchain of your choice.
Run the following command:
brownie networks add development chain-name-fork cmd=ganache-cli host=http://127.0.0.1 fork=RPC_URL accounts=10 mnemonic=brownie port=8545
If you want to pin a specific block, add @<block_number>
brownie networks add development chain-name-fork cmd=ganache-cli host=http://127.0.0.1 fork=RPC_URL@123456 accounts=10 mnemonic=brownie port=8545
This will add a network called chain-name-fork
that will run on http://127.0.0.1
. You just need to pass it an RPC_URL
for the fork
parameter, of which blockchain it should fork.
*Note: If using ganache
, you can use any ganache-cli commands.
You can also do this with hardhat if you choose. The block pin parameter is --fork-block-number 11095000
Option 3: You fork a blockchain yourself, and just point to that
Maybe, you want to run a local hardhat node like so:
npx hardhat node --fork https://eth-mainnet.alchemyapi.io/v2/<key> --fork-block-number 11095000
You'll now have a local blockchain running. You can then add it with something like:
brownie networks add Ethereum ganache host=http://localhost:8545 chainid=1337
-
This was a great help, do you know how to "move ahead in time" using Brownie? IE move the blockchain ahead by 30 blocks for instance? Thanks– PearlMar 27 at 11:30
-
You can "time travel" with
chain.sleep(xx)
. For reference: eth-brownie.readthedocs.io/en/stable/… Mar 28 at 14:01