Open code423n4 opened 3 years ago
shw
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.
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
For example, consider re-writing the harvestFor(address) function of SherX as follows:
harvestFor(address)
SherX
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); } }
Interesting, my assumption was that loops were copying the .length variable in memory automatically.
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 ofSherX
as follows: