How does the ganache-cli --fork work?

I am trying to fork a chain with ganache for dry running transactions. But I still can't understand it exactly, so here are my questions :

Q1: does it download the whole blockchain? or just a minimal version only or not downloading at all?

Q2: does it continue to contact the original node for some data fetching after the fork?

I can't seem to find anything about these questions in the official docs.

Answers 2

  • It relies on an external source (fork from) for pre-fork information and then relies on its own block producer and append new blocks after the fork. It will continue to rely on the external source for information about the pre-fork state.

    You can use it to test interactions. For example, if you want to run unit tests that interact with a liquidity pool and you want the test to be as realistic as possible. You can fork a chain where these things already exist, then deploy your contract and run interaction scenarios.

    Hope it helps.

  • Ganache fork allows to rely on an external source to get past chain state. This allows to query necessary data, and only that. Think of it more as a light client.

    When the fork is created, it means that it will rely on the RPC for past state (a merkle root) that isn't available, however if some state is available here in ganache it will rely on it. So for example, upon startup it will seed 10 user addresses with 100 Eth each. Moving the funds around only affects the local state obviously. Each new block is just a signed state transition.

    A1: It doesn't download all, it only query the parts of the state that are required to execute a tx. If you want to interact with a contract, it will get the contract code.

    A2: Since it doesn't download blocks, it does continue to call the RPC whenever some past state is necessary and not available locally. The amount of past state that is stored locally is defined by the forkCacheSize parameter.

    Depending on which RPC you use it may be slow if you keep requesting lots of data. If you keep interacting with the same contracts over and over again, then data is already locally cached and nothing more is queried from the RPC.

    As for why on startup ganache can create a new block seeding 100 Eth to 10 addresses, well for dev purposes ganache has a special rule that makes such a block valid.

Related Questions