code-423n4 / 2022-04-backd-findings

6 stars 4 forks source link

Gas Optimizations #135

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Save gas in for loops by unchecked arithmetic

The for loop has no overflow risk of i. Use an unchecked block to save gas.

Proof of Concept

access/RoleManager.sol
80:        for (uint256 i = 0; i < roles.length; i++) {

strategies/ConvexStrategyBase.sol
313:        for (uint256 i = 0; i < _rewardTokens.length(); i++) {
380:        for (uint256 i = 0; i < _rewardTokens.length(); i++) {

BkdLocker.sol
310:            for (uint256 i = 0; i < length; i++) {

StakerVault.sol
260:        for (uint256 i = 0; i < actions.length; i++) {

testing/MockStableSwap.sol
30:        for (uint256 i = 0; i < 3; i++) {
42:        for (uint256 i = 0; i < 2; i++) {
70:        for (uint256 i = 0; i < 3; i++) {

Controller.sol
117:        for (uint256 i = 0; i < numActions; i++) {

actions/topup/TopUpAction.sol
188:        for (uint256 i = 0; i < protocols.length; i++) {
456:        for (uint256 i = 0; i < length; i++) {
479:        for (uint256 i = 0; i < length; i++) {
506:        for (uint256 i = 0; i < howMany; i++) {
891:        for (uint256 i = 0; i < length; i++) {

actions/topup/handlers/CTokenRegistry.sol
61:        for (uint256 i = 0; i < ctokens.length; i++) {

actions/topup/handlers/CompoundHandler.sol
135:        for (uint256 i = 0; i < assets.length; i++) {

actions/topup/TopUpKeeperHelper.sol
43:            for (uint256 i = 0; i < users.length; i++) {
46:                for (uint256 j = 0; j < positions.length; j++) {
72:        for (uint256 i = 0; i < keys.length; i++) {
93:        for (uint256 i = 0; i < length; i++) {
165:        for (uint256 i = 0; i < length; i++) {

tokenomics/VestedEscrow.sol
93:        for (uint256 i = 0; i < amounts.length; i++) {

tokenomics/KeeperGauge.sol
155:        for (uint256 i = startEpoch; i < endEpoch; i++) {

tokenomics/InflationManager.sol
91:        for (uint256 i = 0; i < length; i++) {
105:        for (uint256 i = 0; i < length; i++) {
109:        for (uint256 i = 0; i < stakerVaults.length; i++) {
114:        for (uint256 i = 0; i < length; i++) {
166:        for (uint256 i = 0; i < length; i++) {
191:        for (uint256 i = 0; i < length; i++) {
259:        for (uint256 i = 0; i < length; i++) {
283:        for (uint256 i = 0; i < length; i++) {
357:        for (uint256 i = 0; i < length; i++) {
381:        for (uint256 i = 0; i < length; i++) {
404:        for (uint256 i = 0; i < length; i++) {
445:        for (uint256 i = 0; i < length; i++) {

Recommendation

Use unchecked blocks to avoid overflow checks, or use ++i rather than i++ if you don't use unchecked blocks.

for (uint256 i = 0; i < length; ) {
    ...
    unchecked {
        ++i;
    }
}