20,000 USDC
View results
Submission Details
Severity: gas
Valid

Using storage instead of memory for structs/arrays saves gas

Summary

When fetching data from a storage location, assigning the data to a memory variable causes all fields of the struct/array to be read from storage, which incurs a Gcoldsload (2100 gas) for each field of the struct/array. If the fields are read from the new memory variable, they incur an additional MLOAD rather than a cheap stack read. Instead of declearing the variable with the memory keyword, declaring the variable with the storage keyword and caching any fields that need to be re-read in stack variables, will be much cheaper, only incuring the Gcoldsload for the fields actually read. The only time it makes sense to read the whole struct/array into a memory variable, is if the full struct/array is being returned by the function, is being passed to a function that requires memory, or if the array/struct is being read from another memory array/struct

Vulnerability Details

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L117

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L238

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L249

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L296

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L363

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L367

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L441

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L467

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L552

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L606

https://github.com/Cyfrin/2023-07-beedle/blob/main/src/Lender.sol#L611

Tools Used

Manual

Recommendations

  1. Use storage for those structs/arrays.

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.