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

0 stars 0 forks source link

`Basket.sol#approveUnderlying()` Cache and read storage variables from the stack can save gas #100

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

WatchPug

Vulnerability details

For the storage variables that will be accessed multiple times, cache and read from the stack can save ~100 gas from each extra read (SLOAD after Berlin).

For example:

https://github.com/code-423n4/2021-12-defiprotocol/blob/205d3766044171e325df6a8bf2e79b37856eece1/contracts/contracts/Basket.sol#L274-L279

function approveUnderlying(address spender) private {
        for (uint256 i = 0; i < weights.length; i++) {
            IERC20(tokens[i]).safeApprove(spender, 0);
            IERC20(tokens[i]).safeApprove(spender, type(uint256).max);
        }
    }

tokens[i] can be cached.

Recommendation

Change to:

function approveUnderlying(address spender) private {
        for (uint256 i = 0; i < weights.length; i++) {
            IERC20 token = IERC20(tokens[i]);
            token.safeApprove(spender, 0);
            token.safeApprove(spender, type(uint256).max);
        }
    }