code-423n4 / 2021-11-streaming-findings

0 stars 0 forks source link

Cache and read storage variables from the stack can save gas #232

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-11-streaming/blob/56d81204a00fc949d29ddd277169690318b36821/Streaming/src/Locke.sol#L33-L39

/// Accepts governorship
function acceptGov() public {
    require(pendingGov == msg.sender, "!pending");
    address old = gov;
    gov = pendingGov;
    emit NewGov(old, pendingGov);
}

pendingGov can be cached.

Recommendation

Change to:

/// Accepts governorship
function acceptGov() public {
    address _pendingGov = pendingGov;
    require(_pendingGov == msg.sender, "!pending");
    address old = gov;
    gov = _pendingGov;
    emit NewGov(old, _pendingGov);
}