code-423n4 / 2021-12-vader-findings

0 stars 0 forks source link

`LiquidityBasedTWAP.getStaleVaderPrice()` Gas Optimization #155

Closed code423n4 closed 2 years ago

code423n4 commented 2 years ago

Handle

Dravee

Vulnerability details

Impact

SLOADs cost 2100 gas for first time reads of state variables and then 100 gas for repeated reads in the context of a transaction (post Berlin fork). MLOADs cost 3 gas units. Therefore, caching state variable in local variables for repeated reads saves gas.

Proof of Concept

If you look in this for-loop, you'll notice that the twapData and vaderPairs storage variables are accessed at each iteration and the resulting extracted value is then written in uint256[] memory pastLiquidityWeights, a memory variable. After that, pastLiquidityWeights is passed as a memory variable to the _calculateVaderPrice method.

Here, there aren't any reason to use SLOADs instead of MLOADs.

Notice that here and here, the SLOAD is indeed necessary.

Tools Used

VS Code

Recommended Mitigation Steps

Read the storage variable only once and store it in a local memory variable. Then use this memory variable instead.

jack-the-pug commented 2 years ago

Dup #15