Forked Networks 
###############

What is Forking 
===============

Forking is the process of creating a local copy of a network at a specific block height. There is a bit of "magic" to it, because we don't *really* download the whole blockchain locally, but as long as you have a connection to a node (like for example, via an RPC) you can fork a network.

It's incredibly helpful for testing, because it allows you to simulate what could/would happen on a live network when you run a script or send a transaction. 

.. note::

    However, you don't want to blindly trust simulations or the outcome of forked tests. In the real world, people can send transactions to the network while your script is in flight and mess with your scripting!

Forking 
=======

In testing, forking is an essential part of the development process. **Any script that you want to run on a live network you should be running on a forked network first!** In moccasin, forking is a first class citizen.

.. code-block:: toml

    [networks.sepolia]
    url = "https://ethereum-sepolia-rpc.publicnode.com"
    chain_id = 11155111
    fork = true 

Running a script with this setup will run your script locally, but pretending to be on the ``sepolia`` network, with contracts and everything! 

It essentially does some "lazy loading", where it'll only download information from the blockchain if/when you need. For example, if you want to get the balance of an account, it'll only download the balance of that account when your script calls for it.

You can also take any non-forked network and run a forked test just by adding the ``--fork`` flag to the command line. 

.. code-block:: toml

    [networks.sepolia]
    url = "https://ethereum-sepolia-rpc.publicnode.com"
    chain_id = 11155111
    fork = false 


You can fork at a specific block by specifying a ``block_identifier``, which can be either an integer or one of the preset options:  ``safe`` (default), ``latest``, ``earliest``, ``pending``, ``finalized``

.. code-block:: toml

    [networks.sepolia]
    url = "https://ethereum-sepolia-rpc.publicnode.com"
    chain_id = 11155111
    is_fork = false
    block_identifier = 7582167

Forked network defaults 
========================

.. literalinclude::  ../../_autogenerated/fork_defaults.rst
    
