40,000 USDC
View results
Submission Details
Severity: gas

Cache repeat use state variables

Summary

Caching oft-called state variables in a function saves 97 gas (100 vs 3).

Vulnerability Details

In a function, when a variable is retrieved from storage, SLOAD opcode (100 gas) is used, which uses 100 gas per invocation. In comparision, for variables cached in the stack MLOAD (3 gas) is used for retrieval.

The Escrow.resolveDisplute() is most affected by this. The i_tokenContract is read 4 times in excess of the original read (400 gas), i_arbiterFee is read thrice in excess of first read (200 gas), i_buyer and i_seller both read 1 time in excess (100 gas each, 200 total). In total, ~800 gas can be saved per call to this function by first caching these variables.

Tools Used

Forge, Foundry Tooklit

Recommendation

Cache state variables at the function outset.

Support

FAQs

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