Platform: Code4rena
Start Date: 28/04/2022
Pot Size: $50,000 USDC
Total HM: 7
Participants: 43
Period: 5 days
Judge: gzeon
Total Solo HM: 2
Id: 115
League: ETH
Rank: 6/43
Findings: 4
Award: $1,717.38
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: hyh
Also found by: 0xDjango, berndartmueller, cccz, defsec, delfin454000, joestakey, robee
247.8825 USDC - $247.88
Judge has assessed an item in Issue #104 as Medium risk. The relevant finding follows:
Check transfer receiver is not 0 to avoid burned money Transferring tokens to the zero address is usually prohibited to accidentally avoid "burning" tokens by sending them to an unrecoverable zero address.
Code instances: https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L129 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/liquidityMining/v2/DemandMinerV2.sol#L67 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L370 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L247 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L313
#0 - gzeoneth
2022-06-05T15:28:05Z
Duplicate of #145
🌟 Selected for report: ych18
Also found by: MaratCerby, defsec, robee
755.6243 USDC - $755.62
Judge has assessed an item in Issue #104 as Medium risk. The relevant finding follows:
transfer return value of a general ERC20 is ignored Need to use safeTransfer instead of transfer. As there are popular tokens, such as USDT that transfer/trasnferFrom method doesn’t return anything. The transfer return value has to be checked (as there are some other tokens that returns false instead revert), that means you must
Check the transfer return value Another popular possibility is to add a whiteList. Those are the appearances (solidity file, line number, actual line): Code instances: SuperVault.sol, 274 (depositToVault), token.transferFrom(msg.sender, address(this), amount); MerkleDistributor.sol, 68 (recoverERC20), IERC20(_tokenAddress).transfer(owner(), _tokenAmount); SuperVault.sol, 290 (depositAndBorrowFromVault), token.transferFrom(msg.sender, address(this), depositAmount); SuperVault.sol, 129 (leverage), IERC20(asset).transferFrom(msg.sender, address(this), depositAmount); SuperVault.sol, 237 (emptyVault), collateral.transfer(msg.sender, collateral.balanceOf(address(this)));
#0 - gzeoneth
2022-06-05T15:33:33Z
Duplicate of #127
🌟 Selected for report: Dravee
Also found by: 0x1f8b, 0x4non, 0x52, 0xDjango, AlleyCat, Funen, GalloDaSballo, GimelSec, Hawkeye, MaratCerby, Picodes, berndartmueller, cccz, defsec, delfin454000, dipp, hyh, ilan, joestakey, kebabsec, luduvigo, pauliax, peritoflores, robee, rotcivegaf, samruna, shenwilly, sikorico, simon135, sorrynotsorry, unforgiven, z3s
514.4314 USDC - $514.43
To improve algorithm precision instead using division in comparison use multiplication in the following scenario:
Instead a < b / c use a * c < b.
In all of the big and trusted contracts this rule is maintained.
ABDKMath64x64.sol, 600, if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y;
Some fee parameters of functions are not checked for invalid values. Validate the parameters:
DemandMinerV2.setFeeConfig (newFeeConfig)
Some fee parameters of functions are not checked for invalid values. Validate the parameters:
InceptionVaultFactory.priceFeedIds (_priceFeed) ConfigProviderV1.setCollateralOriginationFee (_originationFee) ConfigProvider.setCollateralConfig (_originationFee) ConfigProvider.setCollateralOriginationFee (_originationFee) InceptionVaultFactory.cloneInceptionVault (_inceptionVaultPriceFeed)
You use safeApprove of openZeppelin although it's deprecated. (see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/token/ERC20/utils/SafeERC20.sol#L38) You should change it to increase/decrease Allowance as OpenZeppilin says.
Deprecated safeApprove in TInceptionVaultUnhealthy.sol line 36: _weth.approve(address(a), _adminDepositAmount); Deprecated safeApprove in TInceptionVaultHealthy.sol line 46: _par.approve(address(_inceptionVaultsCore), _MAX_INT); Deprecated safeApprove in TInceptionVaultUnhealthyAssertion.sol line 50: _par.approve(address(_inceptionVaultsCore), _MAX_INT); Deprecated safeApprove in TInceptionVaultUnhealthy.sol line 51: _par.approve(address(_inceptionVaultsCore), _MAX_INT); Deprecated safeApprove in SuperVault.sol line 198: par.approve(address(a.core()), par.balanceOf(address(this)));
The following requires are with empty messages. This is very important to add a message for any require. So the user has enough information to know the reason of failure.
Solidity file: ConfigProvider.sol, In line 27 with Empty Require message. Solidity file: VaultsCore.sol, In line 45 with Empty Require message. Solidity file: PARMiner.sol, In line 41 with Empty Require message. Solidity file: VaultsCoreState.sol, In line 42 with Empty Require message. Solidity file: VaultsCore.sol, In line 149 with Empty Require message.
The project is compiled with different versions of solidity, which is not recommended because it can lead to undefined behaviors.
You should use safe math for solidity version <8 since there is no default over/under flow check it suchversions of solidity.
The contract IGenericMinerV2.sol doesn't use safe math and is of solidity version < 8 The contract MockWBTC.sol doesn't use safe math and is of solidity version < 8 The contract USDX.sol doesn't use safe math and is of solidity version < 8 The contract ABDKMath64x64.sol doesn't use safe math and is of solidity version < 8 The contract IUniswapV2Router01.sol doesn't use safe math and is of solidity version < 8
owner param should be validated to make sure the owner address is not address(0). Otherwise if not given the right input all only owner accessible functions will be unaccessible.
InceptionVaultsCore.sol.initialize _owner InceptionVaultsDataProvider.sol.createVault _owner VaultsDataProvider.sol.createVault _owner VaultsDataProviderV1.sol.createVault _owner SuperVault.sol.initialize _owner
Most contracts use an init pattern (instead of a constructor) to initialize contract parameters. Unless these are enforced to be atomic with contact deployment via deployment script or factory contracts, they are susceptible to front-running race conditions where an attacker/griefer can front-run (cannot access control because admin roles are not initialized) to initially with their own (malicious) parameters upon detecting (if an event is emitted) which the contract deployer has to redeploy wasting gas and risking other transactions from interacting with the attacker-initialized contract.
Many init functions do not have an explicit event emission which makes monitoring such scenarios harder. All of them have re-init checks; while many are explicit some (those in auction contracts) have implicit reinit checks in initAccessControls() which is better if converted to an explicit check in the main init function itself. (details credit to: https://github.com/code-423n4/2021-09-sushimiso-findings/issues/64) The vulnerable initialization functions in the codebase are:
ChainlinkInceptionPriceFeed.sol, initialize, 29 AdminInceptionVault.sol, initialize, 35 InceptionVaultsCore.sol, initialize, 40 SuperVault.sol, initialize, 49 InceptionVaultsDataProvider.sol, initialize, 30
Users can mistakenly think that the return value is the named return, but it is actually the actualreturn statement that comes after. To know that the user needs to read the code and is confusing. Furthermore, removing either the actual return or the named return will save gas.
PriceFeed.sol, getAssetPrice RatesManager.sol, calculateDebt LiquidiationManager.sol, applyLiquidationDiscount LiquidiationManagerV1.sol, applyLiquidationDiscount LiquidiationManagerV1.sol, calculateHealthFactor
The following contracts have a function that allows them an admin to change it to a different address. If the admin accidentally uses an invalid address for which they do not have the private key, then the system gets locked. It is important to have two steps admin change where the first is announcing a pending new admin and the new address should then claim its ownership. A similar issue was reported in a previous contest and was assigned a severity of medium: code-423n4/2021-06-realitycards-findings#105
IAddressProviderV1.sol IGovernanceAddressProvider.sol IAddressProvider.sol AddressProvider.sol GovernanceAddressProvider.sol
The following functions are missing reentrancy modifier although some other pulbic/external functions does use reentrancy modifer. Even though I did not find a way to exploit it, it seems like those functions should have the nonReentrant modifier as the other functions have it as well..
VaultsCore.sol, acceptUpgrade is missing a reentrancy modifier VaultsCore.sol, depositByVaultId is missing a reentrancy modifier VaultsCore.sol, upgrade is missing a reentrancy modifier VaultsCore.sol, deposit is missing a reentrancy modifier InceptionVaultsCore.sol, deposit is missing a reentrancy modifier
From solidity docs: Properly functioning code should never reach a failing assert statement; if this happens there is a bug in your contract which you should fix. With assert the user pays the gas and with require it doesn't. The ETH network gas isn't cheap and users can see it as a scam.
TInceptionVaultUnhealthyAssertion.sol : reachable assert in line 74 TInceptionVaultUnhealthy.sol : reachable assert in line 102 TInceptionVaultUnhealthyAssertion.sol : reachable assert in line 61 TInceptionVaultUnhealthy.sol : reachable assert in line 89 ABDKMath64x64.sol : reachable assert in line 640
In the following functions no value is returned, due to which by default value of return will be 0. We assumed that after the update you return the latest new value. (similar issue here: https://github.com/code-423n4/2021-10-badgerdao-findings/issues/85).
GenericMinerV2.sol, updateBoost MockChainlinkAggregator.sol, setUpdatedAt PARMinerV2.sol, updateBoost
Those are functions and parameters pairs that the function doesn't use the parameter. In case those functions are external/public this is even worst since the user is required to put value that never used and can misslead him and waste its time.
MockBalancerVault.sol: function getPoolTokens parameter poolId isn't used. (getPoolTokens is external) BalancerV2LPOracle.sol: function getRoundData parameter _roundId isn't used. (getRoundData is public) MockBuggyERC20.sol: function _beforeTokenTransfer parameter to isn't used. (_beforeTokenTransfer is internal) VotingEscrow.sol: function _depositFor parameter _oldLocked isn't used. (_depositFor is internal) GUniLPOracle.sol: function getRoundData parameter _roundId isn't used. (getRoundData is public)
The following functions are missing commenting as describe below:
SuperVault.sol, emptyVaultOperation (internal), parameters vaultCollateral, amount, flashloanRepayAmount, params not commented SuperVault.sol, initialize (external), parameter dexAP not commented SuperVault.sol, executeOperation (external), @return is missing SuperVault.sol, leverageOperation (internal), parameters token, flashloanRepayAmount, params not commented SuperVault.sol, rebalanceOperation (internal), parameters fromCollateral, amount, flashloanRepayAmount, params not commented
Open TODOs can hint at programming or architectural errors that still need to be fixed. These files has open TODOs:
Open TODO in GenericMiner.sol line 112 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
Open TODO in PARMiner.sol line 165 : require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
Open TODO in GenericMiner.sol line 93 : require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
Open TODO in GenericMiner.sol line 90 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
Open TODO in PARMiner.sol line 162 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
Transferring tokens to the zero address is usually prohibited to accidentally avoid "burning" tokens by sending them to an unrecoverable zero address.
https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L129 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/liquidityMining/v2/DemandMinerV2.sol#L67 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L370 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L247 https://github.com/code-423n4/2022-04-mimo/tree/main/supervaults/contracts/SuperVault.sol#L313
From solidity docs: Properly functioning code should never reach a failing assert statement; if this happens there is a bug in your contract which you should fix. With assert the user pays the gas and with require it doesn't. The ETH network gas isn't cheap and users can see it as a scam.
TInceptionVaultUnhealthyAssertion.sol : reachable assert in line 74 TInceptionVaultUnhealthy.sol : reachable assert in line 102 TInceptionVaultUnhealthyAssertion.sol : reachable assert in line 61 TInceptionVaultUnhealthy.sol : reachable assert in line 89 ABDKMath64x64.sol : reachable assert in line 640
In the following functions no value is returned, due to which by default value of return will be 0. We assumed that after the update you return the latest new value. (similar issue here: https://github.com/code-423n4/2021-10-badgerdao-findings/issues/85).
GenericMinerV2.sol, updateBoost MockChainlinkAggregator.sol, setUpdatedAt PARMinerV2.sol, updateBoost
Those are functions and parameters pairs that the function doesn't use the parameter. In case those functions are external/public this is even worst since the user is required to put value that never used and can misslead him and waste its time.
MockBalancerVault.sol: function getPoolTokens parameter poolId isn't used. (getPoolTokens is external) BalancerV2LPOracle.sol: function getRoundData parameter _roundId isn't used. (getRoundData is public) MockBuggyERC20.sol: function _beforeTokenTransfer parameter to isn't used. (_beforeTokenTransfer is internal) VotingEscrow.sol: function _depositFor parameter _oldLocked isn't used. (_depositFor is internal) GUniLPOracle.sol: function getRoundData parameter _roundId isn't used. (getRoundData is public)
The following functions are missing commenting as describe below:
SuperVault.sol, emptyVaultOperation (internal), parameters vaultCollateral, amount, flashloanRepayAmount, params not commented SuperVault.sol, initialize (external), parameter dexAP not commented SuperVault.sol, executeOperation (external), @return is missing SuperVault.sol, leverageOperation (internal), parameters token, flashloanRepayAmount, params not commented SuperVault.sol, rebalanceOperation (internal), parameters fromCollateral, amount, flashloanRepayAmount, params not commented
Open TODOs can hint at programming or architectural errors that still need to be fixed. These files has open TODOs:
Open TODO in GenericMiner.sol line 112 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
Open TODO in PARMiner.sol line 165 : require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
Open TODO in GenericMiner.sol line 93 : require(userInfo.stake >= value, "INSUFFICIENT_STAKE_FOR_USER"); //TODO cleanup error message
Open TODO in GenericMiner.sol line 90 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
Open TODO in PARMiner.sol line 162 : require(value > 0, "STAKE_MUST_BE_GREATER_THAN_ZERO"); //TODO cleanup error message
To give more trust to users: functions that set key/critical variables should be put behind a timelock.
https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/liquidityMining/v2/PARMinerV2.sol#L82 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/v1/VaultsDataProviderV1.sol#L73 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/core/ConfigProvider.sol#L254 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/core/AddressProvider.sol#L63 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/v1/AddressProviderV1.sol#L64
Some tokens (like USDT) do not work when changing the allowance from an existing non-zero allowance value. They must first be approved by zero and then the actual allowance must be approved.
approve without approving 0 first SuperVault.sol, 288, token.approve(address(a.core()), depositAmount);
approve without approving 0 first VaultsCoreV1.sol, 60, asset.safeApprove(_newVaultsCore, MAX_INT);
approve without approving 0 first MIMOBuybackUniswapV2.sol, 34, PAR.approve(address(router), 2**256 - 1);
approve without approving 0 first SuperVault.sol, 198, par.approve(address(a.core()), par.balanceOf(address(this)));
approve without approving 0 first MIMOBuyBack.sol, 35, PAR.approve(address(balancer), 2**256 - 1);
use openzeppilin's safeCast in:
https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/mocks/MockInceptionAggregator.sol#L98 : unsafe cast uint80(latestRound) https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/libraries/ABDKMath64x64.sol#L595 : unsafe cast uint128(result) https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/mocks/MockChainlinkAggregator.sol#L100 : unsafe cast uint80(latestRound) https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/mocks/MockChainlinkFeed.sol#L97 : unsafe cast uint80(latestRound)
The use of send() / call() to send ETH may have unintended outcomes on the eth being sent to the receiver. Eth may be irretrievable or undelivered if the msg.sender or feeRecipient is a smart contract. Funds can potentially be lost if; 1. The smart contract fails to implement the payable fallback function 2. The fallback function uses more than 2300 gas units Different from .transfer(...), .send(...) and call(...) doesn't revert when it fails, and therefore its retrun value is extremely important. The latter situation may occur in the instance of gas cost changes. The impact would mean that any contracts receiving funds would potentially be unable to retrieve funds from the transaction. A detailed explanation of why relying on payable().transfer() may result in unexpected loss of eth can be found here: https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now This is not just a best-practice advice since the return value isn't considered!!! If you would consider it then it was just a best practice.
SuperVault.sol, 345, router.call(dexTxData);
PARMinerV2.sol, 125, router.call(dexTxData);
A malicious attacker that is also a protocol owner can push unlimitedly to an array, that some function loop over this array. If increasing the array size enough, calling the function that does a loop over the array will always revert since there is a gas limit. This is a Med Risk issue since it can lead to DoS with a reasonable chance of having untrusted owner or even an owner that did a mistake in good faith.
FeeDistributorV1.sol (L104): Unbounded loop on the array payees that can be publicly pushed by ['_addPayee'] and can't be pulled MinerPayer.sol (L68): Unbounded loop on the array payees that can be publicly pushed by ['_addPayee'] and can't be pulled MinerPayer.sol (L59): Unbounded loop on the array payees that can be publicly pushed by ['_addPayee'] and can't be pulled BaseDistributor.sol (L64): Unbounded loop on the array payees that can be publicly pushed by ['_addPayee'] and can't be pulled MinerPayer.sol (L46): Unbounded loop on the array payees that can be publicly pushed by ['_addPayee'] and can't be pulled
Division by 0 can lead to accidentally revert, (An example of a similar issue - https://github.com/code-423n4/2021-10-defiprotocol-findings/issues/84)
https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/oracles/GUniLPOracle.sol#L107 priceB might be 0 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/libraries/BNum.sol#L63 a might be 0 https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/libraries/BNum.sol#L53 a might be 0
Timelock.sol.cancelTransaction inherent ITimelock.sol.cancelTransaction but the parameters does not match https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/governance/interfaces/ITimelock.sol#L43 Timelock.sol.executeTransaction inherent ITimelock.sol.executeTransaction but the parameters does not match https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/governance/interfaces/ITimelock.sol#L51 InceptionVaultsCore.sol.initialize inherent IInceptionVaultsCore.sol.initialize but the parameters does not match https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/inception/interfaces/IInceptionVaultsCore.sol#L39 Timelock.sol.queueTransaction inherent ITimelock.sol.queueTransaction but the parameters does not match https://github.com/code-423n4/2022-04-mimo/tree/main/core/contracts/governance/interfaces/ITimelock.sol#L35
Some tokens don't correctly implement the EIP20 standard and their approve function returns void instead of a success boolean. Calling these functions with the correct EIP20 function signatures will always revert. Tokens that don't correctly implement the latest EIP20 spec, like USDT, will be unusable in the mentioned contracts as they revert the transaction because of the missing return value. We recommend using OpenZeppelin’s SafeERC20 versions with the safeApprove function that handle the return value check as well as non-standard-compliant tokens. The list of occurrences in format (solidity file, line number, actual line)
TInceptionVaultUnhealthyProperty.sol, 34, _weth.approve(address(a), _adminDepositAmount);
MIMOBuyBack.sol, 35, PAR.approve(address(balancer), 2**256 - 1);
SuperVault.sol, 272, token.approve(address(a.core()), amount);
TInceptionVaultUnhealthy.sol, 36, _weth.approve(address(a), _adminDepositAmount);
TInceptionVaultUnhealthyProperty.sol, 49, _par.approve(address(_inceptionVaultsCore), _MAX_INT);
Need to use safeTransfer instead of transfer. As there are popular tokens, such as USDT that transfer/trasnferFrom method doesn’t return anything. The transfer return value has to be checked (as there are some other tokens that returns false instead revert), that means you must
SuperVault.sol, 274 (depositToVault), token.transferFrom(msg.sender, address(this), amount); MerkleDistributor.sol, 68 (recoverERC20), IERC20(_tokenAddress).transfer(owner(), _tokenAmount); SuperVault.sol, 290 (depositAndBorrowFromVault), token.transferFrom(msg.sender, address(this), depositAmount); SuperVault.sol, 129 (leverage), IERC20(asset).transferFrom(msg.sender, address(this), depositAmount); SuperVault.sol, 237 (emptyVault), collateral.transfer(msg.sender, collateral.balanceOf(address(this)));
The current implementaion is using an non-upgradeable version of the Ownbale library. instead of the upgradeable version: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol. A regular, non-upgradeable Ownbale library will make the deployer the default owner in the constructor. Due to a requirement of the proxy-based upgradeability system, no constructors can be used in upgradeable contracts. Therefore, there will be no owner when the contract is deployed as a proxy contract Use @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol and @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol instead. And add __Ownable_init(); at the beginning of the initializer.
InceptionVaultsCore.sol AdminInceptionVault.sol
The attacker can push unlimitedly to an array, that some function loop over this array. If increasing the array size enough, calling the function that does a loop over the array will always revert since there is a gas limit. This is an High Risk issue since those arrays are publicly allows to push items into them.
PreUseAirdrop.sol (L73): Unbounded loop on the array payouts that can be publicly pushed by ['constructor']
199.4485 USDC - $199.45
In the following files there are state variables that could be set immutable to save gas.
_inceptionVaultPriceFeed in TInceptionVaultUnhealthyAssertion.sol _inceptionCollateral in ChainlinkInceptionPriceFeed.sol a in VaultsDataProvider.sol _vaultsDataProvider in TIVSetup.sol _baseChainlinkInceptionPriceFeed in TIVSetup.sol
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.
BConst.sol, INIT_POOL_SUPPLY TInceptionVaultUnhealthy.sol, _adminInceptionVault TInceptionVaultUnhealthyProperty.sol, _exist BConst.sol, BPOW_PRECISION MIMODistributorV2.sol, _SECONDS_PER_YEAR
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++) { ... }
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.
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:
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
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:
MinerPayer.sol, 69 FeeDistributorV1.sol, 111 PreUseAirdrop.sol, 74 FeeDistributorV1.sol, 105 FeeDistributor.sol, 47
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:
ChainlinkInceptionPriceFeed.sol: _PRICE_ORACLE_STALE_THRESHOLD is read twice in getAssetPrice PriceFeed.sol: PRICE_ORACLE_STALE_THRESHOLD is read twice in getAssetPrice
Unnecessary default assignments, you can just declare and it will save gas and have the same meaning.
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;
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:
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
Using != 0 is slightly cheaper than > 0. (see https://github.com/code-423n4/2021-12-maple-findings/issues/75 for similar issue)
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'
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)
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:
ABDKMath64x64.sol, int256 bit, 467 AdminInceptionVault.sol, uint8 i, 108 TInceptionVaultFactory.sol, uint8 i, 20
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.)
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); }
The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.
BNum.sol, bdiv BNum.sol, bpowi SuperVault.sol, rebalanceOperation SuperVault.sol, emptyVaultOperation GenericMinerV2.sol, _getBoostMultiplier
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:
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);
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.
BoringOwnable.sol USDX.sol TInceptionVaultUnhealthyProperty.sol ISTABLEX.sol IUniswapV2Router01.sol
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.
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);)
We recommend not to cache msg.sender since calling it is 2 gas while reading a variable is more.
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