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 #105

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

Gas Optimizations #105

code423n4 opened this issue May 2, 2022 · 0 comments
Labels
bug Something isn't working G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

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:

    _inceptionVaultPriceFeed in TInceptionVaultUnhealthyAssertion.sol
    _inceptionCollateral in ChainlinkInceptionPriceFeed.sol
    a in VaultsDataProvider.sol
    _vaultsDataProvider in TIVSetup.sol
    _baseChainlinkInceptionPriceFeed in TIVSetup.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:

    BConst.sol, INIT_POOL_SUPPLY
    TInceptionVaultUnhealthy.sol, _adminInceptionVault
    TInceptionVaultUnhealthyProperty.sol, _exist
    BConst.sol, BPOW_PRECISION
    MIMODistributorV2.sol, _SECONDS_PER_YEAR

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:

    BaseDistributor.sol, _payees, 71
    MinerPayer.sol, payees, 47
    MinerPayer.sol, payees, 62
    FeeDistributor.sol, _payees, 75
    FeeDistributor.sol, payees, 47

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:

    change to prefix increment and unchecked: VaultsDataProviderV1.sol, i, 159
    change to prefix increment and unchecked: FeeDistributor.sol, i, 69
    change to prefix increment and unchecked: VaultsCoreState.sol, i, 87
    change to prefix increment and unchecked: AdminInceptionVault.sol, i, 108
    change to prefix increment and unchecked: FeeDistributorV1.sol, i, 111

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:

    MinerPayer.sol, 69
    FeeDistributorV1.sol, 111
    PreUseAirdrop.sol, 74
    FeeDistributorV1.sol, 105
    FeeDistributor.sol, 47

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:

    ChainlinkInceptionPriceFeed.sol: _PRICE_ORACLE_STALE_THRESHOLD is read twice in getAssetPrice
    PriceFeed.sol: PRICE_ORACLE_STALE_THRESHOLD is read twice in getAssetPrice

Unnecessary default assignment

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

Code instances:

    BConst.sol (L#26) : uint256 public constant EXIT_FEE = 0; 
    MIMOBuybackUniswapV2.sol (L#20) : bool public whitelistEnabled = false; 
    VaultsDataProvider.sol (L#15) : uint256 public override vaultCount = 0; 
    VotingEscrow.sol (L#27) : bool public expired = false;
    VaultsDataProviderV1.sol (L#15) : uint256 public override vaultCount = 0; 

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 instances:

    Solidity file: MinerPayer.sol, In line 35, Require message length to shorten: 37, The message: Governance address can't be 0 address
    Solidity file: VotingEscrow.sol, In line 96, Require message length to shorten: 36, The message: Cannot add to expired lock. Withdraw
    Solidity file: MockBuggyERC20.sol, In line 138, Require message length to shorten: 34, The message: ERC20: approve to the zero address
    Solidity file: VotingEscrow.sol, In line 81, Require message length to shorten: 38, The message: Can only lock until time in the future
    Solidity file: MockBuggyERC20.sol, In line 102, Require message length to shorten: 37, The message: ERC20: transfer from the zero address

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:

    VotingEscrow.sol, 94: change '_value > 0' to '_value != 0'
    FeeDistributor.sol, 107: change '_shares > 0' to '_shares != 0'
    GenericMiner.sol, 91: change 'value > 0' to 'value != 0'
    GenericMinerV2.sol, 195: change 'value > 0' to 'value != 0'
    PARMiner.sol, 163: change 'value > 0' to 'value != 0'

Unnecessary cast

Code instances:

    address InceptionVaultFactory.sol.cloneInceptionVault - unnecessary casting address(_assetOracle)
    uint80 MockChainlinkAggregator.sol.getRoundData - unnecessary casting uint80(_roundId)
    uint80 MockInceptionAggregator.sol.getRoundData - unnecessary casting uint80(_roundId)
    address ConfigProviderV1.sol.setCollateralConfig - unnecessary casting address(_collateralType)
    int256 ABDKMath64x64.sol.muli - unnecessary casting int256(y)

uint8 index

Due to how the EVM natively works on 256 numbers, using a 8 bit number here introduces additional costs as the EVM has to properly enforce the limits of this smaller type.
See the warning at this link: https://docs.soliditylang.org/en/v0.8.0/internals/layout_in_storage.html#layout-of-state-variables-in-storage
We recommend to use uint256 for the index in every for loop instead using uint8:

Code instances:

    ABDKMath64x64.sol, int256 bit, 467
    AdminInceptionVault.sol, uint8 i, 108
    TInceptionVaultFactory.sol, uint8 i, 20

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

    WadRayMath.sol, ray, { return _RAY; }
    WadRayMath.sol, wad, { return _WAD; }
    BNum.sol, btoi, { return a / BONE; }
    ABDKMath64x64.sol, to128x128, { return int256(x) << 64; }
    WadRayMath.sol, wadMul, { return _HALF_WAD.add(a.mul(b)).div(_WAD); }

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:

    BNum.sol, bdiv
    BNum.sol, bpowi
    SuperVault.sol, rebalanceOperation
    SuperVault.sol, emptyVaultOperation
    GenericMinerV2.sol, _getBoostMultiplier

Cache powers of 10 used several times

You calculate the power of 10 every time you use it instead of caching it once as a constant variable and using it instead.
Fix the following code lines:

Code instances:

GUniLPOracle.sol, 45 : You should cache the used power of 10 as constant state variable since it's used several times (2): _tokenDecimalsUnitA = 10**decimalsA;

GUniLPOracle.sol, 46 : You should cache the used power of 10 as constant state variable since it's used several times (2): _tokenDecimalsOffsetA = 10**(18 - decimalsA);

GUniLPOracle.sol, 49 : You should cache the used power of 10 as constant state variable since it's used several times (2): _tokenDecimalsUnitB = 10**decimalsB;

GUniLPOracle.sol, 50 : You should cache the used power of 10 as constant state variable since it's used several times (2): _tokenDecimalsOffsetB = 10**(18 - decimalsB);

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:

    BoringOwnable.sol
    USDX.sol
    TInceptionVaultUnhealthyProperty.sol
    ISTABLEX.sol
    IUniswapV2Router01.sol

Gas Optimization On The 2^256-1

Some projects (e.g. Uniswap - https://github.com/Uniswap/interface/blob/main/src/hooks/useApproveCallback.ts#L88)
set the default value of the user's allowance to 2^256 - 1. Since the value 2^256 - 1 can also be represented in
hex as 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff. From Ethereum's yellow paper we know
that zeros are cheaper than non-zero values in the hex representation. Considering this fact, an alternative
choice could be now 0x8000000000000000000000000000000000000000000000000000000000000000 or 2^255 to represent
"infinity". If you do the calculations with Remix, you will see that the former costs 47'872 gas, while the latter
costs 45'888 gas. If you accept that infinity can also be represented via 2^255 (instead of 2^256-1), which almost
all projects can - you can already save about 4% gas leveraging this optimisation trick on those calculations.

Code instances:

    SuperVault.sol (L#326): token.approve(address(a.core()), 2**256 - 1);)
    VaultsCoreState.sol (L#18): uint256 internal constant _MAX_INT = 2**256 - 1; )
    MIMOBuybackUniswapV2.sol (L#61): router.swapExactTokensForTokens( PAR.balanceOf(address(this)), 0, path, address(this), 2**256 - 1 );)
    MIMOBuyBack.sol (L#36): PAR.approve(address(balancer), 2**256 - 1);)
    MIMOBuybackUniswapV2.sol (L#35): PAR.approve(address(router), 2**256 - 1);)

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-04-mimo/tree/main/core/contracts/inception/BoringOwnable.sol#L19
    https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/governance/Timelock.sol#L44
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels May 2, 2022
code423n4 added a commit that referenced this issue May 2, 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)
Projects
None yet
Development

No branches or pull requests

1 participant