code-423n4 / 2021-07-sherlock-findings

0 stars 0 forks source link

Avoid repeating storage reads in a loop to save gas #149

Open code423n4 opened 3 years ago

code423n4 commented 3 years ago

Handle

shw

Vulnerability details

Impact

A storage read cost more gas than a memory read. State variables that do not change during a loop can be stored in local variables and be read from memory multiple times to save gas.

Proof of Concept

Referenced code: LibPool.sol#L89 LibSherX.sol#L60 LibSherX.sol#L94 PoolBase.sol#L131 SherX.sol#L76 SherX.sol#L98 SherX.sol#L152 SherX.sol#L184 SherX.sol#L243 Gov.sol#L190

Recommended Mitigation Steps

For example, consider re-writing the harvestFor(address) function of SherX as follows:

function harvestFor(address _user) public override {
  GovStorage.Base storage gs = GovStorage.gs();
  uint256 len = gs.tokensStaker.length;
  for (uint256 i; i < len; i++) {
    PoolStorage.Base storage ps = PoolStorage.ps(gs.tokensStaker[i]);
    harvestFor(_user, ps.lockToken);
  }
}
Evert0x commented 3 years ago

Interesting, my assumption was that loops were copying the .length variable in memory automatically.