A reader submitted an interesting feature request last week in Discord, asking for the ability to manipulate the ERC20 token balance for a given address through AnvilFork
.
If you don’t know about forking, or the history of the AnvilFork
helper class, I recommend reading these two posts:
The feature request sounded interesting and useful, so I took it on.
It was immediately clear that the feature was too complex to assign completely to the fork helper. Rather than jam a bunch of loosely-related functionality into a single method, it would be better to implement the storage manipulation methods on the fork helper and build application-specific helper functions to facilitate deciphering storage slots for a given contract.
The techniques demonstrated below will be applicable for contracts of all kinds, but the specific example assumes that we are investigating a a token contract meeting a typical ERC-20 specification.
Storage Manipulation
The storage manipulation was simple: I implemented a set_storage method for accessing Anvil’s underlying anvil_setStorageAt endpoint.
NOTE: An ERC-20 token typically stores the balance for holders in a hash map. The balances are mapped to the keccak hash of the byte concatenation of the holder address and the storage slot where the mapping appears.
Here’s a demonstration verifying the balance returned by the mainnet WETH contract against a manual storage lookup using the balance mapping storage slot (3) and the address for the Uniswap V4 PoolManager: