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

0 stars 0 forks source link

Gas Optimizations #129

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

C4-001: Revert String Size Optimization

C4-002 : Adding unchecked directive can save gas

C4-003 : Check if amount > 0 before token transfer can save gas

C4-004 : There is no need to assign default values to variables

C4-005 : Free gas savings for using solidity 0.8.10+

C4-006 : Using operator && used more gas

C4-007 : Non-strict inequalities are cheaper than strict ones

C4-008 : Use Custom Errors instead of Revert Strings to save Gas

C4-009 : Use Shift Right/Left instead of Division/Multiplication if possible

C4-010 : Cache array length in for loops can save gas

C4-011 : State Variables that can be changed to immutable

C4-012 : Use calldata instead of memory for function parameters

C4-001: Revert String Size Optimization

Impact

Shortening revert strings to fit in 32 bytes will decrease deploy time gas and will decrease runtime gas when the revert condition has been met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead for computing memory offset, etc.

Proof of Concept

Revert strings > 32 bytes are here:

  ../2022-05-backd-main/protocol/libraries/Errors.sol::11 => string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::18 => string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::21 => string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::22 => string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::24 => "invalid pool implementation for given coin";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::26 => "invalid LP Token implementation for given coin";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::28 => "invalid vault implementation for given coin";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::30 => "invalid stakerVault implementation for given coin";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::33 => string internal constant INSUFFICIENT_AMOUNT_OUT = "Amount received less than min amount";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::34 => string internal constant INSUFFICIENT_AMOUNT_IN = "Amount spent more than max amount";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::47 => string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::51 => string internal constant CANNOT_EXECUTE_IN_SAME_BLOCK = "cannot execute action in same block";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::57 => "not enough funds were withdrawn from the pool";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::63 => string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::65 => "the minter address of the LP token and the pool address do not match";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::66 => string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::70 => string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::73 => "insufficient funds for updating the position";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::74 => string internal constant SAME_AS_CURRENT = "value must be different to existing value";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::80 => string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::84 => string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::89 => "pool does not support additional underlying coins to be withdrawn";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::95 => string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::99 => string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::100 => string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::103 => string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
  ../2022-05-backd-main/protocol/libraries/Errors.sol::105 => "Cannot relock funds when withdrawal is being prepared";

Tools Used

Manual Review

Recommended Mitigation Steps

Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.

C4-002 : Adding unchecked directive can save gas

Impact

For the arithmetic operations that will never over/underflow, using the unchecked directive (Solidity v0.8 has default overflow/underflow checks) can save some gas from the unnecessary internal over/underflow checks.

Proof of Concept

  ../2022-05-backd-main/protocol/contracts/zaps/PoolMigrationZap.sol::22 => for (uint256 i; i < newPools_.length; ++i) {

Tools Used

None

Recommended Mitigation Steps

Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.

Unchecked{i++};

C4-003 : Check if amount > 0 before token transfer can save gas

Impact

Since _amount can be 0. Checking if (_amount != 0) before the transfer can potentially save an external call and the unnecessary gas cost of a 0 token transfer.

Proof of Concept

./protocol/contracts/tokenomics/VestedEscrowRevocable.sol:10:- remove safeTransferFrom logic and add support for "airdropped" reward token
./protocol/contracts/tokenomics/VestedEscrowRevocable.sol:60:        rewardToken.safeTransferFrom(
./protocol/contracts/tokenomics/AmmConvexGauge.sol:162:        IERC20(ammToken).safeTransferFrom(msg.sender, address(this), amount);
./protocol/contracts/tokenomics/FeeBurner.sol:70:            token_.safeTransferFrom(msg.sender, address(this), tokenBalance_);
./protocol/contracts/tokenomics/VestedEscrow.sol:10:- remove safeTransferFrom logic and add support for "airdropped" reward token
./protocol/contracts/tokenomics/VestedEscrow.sol:146:        rewardToken.safeTransferFrom(holdingContract[msg.sender], _recipient, claimable);
./protocol/contracts/tokenomics/AmmGauge.sol:109:        IERC20(ammToken).safeTransferFrom(msg.sender, address(this), amount);

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider checking amount != 0.

C4-004 : There is no need to assign default values to variables

Impact - Gas Optimization

Boolean is default initialized to false. There is no need assign false to variable.

Proof of Concept

  protocol/contracts/tokenomics/InflationManager.sol::412 => bool keeperGaugeExists = false;

Tools Used

Code Review

Recommended Mitigation Steps

bool x = false costs more gas than bool x without having any different functionality.

C4-005 : Free gas savings for using solidity 0.8.13+

Impact

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

Proof of Concept

All Contracts

Solidity 0.8.14 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Solidity 0.8.13 has some improvements too but not well tested.

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider to upgrade pragma to at least 0.8.13.

C4-006 : Using operator && used more gas

Impact

Using double require instead of operator && can save more gas.

Proof of Concept

  1. Navigate to the following contracts.
protocol/contracts/tokenomics/AmmConvexGauge.sol:73:        if (amount <= 0 && crvAmount <= 0 && cvxAmount <= 0) return 0;
protocol/contracts/tokenomics/AmmConvexGauge.sol:107:        if (!killed && totalStaked > 0) {
protocol/contracts/tokenomics/AmmConvexGauge.sol:129:        if (!killed && totalStaked > 0) {
protocol/contracts/tokenomics/InflationManager.sol:420:        if (!keeperGaugeExists && weightBasedKeeperDistributionDeactivated && length >= 1) {
protocol/contracts/tokenomics/InflationManager.sol:426:        if (exists && !IKeeperGauge(keeperGauge).killed()) {
protocol/contracts/tokenomics/AmmGauge.sol:88:        if (!killed && totalStaked > 0) {

Tools Used

Code Review

Recommended Mitigation Steps

Example


using &&:

function check(uint x)public view{
require(x == 0 && x < 1 );
}
// gas cost 21630

using double require:

require(x == 0 );
require( x < 1);
}
}
// gas cost 21622

C4-007 : Non-strict inequalities are cheaper than strict ones

Impact

Strict inequalities add a check of non equality which costs around 3 gas.

Proof of Concept

  protocol/contracts/BkdLocker.sol::91 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/BkdLocker.sol::92 => require(totalLockedBoosted > 0, Error.NOT_ENOUGH_FUNDS);
  protocol/contracts/BkdLocker.sol::137 => require(length > 0, "No entries");
  protocol/contracts/BkdLocker.sol::139 => while (i > 0) {
  protocol/contracts/BkdLocker.sol::254 => if (userBalance > 0) {
  protocol/contracts/BkdLocker.sol::301 => if (userBalance > 0) {
  protocol/contracts/CvxCrvRewardsLocker.sol::174 => if (cvxcrvBal > 0) {
  protocol/contracts/CvxCrvRewardsLocker.sol::268 => if (IERC20(CVX_CRV).balanceOf(address(this)) > 0)
  protocol/contracts/LpToken.sol::87 => if (amount > 0) ILiquidityPool(minter).handleLpTokenTransfer(from, to, amount); // add check to not break 0 transfers
  protocol/contracts/RewardHandler.sol::63 => if (IERC20(token).allowance(address(this), spender) > 0) return;
  protocol/contracts/actions/topup/TopUpAction.sol::57 => if (depositAmount > 0) {
  protocol/contracts/actions/topup/TopUpAction.sol::67 => if (lockAmount > 0) {
  protocol/contracts/actions/topup/TopUpAction.sol::103 => if (IERC20(token).allowance(address(this), spender) > 0) return;
  protocol/contracts/actions/topup/TopUpAction.sol::214 => require(record.singleTopUpAmount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/actions/topup/TopUpAction.sol::535 => require(position.totalTopUpAmount > 0, Error.INSUFFICIENT_BALANCE);
  protocol/contracts/actions/topup/TopUpAction.sol::655 => if (position.depositTokenBalance > 0) {
  protocol/contracts/actions/topup/TopUpAction.sol::866 => if (IERC20(token).allowance(address(this), spender) > 0) return;
  protocol/contracts/actions/topup/TopUpActionFeeHandler.sol::123 => require(totalClaimable > 0, Error.NOTHING_TO_CLAIM);
  protocol/contracts/actions/topup/handlers/AaveHandler.sol::62 => if (variableDebt + stableDebt > 0) {
  protocol/contracts/actions/topup/handlers/AaveHandler.sol::84 => if (IERC20(token).allowance(address(this), spender) > 0) return;
  protocol/contracts/actions/topup/handlers/CompoundHandler.sol::137 => if (IERC20(token).allowance(address(this), spender) > 0) return;
  protocol/contracts/pool/LiquidityPool.sol::469 => require(underlyingAmount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/pool/LiquidityPool.sol::471 => require(lpToken_.balanceOf(account) > 0, Error.INSUFFICIENT_BALANCE);
  protocol/contracts/pool/LiquidityPool.sol::514 => require(mintedLp >= minTokenAmount && mintedLp > 0, Error.INVALID_AMOUNT);
  protocol/contracts/pool/LiquidityPool.sol::538 => require(redeemLpTokens > 0, Error.INVALID_AMOUNT);
  protocol/contracts/strategies/BkdEthCvx.sol::105 => if (stakedBalance > 0) {
  protocol/contracts/strategies/BkdEthCvx.sol::111 => if (lpBalance > 0) {
  protocol/contracts/strategies/BkdTriHopCvx.sol::154 => if (underlyingBalance > 0) {
  protocol/contracts/strategies/BkdTriHopCvx.sol::162 => if (hopLpBalance > 0) {
  protocol/contracts/strategies/BkdTriHopCvx.sol::214 => if (hopLpBalance > 0) {
  protocol/contracts/strategies/BkdTriHopCvx.sol::361 => if (stakedBalance > 0) {
  protocol/contracts/strategies/BkdTriHopCvx.sol::367 => if (lpBalance > 0) {
  protocol/contracts/strategies/ConvexStrategyBase.sol::410 => if (cvxCommunityReserveShare_ > 0) {
  protocol/contracts/strategies/ConvexStrategyBase.sol::413 => if (cvxBalance_ > 0) {
  protocol/contracts/strategies/ConvexStrategyBase.sol::421 => if (crvCommunityReserveShare_ > 0) {
  protocol/contracts/strategies/ConvexStrategyBase.sol::424 => if (crvBalance_ > 0) {
  protocol/contracts/swappers/SwapperRouter.sol::264 => if (IERC20(token_).allowance(address(this), spender_) > 0) return;
  protocol/contracts/testing/MockErc20Strategy.sol::64 => require(currentBalance > 0, "Invalid amount to withdraw");
  protocol/contracts/testing/MockErc20Strategy.sol::74 => require(amount > 0, "Invalid amount to transfer");
  protocol/contracts/testing/MockEthStrategy.sol::65 => require(currentBalance > 0, "Invalid amount to withdraw");
  protocol/contracts/testing/MockVotingEscrow.sol::35 => require(_balances[msg.sender] > 0, "a lock needs to first be created");
  protocol/contracts/tokenomics/AmmConvexGauge.sol::107 => if (!killed && totalStaked > 0) {
  protocol/contracts/tokenomics/AmmConvexGauge.sol::129 => if (!killed && totalStaked > 0) {
  protocol/contracts/tokenomics/AmmConvexGauge.sol::158 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/tokenomics/AmmConvexGauge.sol::171 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/tokenomics/AmmConvexGauge.sol::197 => if (totalStaked > 0) {
  protocol/contracts/tokenomics/AmmGauge.sol::88 => if (!killed && totalStaked > 0) {
  protocol/contracts/tokenomics/AmmGauge.sol::104 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/tokenomics/AmmGauge.sol::125 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/tokenomics/AmmGauge.sol::147 => if (totalStaked > 0) {
  protocol/contracts/tokenomics/FeeBurner.sol::117 => if (IERC20(token_).allowance(address(this), spender_) > 0) return;
  protocol/contracts/tokenomics/InflationManager.sol::575 => totalKeeperPoolWeight = totalKeeperPoolWeight > 0 ? totalKeeperPoolWeight : 0;
  protocol/contracts/tokenomics/InflationManager.sol::589 => totalLpPoolWeight = totalLpPoolWeight > 0 ? totalLpPoolWeight : 0;
  protocol/contracts/tokenomics/InflationManager.sol::602 => totalAmmTokenWeight = totalAmmTokenWeight > 0 ? totalAmmTokenWeight : 0;
  protocol/contracts/tokenomics/KeeperGauge.sol::140 => require(totalClaimable > 0, Error.ZERO_TRANSFER_NOT_ALLOWED);
  protocol/contracts/tokenomics/LpGauge.sol::68 => if (poolTotalStaked > 0) {
  protocol/contracts/tokenomics/LpGauge.sol::114 => if (poolTotalStaked > 0) {
  protocol/contracts/tokenomics/VestedEscrow.sol::84 => require(unallocatedSupply > 0, "No reward tokens in contract");
  protocol/contracts/vault/Vault.sol::163 => require(amount > 0, Error.INVALID_AMOUNT);
  protocol/contracts/vault/Vault.sol::231 => if (remainingStrategyBalance > 0) {
  protocol/contracts/vault/Vault.sol::466 => if (strategistShare > 0) {
  protocol/contracts/vault/Vault.sol::609 => if (currentDebt > 0) {
  protocol/contracts/vault/Vault.sol::638 => if (strategistShare > 0) {
  protocol/contracts/vault/Vault.sol::711 => if (govShare > 0) {
  protocol/contracts/vault/Vault.sol::727 => } else if (underlyingReserves > 0) {

Tools Used

Code Review

Recommended Mitigation Steps

Use >= or <= instead of > and < when possible.

C4-008 : Use Custom Errors instead of Revert Strings to save Gas

Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met)

Source Custom Errors in Solidity:

Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.

Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).

Instances include:

All require Statements

Tools Used

Code Review

Recommended Mitigation Steps

Recommended to replace revert strings with custom errors.

C4-009 : Use Shift Right/Left instead of Division/Multiplication if possible

Impact

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

While the DIV opcode uses 5 gas, the SHR opcode only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.

Proof of Concept

Contracts

Tools Used

None

Recommended Mitigation Steps

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

C4-010 : Cache array length in for loops can save gas

Impact

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Proof of Concept

  1. Navigate to the following smart contract line.
  protocol/contracts/tokenomics/InflationManager.sol::116 => for (uint256 i; i < stakerVaults.length; i = i.uncheckedInc()) {
  protocol/contracts/tokenomics/VestedEscrow.sol::94 => for (uint256 i; i < amounts.length; i = i.uncheckedInc()) {
  protocol/contracts/zaps/PoolMigrationZap.sol::22 => for (uint256 i; i < newPools_.length; ++i) {
  protocol/contracts/zaps/PoolMigrationZap.sol::39 => for (uint256 i; i < oldPoolAddresses_.length; ) {
  protocol/libraries/EnumerableExtensions.sol::19 => uint256 len = addresses.length();

Tools Used

None

Recommended Mitigation Steps

Consider to cache array length.

C4-011 : State Variables that can be changed to immutable

Impact

Solidity 0.6.5 introduced immutable as a major feature. It allows setting contract-level variables at construction time which gets stored in code rather than storage.

Consider the following generic example:

contract C {
   /// The owner is set during contruction time, and never changed afterwards.
   address public owner = msg.sender;
}

In the above example, each call to the function owner() reads from storage, using a sload. After EIP-2929, this costs 2100 gas cold or 100 gas warm. However, the following snippet is more gas efficient:

contract C {
   /// The owner is set during contruction time, and never changed afterwards.
   address public immutable owner = msg.sender;
}

In the above example, each storage read of the owner state variable is replaced by the instruction push32 value, where value is set during contract construction time. Unlike the last example, this costs only 3 gas.

Proof of Concept

  1. Navigate to the following smart contract line.
https://github.com/code-423n4/2022-05-backd/blob/main/protocol/contracts/tokenomics/VestedEscrow.sol#L39

Tools Used

None

Recommended Mitigation Steps

Consider using immutable variable.

C4-012 : Use calldata instead of memory for function parameters

Impact

In some cases, having function arguments in calldata instead of memory is more optimal.

Consider the following generic example:

contract C {
   function add(uint[] memory arr) external returns (uint sum) {
       uint length = arr.length;
       for (uint i = 0; i < arr.length; i++) {
           sum += arr[i];
       }
   }
}

In the above example, the dynamic array arr has the storage location memory. When the function gets called externally, the array values are kept in calldata and copied to memory during ABI decoding (using the opcode calldataload and mstore). And during the for loop, arr[i] accesses the value in memory using a mload. However, for the above example this is inefficient. Consider the following snippet instead:

contract C {
   function add(uint[] calldata arr) external returns (uint sum) {
       uint length = arr.length;
       for (uint i = 0; i < arr.length; i++) {
           sum += arr[i];
       }
   }
}

In the above snippet, instead of going via memory, the value is directly read from calldata using calldataload. That is, there are no intermediate memory operations that carries this value.

Gas savings: In the former example, the ABI decoding begins with copying value from calldata to memory in a for loop. Each iteration would cost at least 60 gas. In the latter example, this can be completely avoided. This will also reduce the number of instructions and therefore reduces the deploy time cost of the contract.

In short, use calldata instead of memory if the function argument is only read.

Note that in older Solidity versions, changing some function arguments from memory to calldata may cause "unimplemented feature error". This can be avoided by using a newer (0.8.*) Solidity compiler.

Proof of Concept

  1. Navigate to the following smart contract line.
protocol/contracts/tokenomics/FeeBurner.sol:43:    function burnToTarget(address[] memory tokens_, address targetLpToken_)

Tools Used

None

Recommended Mitigation Steps

Some parameters in examples given above are later hashed. It may be beneficial for those parameters to be in memory rather than calldata.

GalloDaSballo commented 2 years ago

C4-001: Revert String Size Optimization

6 gas * 27 162

C4-002 : Adding unchecked directive can save gas

20 gas

C4-003 : Check if amount > 0 before token transfer can save gas

Yes but only in "bad path"

C4-004 : There is no need to assign default values to variables

Saves 3 gas

C4-005 : Free gas savings for using solidity 0.8.13+

Glad the warden mentioned what the savings are, but in lack of POC with clear before after, I cannot give any gas saved

C4-006 : Using operator && used more gas

You mention requires but those are ifs, will not award any points

C4-007 : Non-strict inequalities are cheaper than strict ones

In lack of POC I disagree, a strict inequality is just one opcode, a non-strict requires more

 C4-008 : Use Custom Errors instead of Revert Strings to save Gas

Same, no POC, no points

C4-010 : Cache array length in for loops can save gas

Saves 3 gas per instance 5 * 3 = 15

C4-011 : State Variables that can be changed to immutable

Saves one SLOAD (in lack of POC), 2.1k

C4-012 : Use calldata instead of memory for function parameters

In lack of POC I won't award points

Total gas saved 2300

I'll penalize this report as it really looks automated