Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas Optimizations #44

Open
code423n4 opened this issue May 14, 2022 · 0 comments
Open

Gas Optimizations #44

code423n4 opened this issue May 14, 2022 · 0 comments
Labels
bug Something isn't working G (Gas Optimization) sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons

Comments

@code423n4
Copy link
Contributor

Boolean variables can be checked within conditionals directly without the use of equality operators to true/false.

Code instances:

    ArbitartorVault.sol, 54: require(shutdown==false,"pool closed");
    VoterProxy.sol, 168: if(protectedTokens[_token] == false){
    VoterProxy.sol, 107: require(operator == address(0) || IDeposit(operator).isShutdown() == true, "needs shutdown");
    VoterProxy.sol, 171: if(protectedTokens[_gauge] == false){
    AuraMerkleDrop.sol, 123: require(hasClaimed[msg.sender] == false, "already claimed");

State variables that could be set immutable

In the following files there are state variables that could be set immutable to save gas.

Code instances:

    smart_wallet_checker in MockCurveVoteEscrow.sol
    poolToken in MockBalancerVault.sol
    rate in MockCurveMinter.sol
    token in MockCurveVoteEscrow.sol

Unused state variables

Unused state variables are gas consuming at deployment (since they are located in storage) and are
a bad code practice. Removing those variables will decrease deployment gas cost and improve code quality.
This is a full list of all the unused storage variables we found in your code base.

Code instances:

    ConvexMasterChef.sol, BONUS_MULTIPLIER
    RewardFactory.sol, rewardActiveList

Unused declared local variables

Unused local variables are gas consuming, since the initial value assignment costs gas. And are
a bad code practice. Removing those variables will decrease the gas cost and improve code quality.
This is a full list of all the unused storage variables we found in your code base.

Code instances:

    AuraLocker.sol, constructor, currentEpoch
    AuraLocker.sol, _checkpointEpoch, nextEpochDate

Caching array length can save gas

Caching the array length is more gas efficient.
This is because access to a local variable in solidity is more efficient than query storage / calldata / memory.
We recommend to change from:

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

to:

uint len = array.length  
for (uint256 i=0; i<len; i++) { ... }

Code instances:

    BaseRewardPool.sol, extraRewards, 230
    AuraClaimZap.sol, tokenRewardContracts, 151
    Booster.sol, poolInfo, 379
    MockFeeDistro.sol, _tokens, 19
    AuraLocker.sol, locks, 696

Prefix increments are cheaper than postfix increments

Prefix increments are cheaper than postfix increments.
Further more, using unchecked {++x} is even more gas efficient, and the gas saving accumulates every iteration and can make a real change
There is no risk of overflow caused by increamenting the iteration index in for loops (the ++i in for (uint256 i = 0; i < numIterations; ++i)).
But increments perform overflow checks that are not necessary in this case.
These functions use not using prefix increments (++x) or not using the unchecked keyword:

Code instances:

    just change to unchecked: ConvexMasterChef.sol, pid, 180
    change to prefix increment and unchecked: PoolManagerSecondaryProxy.sol, i, 69
    change to prefix increment and unchecked: MockCurveGauge.sol, i, 36
    change to prefix increment and unchecked: ArbitartorVault.sol, i, 49
    change to prefix increment and unchecked: MockFeeDistro.sol, i, 38

Unnecessary index init

In for loops you initialize the index to start from 0, but it already initialized to 0 in default and this assignment cost gas.
It is more clear and gas efficient to declare without assigning 0 and will have the same meaning:

Code instances:

    AuraClaimZap.sol, 147
    AuraClaimZap.sol, 151
    ExtraRewardStashV3.sol, 199
    AuraClaimZap.sol, 143
    AuraLocker.sol, 773

Storage double reading. Could save SLOAD

Reading a storage variable is gas costly (SLOAD). In cases of multiple read of a storage variable in the same scope, caching the first read (i.e saving as a local variable) can save gas and decrease the
overall gas uses. The following is a list of functions and the storage variables that you read twice:

Code instances:

    ConvexMasterChef.sol: endBlock is read twice in getMultiplier
    Booster.sol: lockRewards is read twice in setFeeInfo

Unnecessary default assignment

Unnecessary default assignments, you can just declare and it will save gas and have the same meaning.

Code instances:

    AuraLocker.sol (L#72) : uint256 public queuedCvxCrvRewards = 0;
    BaseRewardPool.sol (L#76) : uint256 public currentRewards = 0;
    AuraBalRewardPool.sol (L#39) : uint256 public rewardRate = 0;
    CrvDepositor.sol (L#36) : uint256 public incentiveCrv = 0;
    AuraMerkleDrop.sol (L#29) : uint256 public pendingPenalty = 0; 

Rearrange state variables

You can change the order of the storage variables to decrease memory uses.

Code instances:

In CrvDepositor.sol,rearranging the storage fields can optimize to: 12 slots from: 13 slots.
The new order of types (you choose the actual variables):
1. uint256
2. uint256
3. uint256
4. uint256
5. uint256
6. uint256
7. address
8. bool
9. address
10. address
11. address
12. address
13. address

In BoosterOwner.sol,rearranging the storage fields can optimize to: 8 slots from: 9 slots.
The new order of types (you choose the actual variables):
1. uint256
2. uint256
3. address
4. bool
5. bool
6. address
7. address
8. address
9. address
10. address

In AuraVestedEscrow.sol,rearranging the storage fields can optimize to: 6 slots from: 7 slots.
The new order of types (you choose the actual variables):
1. IERC20
2. IAuraLocker
3. uint256
4. uint256
5. uint256
6. address
7. bool

In AuraLocker.sol,rearranging the storage fields can optimize to: 13 slots from: 15 slots.
The new order of types (you choose the actual variables):
1. uint256
2. uint256
3. uint256
4. uint256
5. uint256
6. IERC20
7. uint256
8. uint256
9. uint256
10. string
11. string
12. address
13. uint8
14. bool
15. address

Short the following require messages

The following require messages are of length more than 32 and we think are short enough to short
them into exactly 32 characters such that it will be placed in one slot of memory and the require
function will cost less gas.
The list:

Code instance:

    Solidity file: AuraLocker.sol, In line 197, Require message length to shorten: 33, The message: Cannot add StakingToken as reward

Use != 0 instead of > 0

Using != 0 is slightly cheaper than > 0. (see code-423n4/2021-12-maple-findings#75 for similar issue)

Code instances:

    CrvDepositor.sol, 175: change 'incentiveCrv > 0' to 'incentiveCrv != 0'
    AuraClaimZap.sol, 196: change 'depositCrvMaxAmount > 0' to 'depositCrvMaxAmount != 0'
    AuraBalRewardPool.sol, 121: change '_amount > 0' to '_amount != 0'
    AuraLocker.sol, 400: change '_checkDelay > 0' to '_checkDelay != 0'
    AuraLocker.sol, 419: change '_checkDelay > 0' to '_checkDelay != 0'

Unnecessary cast

Code instances:

    uint256 AuraLocker.sol.balanceAtEpochOf - unnecessary casting uint256(_epoch)
    uint256 AuraLocker.sol.totalSupplyAtEpoch - unnecessary casting uint256(_epoch)
    IERC20 ClaimFeesHelper.sol.claimFees - unnecessary casting IERC20(_token)

Use unchecked to save gas for certain additive calculations that cannot overflow

You can use unchecked in the following calculations since there is no risk to overflow:

Code instances:

    AuraMinter.sol (L#23) - inflationProtectionTime = block.timestamp + 156 weeks;
    MockCurveVoteEscrow.sol (L#42) - require(unlockTime < block.timestamp + MAX_LEN, "Lock too long");
    BoosterOwner.sol (L#163) - forceTimestamp = block.timestamp + FORCE_DELAY; 
    CrvDepositor.sol (L#94) - uint256 unlockAt = block.timestamp + MAXTIME;
    CrvDepositor.sol (L#127) - uint256 unlockAt = block.timestamp + MAXTIME;

Consider inline the following functions to save gas

You can inline the following functions instead of writing a specific function to save gas.
(see https://github.com/code-423n4/2021-11-nested-findings/issues/167 for a similar issue.)

Code instances

    MathUtil.sol, min, { return a < b ? a : b; }
    AuraClaimZap.sol, _checkOption, { return (_mask & (1 << _flag)) != 0; }
    AuraLocker.sol, _lastTimeRewardApplicable, { return AuraMath.min(block.timestamp, _finishTime); }
    MockVoteStorage.sol, hashStr, { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", uint2str(bytes(str).length), str)); }

Inline one time use functions

The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.

Code instances:

    BaseRewardPool.sol, _withdrawAndUnwrapTo
    MockVoteStorage.sol, payloadStr
    AuraLocker.sol, _checkpointsLookup
    Booster.sol, _earmarkRewards
    VoterProxy.sol, _withdrawSome

Upgrade pragma to at least 0.8.4

Using newer compiler versions and the optimizer gives gas optimizations
and additional safety checks are available for free.

The advantages of versions 0.8.* over <0.8.0 are:

    1. Safemath by default from 0.8.0 (can be more gas efficient than library based safemath.)
    2. Low level inliner : from 0.8.2, leads to cheaper runtime gas. Especially relevant when the contract has small functions. For example, OpenZeppelin libraries typically have a lot of small helper functions and if they are not inlined, they cost an additional 20 to 40 gas because of 2 extra jump instructions and additional stack operations needed for function calls.
    3. Optimizer improvements in packed structs: Before 0.8.3, storing packed structs, in some cases used an additional storage read operation. After EIP-2929, if the slot was already cold, this means unnecessary stack operations and extra deploy time costs. However, if the slot was already warm, this means additional cost of 100 gas alongside the same unnecessary stack operations and extra deploy time costs.
    4. Custom errors from 0.8.4, leads to cheaper deploy time cost and run time cost. Note: the run time cost is only relevant when the revert condition is met. In short, replace revert strings by custom errors.

Code instances:

    ExtraRewardStashV3.sol
    ProxyFactory.sol
    IERC4626.sol
    IRewardHook.sol
    BaseRewardPool.sol

Do not cache msg.sender

We recommend not to cache msg.sender since calling it is 2 gas while reading a variable is more.

Code instances:

    https://github.com/code-423n4/2022-05-aura/tree/main/contracts/BalLiquidityProvider.sol#L37
    https://github.com/code-423n4/2022-05-aura/tree/main/convex-platform/contracts/contracts/Booster.sol#L108
    https://github.com/code-423n4/2022-05-aura/tree/main/convex-platform/contracts/contracts/cCrv.sol#L32
    https://github.com/code-423n4/2022-05-aura/tree/main/convex-platform/contracts/contracts/PoolManagerSecondaryProxy.sol#L43
    https://github.com/code-423n4/2022-05-aura/tree/main/convex-platform/contracts/contracts/PoolManagerProxy.sol#L29
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels May 14, 2022
code423n4 added a commit that referenced this issue May 14, 2022
@0xMaharishi 0xMaharishi added the sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons label May 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working G (Gas Optimization) sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons
Projects
None yet
Development

No branches or pull requests

2 participants