Cyfrin / 2023-07-foundry-defi-stablecoin

37 stars 32 forks source link

Cache state variables instead of rereading #1058

Closed codehawks-bot closed 1 year ago

codehawks-bot commented 1 year ago

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:

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