The instances below point to the second+ access of a state variable within a function. Caching of a state variable replaces each Gwarmaccess (100 gas) with a much cheaper stack read. Other less obvious fixes/optimizations include having local memory caches of state variable structs, or having local caches of state variable contracts/addresses.
Cache storage-based state variables in local memory-based variables appropriately to convert SLOADs to MLOADs and reduce gas consumption from 100 units to 3 units. than once for a function
Cache state variables instead of rereading
Severity
Gas Optimization / Informational
Relevant GitHub Links
https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/tree/main/src/DSCEngine.sol#L78
https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/tree/main/src/DSCEngine.sol#L80
https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/tree/main/src/DSCEngine.sol#L82
Summary
Vulnerability Details
The instances below point to the second+ access of a state variable within a function. Caching of a state variable replaces each Gwarmaccess (100 gas) with a much cheaper stack read. Other less obvious fixes/optimizations include having local memory caches of state variable structs, or having local caches of state variable contracts/addresses.
More detail see this.
There are
3
instances of this issue:DSCEngine.s_collateralTokens should be cached with local memory-based variable in DSCEngine.getAccountCollateralValue(address), It is called more than once:
DSCEngine.s_collateralDeposited should be cached with local memory-based variable in DSCEngine.getAccountCollateralValue(address), It is called more than once:
DSCEngine.i_dsc should be cached with local memory-based variable in DSCEngine._burnDsc(uint256,address,address), It is called more than once:
Impact
Tools Used
Recommendations
Cache storage-based state variables in local memory-based variables appropriately to convert SLOADs to MLOADs and reduce gas consumption from 100 units to 3 units. than once for a function