bunker.finance contest - robee's results

The easiest way to borrow against your NFTs.

General Information

Platform: Code4rena

Start Date: 03/05/2022

Pot Size: $50,000 USDC

Total HM: 4

Participants: 46

Period: 5 days

Judge: gzeon

Total Solo HM: 2

Id: 117

League: ETH

bunker.finance

Findings Distribution

Researcher Performance

Rank: 11/46

Findings: 2

Award: $414.69

🌟 Selected for report: 0

πŸš€ Solo Findings: 0

Awards

274.7287 USDC - $274.73

Labels

bug
QA (Quality Assurance)

External Links

Require with empty message

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.

Code instance:

Solidity file: CEther.sol, In line 148 with Empty Require message.

Not verified input

external / public functions parameters should be validated to make sure the address is not 0. Otherwise if not given the right input it can mistakenly lead to loss of user funds.

Code instances:

CEther.sol.liquidateBorrowNft borrower CNft.sol.call to CNft.sol.safeBatchTransferFrom to Comptroller.sol.seizeAllowed liquidator Comptroller.sol.transferAllowed cAsset

Solidity compiler versions mismatch

The project is compiled with different versions of solidity, which is not recommended because it can lead to undefined behaviors.

Code instance:

Use safe math for solidity version <8

You should use safe math for solidity version <8 since there is no default over/under flow check it suchversions of solidity.

Code instances:

The contract CEther.sol doesn't use safe math and is of solidity version < 8 The contract Comptroller.sol doesn't use safe math and is of solidity version < 8 The contract CErc20.sol doesn't use safe math and is of solidity version < 8

Init frontrun

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:

Code instance:

CNft.sol, initialize, 17

Assert instead require to validate user inputs

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.

Code instances:

Comptroller.sol : reachable assert in line 332 Comptroller.sol : reachable assert in line 206

In the following public update functions no value is returned

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).

Code instance:

Comptroller.sol, updateContributorRewards

Never used parameters

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.

Code instances:

CNft.sol: function onERC721Received parameter tokenId isn't used. (onERC721Received is public) CNft.sol: function onERC1155Received parameter data isn't used. (onERC1155Received is public) CNft.sol: function onERC1155Received parameter from isn't used. (onERC1155Received is public) Comptroller.sol: function _initializeNftCollateral parameter _collateralFactorMantissa isn't used. (_initializeNftCollateral is external) CNft.sol: function onERC1155Received parameter value isn't used. (onERC1155Received is public)

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/bunker-protocol/tree/main/contracts/CNft.sol#L139 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CEther.sol#L167 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L95 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CErc20.sol#L209 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CErc20.sol#L174

Assert instead require to validate user inputs

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.

Code instances:

Comptroller.sol : reachable assert in line 332 Comptroller.sol : reachable assert in line 206

In the following public update functions no value is returned

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).

Code instance:

Comptroller.sol, updateContributorRewards

Never used parameters

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.

Code instances:

CNft.sol: function onERC721Received parameter tokenId isn't used. (onERC721Received is public) CNft.sol: function onERC1155Received parameter data isn't used. (onERC1155Received is public) CNft.sol: function onERC1155Received parameter from isn't used. (onERC1155Received is public) Comptroller.sol: function _initializeNftCollateral parameter _collateralFactorMantissa isn't used. (_initializeNftCollateral is external) CNft.sol: function onERC1155Received parameter value isn't used. (onERC1155Received is public)

Two arrays length mismatch

The functions below fail to perform input validation on arrays to verify the lengths match. A mismatch could lead to an exception or undefined behavior. Consider making this a medium risk please.

Code instances

https://github.com/code-423n4/bunker-protocol/tree/main/contracts/ERC1155Enumerable.sol#L35 _beforeTokenTransfer ['ids', 'amounts'] https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L166 safeBatchTransferFrom ['ids', 'amounts']

Not owner function calls an owner function

Code instance:

CNft.sol.executeCall - calls call

Div by 0

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)

Code instances:

https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L40 amounts might be 0 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L116 amounts might be 0

Tokens with fee on transfer are not supported

There are ERC20 tokens that charge fee for every transfer() / transferFrom().

Vault.sol#addValue() assumes that the received amount is the same as the transfer amount, and uses it to calculate attributions, balance amounts, etc. But, the actual transferred amount can be lower for those tokens. Therefore it's recommended to use the balance change before and after the transfer instead of the amount. This way you also support the tokens with transfer fee - that are popular.

Code instances:

https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L95 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CNft.sol#L139

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

  1. 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:

CErc20.sol, 209 (doTransferOut), token.transfer(to, amount); CErc20.sol, 174 (doTransferIn), token.transferFrom(from, address(this), amount); CErc20.sol, 138 (sweepToken), token.transfer(admin, balance);

Awards

139.9606 USDC - $139.96

Labels

bug
G (Gas Optimization)

External Links

Unnecessary equals boolean

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

Code instances:

Comptroller.sol, 997: require(msg.sender == admin || state == true, "only admin can unpause"); Comptroller.sol, 142: if (marketToJoin.accountMembership[borrower] == true) { Comptroller.sol, 1011: require(msg.sender == admin || state == true, "only admin can unpause"); Comptroller.sol, 1029: require(msg.sender == admin || state == true, "only admin can unpause"); Comptroller.sol, 1065: require(market.isListed == true, "comp market is not listed");

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:

Comptroller.sol, collateralFactorMaxMantissa Comptroller.sol, closeFactorMinMantissa Comptroller.sol, closeFactorMaxMantissa

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:

Comptroller.sol, distributeBorrowerComp, borrowState Comptroller.sol, updateCompSupplyIndex, compAccrued Comptroller.sol, liquidateCalculateSeizeTokens, exchangeRateMantissa Comptroller.sol, distributeSupplierComp, supplyState Comptroller.sol, updateCompBorrowIndex, borrowAmount

Change transferFrom to transfer

'transferFrom(address(this), , **)' could be replaced by the following more gas efficient 'transfer(, **)' This replacement is more gas efficient and improves the code quality.

Code instances:

CNft.sol, 152 : IERC721(underlying).safeTransferFrom(address(this), msg.sender, tokenIds[i], ""); CNft.sol, 141 : IERC1155(underlying).safeBatchTransferFrom(address(this), msg.sender, tokenIds, amounts, "");

Unnecessary array boundaries check when loading an array element twice

There are places in the code (especially in for-each loops) that loads the same array element more than once. In such cases, only one array boundaries check should take place, and the rest are unnecessary. Therefore, this array element should be cached in a local variable and then be loaded again using this local variable, skipping the redundant second array boundaries check:

Code instance:

Comptroller.sol.claimComp - double load of holders[j]

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:

CEther.sol, , 178 ERC1155Enumerable.sol, ids, 51 CNft.sol, vars, 176 Comptroller.sol, assets, 591 Comptroller.sol, allMarkets, 928

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: CNft.sol, i, 176 just change to unchecked: CNft.sol, i, 98 change to prefix increment and unchecked: Comptroller.sol, i, 591 change to prefix increment and unchecked: Comptroller.sol, i, 1223 change to prefix increment and unchecked: Comptroller.sol, i, 199

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:

Comptroller.sol, 928 Comptroller.sol, 1223 Comptroller.sol, 949 Comptroller.sol, 591 Comptroller.sol, 1240

Unnecessary default assignment

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

Code instances:

Comptroller.sol (L#81) : uint internal constant collateralFactorMaxMantissa = 0.9e18; Comptroller.sol (L#75) : uint internal constant closeFactorMinMantissa = 0.05e18; Comptroller.sol (L#78) : uint internal constant closeFactorMaxMantissa = 0.9e18;

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: CNft.sol, In line 93, Require message length to shorten: 35, The message: CNFT: Liquidator cannot be borrower Solidity file: Comptroller.sol, In line 996, Require message length to shorten: 39, The message: only pause guardian and admin can pause Solidity file: Comptroller.sol, In line 702, Require message length to shorten: 34, The message: cNFT is from the wrong comptroller Solidity file: Comptroller.sol, In line 171, Require message length to shorten: 37, The message: exitMarket: getAccountSnapshot failed Solidity file: Comptroller.sol, In line 995, Require message length to shorten: 40, The message: cannot pause a market that is not listed

Unnecessary Reentrancy Guards

Where there is onlyOwner or Initializer modifer, the reentrancy gaurd isn't necessary (unless you don't trust the owner or the deployer, which will lead to full security breakdown of the project and we believe this is not the case) This is a list we found of such occurrences:

Code instance:

CNft.sol no need both nonReentrant and onlyOwner modifiers in call

Use != 0 instead of > 0

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

Code instances:

CErc20.sol, 194: change 'balance > 0' to 'balance != 0' CNft.sol, 127: change 'balance > 0' to 'balance != 0' Comptroller.sol, 302: change 'redeemAmount > 0' to 'redeemAmount != 0' Comptroller.sol, 1255: change 'amount > 0' to 'amount != 0'

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

UniswapV2PriceOracle.sol (L#32) - pairObservations[pair][numPairObservations[pair]++ % OBSERVATION_BUFFER_SIZE] = Observation( block.timestamp, px0Cumulative, px1Cumulative );

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

Comptroller.sol, adminOrInitializing, { return msg.sender == admin || msg.sender == comptrollerImplementation; } Comptroller.sol, getAccountLiquidityInternal, { return getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0); }

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:

Comptroller.sol, _addMarketInternal UniswapV2PriceOracle.sol, price0Cumulative UniswapV2PriceOracle.sol, price0 Comptroller.sol, getAccountLiquidityInternal Comptroller.sol, setCompSpeedInternal

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

CNftPriceOracle.sol, 98 : You should cache the used power of 10 as constant state variable since it's used several times (3): return FullMath.mulDiv(pricePerToken, 1018 - mintFee, 1018);

Change if -> revert pattern to require

Change if -> revert pattern to 'require' to save gas and improve code quality, if (some_condition) { revert(revert_message) }

to: require(!some_condition, revert_message)

In the following locations:

Code instance:

Comptroller.sol, 303

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:

CErc20.sol CEther.sol Comptroller.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/bunker-protocol/tree/main/contracts/Comptroller.sol#L85 https://github.com/code-423n4/bunker-protocol/tree/main/contracts/CEther.sol#L29
AuditHub

A portfolio for auditors, a security profile for protocols, a hub for web3 security.

Built bymalatrax Β© 2024

Auditors

Browse

Contests

Browse

Get in touch

ContactTwitter