The ModuleKit has an inbuilt helper to granularly calculate the gas costs of UserOperations. For example, it calculates the gas costs of the various phases of the ERC-4337 flow and L2-L1 calldata gas.
Before using this utility, create a folder called gas_calculations
in the root folder of the directory (same level as the src
folder) and ensure that you have the right permissions settings set in your foundry.toml
file:
In the test function(s) that you want to perform, call instance.log4337Gas("identifier")
before a UserOperation
is executed. This will log the gas used for the UserOperation
and use the identifier as the filename for the gas report. Make sure to use a unique identifier for each UserOp, otherwise the gas reports will be overwritten. For example:
To run the tests and log gas, run the following command:
After the tests have finished, the gas reports will be written to the gas_calculations
folder in the root of the project. A gas report will look like this:
Note that if you re-run gas calculations, then the newest number will be added and every value will be followed by a (diff: ...)
that shows the difference, in gas units between the calculations.
All numbers are in gas units. To calculate the cost in gwei, follow the instructions below:
totalGasUsed * gasPrice
totalGasUsed * l2GasPrice + callDataGasUsed * l1GasPrice
Note: if you are calculating the dollar amount of the gas cost, make sure to use the relevant gwei to usd conversions if the L2 has a different gas token to L1.