Platform: Code4rena
Start Date: 11/08/2022
Pot Size: $40,000 USDC
Total HM: 8
Participants: 108
Period: 4 days
Judge: hickuphh3
Total Solo HM: 2
Id: 152
League: ETH
Rank: 50/108
Findings: 2
Award: $62.02
🌟 Selected for report: 0
🚀 Solo Findings: 0
🌟 Selected for report: Saw-mon_and_Natalie
Also found by: 0x1f8b, 0x52, 0xDjango, 0xNazgul, 0xSmartContract, 0xSolus, 0xackermann, 0xmatt, 0xsolstars, Aymen0909, Bnke0x0, Chom, Deivitto, DevABDee, Dravee, ElKu, IllIllI, JC, Kumpa, Lambda, LeoS, MiloTruck, PwnedNoMore, ReyAdmirado, Rohan16, Rolezn, Ruhum, Sm4rty, TomJ, Treasure-Seeker, Vexjon, Waze, Yiko, __141345__, apostle0x01, auditor0517, berndartmueller, bin2chen, bobirichman, brgltd, bulej93, c3phas, carlitox477, cccz, cryptphi, csanuragjain, d3e4, danb, delfin454000, durianSausage, erictee, fatherOfBlocks, gogo, iamwhitelights, joestakey, jonatascm, ladboy233, mics, oyc_109, rbserver, ret2basic, robee, rokinot, rvierdiiev, shenwilly, sikorico, simon135, thank_you, wagmi, yash90, zeesaw, zkhorse
41.4024 USDC - $41.40
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: WETH9.sol, In line 55 with Empty Require message. Solidity file: WETH9.sol, In line 29 with Empty Require message.
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.
FETH.sol.approve spender WETH9.sol.transfer dst FETHMarketMock.sol.marketChangeLockup unlockFrom MinterRole.sol.grantMinter account
WETH address is hardcoded but it may differ on other chains, e.g. Polygon, so make sure to check this before deploying and update if necessary You should consider injecting WETH address via the constructor. (previous issue: https://github.com/code-423n4/2021-10-ambire-findings/issues/54)
Hardcoded weth address in FETH.sol
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:
NFTDropCollection.sol, initialize, 120 NFTDropMarket.sol, initialize, 100 NFTCollection.sol, initialize, 105 SequentialMintCollectionMock.sol, initializeWithModifier, 10 PercentSplitETH.sol, initialize, 129 NFTCollectionFactory.sol, initialize, 192 FoundationTreasury.sol, initialize, 66
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.
BasicERC721.sol, balanceOf FETH.sol, transferFrom FETH.sol, marketLockupFor
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).
NFTDropCollection.sol, updateMaxTokenId NFTCollectionFactory.sol, adminUpdateNFTCollectionImplementation NFTCollectionFactory.sol, adminUpdateNFTDropCollectionImplementation NFTCollection.sol, updateMaxTokenId NFTCollection.sol, updateBaseURI NFTDropCollection.sol, updatePreRevealContent
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.
OZERC165Checker.sol: function supportsERC165InterfaceUnchecked parameter account isn't used. (supportsERC165InterfaceUnchecked is internal) FETHMarketMock.sol: function marketChangeLockup parameter unlockAmount isn't used. (marketChangeLockup is external) FETHMarketMock.sol: function marketLockupFor parameter amount isn't used. (marketLockupFor is public) MockRoyaltyRegistry.sol: function setRoyaltyLookupAddress parameter tokenAddress isn't used. (setRoyaltyLookupAddress is external) FETHMarketMock.sol: function marketChangeLockup parameter depositFor isn't used. (marketChangeLockup is external) FETHMarketMock.sol: function marketChangeLockup parameter depositAmount isn't used. (marketChangeLockup is external) SendValueWithFallbackWithdraw.sol: function _sendValueWithFallbackWithdraw parameter gasLimit isn't used. (_sendValueWithFallbackWithdraw is internal) FETHMarketMock.sol: function marketLockupFor parameter account isn't used. (marketLockupFor is public) FETHMarketMock.sol: function marketChangeLockup parameter unlockExpiration isn't used. (marketChangeLockup is external) FETHMarketMock.sol: function marketChangeLockup parameter unlockFrom isn't used. (marketChangeLockup is external) MockRoyaltyRegistry.sol: function setRoyaltyLookupAddress parameter royaltyAddress isn't used. (setRoyaltyLookupAddress is external)
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-08-foundation/tree/main/contracts/mocks/BasicERC721.sol#L263 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L383 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/PercentSplitETH.sol#L236 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L267 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/mocks/BasicERC721.sol#L244
The following functions are missing commenting as describe below:
FETHNode.sol, _tryUseFETHBalance (internal), parameters totalAmount, shouldRefundSurplus not commented
To give more trust to users: functions that set key/critical variables should be put behind a timelock.
https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/mocks/RoyaltyRegistry/MockRoyaltyRegistry.sol#L9 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/mocks/FETHMarketMock.sol#L14 https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/mocks/BasicERC721.sol#L81
use openzeppilin's safeCast in:
https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L514 : unsafe cast uint32(escrowIndex) https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L615 : unsafe cast uint96(amount) https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L498 : unsafe cast uint96(amount) https://github.com/code-423n4/2022-08-foundation/tree/main/contracts/FETH.sol#L393 : unsafe cast uint96(amount)
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
PercentSplitETH.sol, 245 (_splitERC20Tokens), try erc20Contract.transfer(_shares[0].recipient, amountToSend) { PercentSplitETH.sol, 236 (_splitERC20Tokens), try erc20Contract.transfer(share.recipient, amountToSend) {
#0 - HardlyDifficult
2022-08-18T18:41:27Z
Require with empty message
Invalid - this is a mock contract.
Not verified input
FETH and mocks were out of scope. For MinterRole we wanted to remain consistent with grantRole from the OZ implementation which would still be publicly available.
Hardcoded WETH
Invalid, we don't use WETH.
Use constructor to initialize templates
Agree this is a good best practice to add. Will fix.
Named return issue
Invalid - mocks and FETH were out of scope.
In the following public update functions no value is returned
Invalid. These functions do not have a return value and they don't seem to require one.
Never used parameters
Invalid - those examples appear to have valid use cases.
Check transfer receiver is not 0 to avoid burned money
Invalid. Those contracts were out of scope.
Missing natspec comments
Fair feedback -- for natspec we aim for complete coverage of the public interfaces but for internal/private/libraries we have some gaps in order to reduce redundancy, for those we aim to include comments where things are unclear or not obvious from the function and variable names.
Add a timelock
Fair feedback and we may revisit this in the future.
Unsafe Cast
Invalid. FETH was out of scope.
transfer return value of a general ERC20 is ignored
Invalid. PercentSplitETH was out of scope.
🌟 Selected for report: Dravee
Also found by: 0x040, 0x1f8b, 0xDjango, 0xHarry, 0xNazgul, 0xSmartContract, 0xbepresent, 0xkatana, Amithuddar, Aymen0909, Bnke0x0, Chom, CodingNameKiki, Deivitto, DevABDee, Diraco, ElKu, Fitraldys, Funen, IllIllI, JC, LeoS, Metatron, MiloTruck, Noah3o6, ReyAdmirado, Rohan16, Rolezn, Saw-mon_and_Natalie, Sm4rty, SpaceCake, TomJ, Tomio, Trabajo_de_mates, Waze, Yiko, __141345__, ajtra, apostle0x01, bobirichman, brgltd, bulej93, c3phas, cRat1st0s, carlitox477, d3e4, durianSausage, erictee, fatherOfBlocks, gerdusx, gogo, hakerbaya, ignacio, jag, joestakey, ladboy233, medikko, mics, newfork01, oyc_109, pfapostol, robee, rvierdiiev, sach1r0, saian, samruna, sikorico, simon135, wagmi, zeesaw, zkhorse, zuhaibmohd
20.6172 USDC - $20.62
In the following files there are state variables that could be set immutable to save gas.
versionNFTCollection in NFTCollectionFactory.sol paymentAddress in NFTDropCollection.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.
AdminRole.sol, __gap OZAccessControlUpgradeable.sol, __gap NFTDropMarketFixedPriceSale.sol, __gap MarketSharedCore.sol, __gap WETH9.sol, symbol SendValueWithFallbackWithdraw.sol, __gap_was_pendingWithdrawals WETH9.sol, name Gap10000.sol, __gap WETH9.sol, decimals NFTDropMarketCore.sol, __gap CollateralManagement.sol, __gap FoundationTreasuryNode.sol, __gap_was_treasury
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.
OZERC165Checker.sol, supportsERC165InterfaceUnchecked, encodedParams
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:
PercentSplitETH.sol.getShares - double load of _shares[i]
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++) { ... }
PercentSplitETH.sol, shares, 320 PercentSplitETH.sol, _shares, 115
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:
just change to unchecked: PercentSplitETH.sol, i, 320 just change to unchecked: PercentSplitETH.sol, i, 115
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:
PercentSplitETH.sol, 320 PercentSplitETH.sol, 115
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:
PercentSplitETH.sol: BASIS_POINTS is read twice in initialize
Unnecessary default assignments, you can just declare and it will save gas and have the same meaning.
BasicERC721WithoutOwnerOfRevert.sol (L#18) : uint256 private id = 0;
Use bytes32 instead of string to save gas whenever possible. String is a dynamic data structure and therefore is more gas consuming then bytes32.
FETH.sol (L135), string public constant symbol = "FETH"; WETH9.sol (L6), string public name = "Wrapped Ether"; WETH9.sol (L7), string public symbol = "WETH"; FETH.sol (L130), string public constant name = "Foundation ETH";
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: BasicERC721.sol, In line 263, Require message length to shorten: 37, The message: ERC721: transfer from incorrect owner Solidity file: PercentSplitETH.sol, In line 148, Require message length to shorten: 35, The message: Split: Total amount must equal 100% Solidity file: NFTDropCollection.sol, In line 130, Require message length to shorten: 40, The message: NFTDropCollection: `_symbol` must be set Solidity file: NFTDropCollection.sol, In line 179, Require message length to shorten: 38, The message: NFTDropCollection: Exceeds max tokenId Solidity file: NFTCollection.sol, In line 263, Require message length to shorten: 35, The message: NFTCollection: tokenCID is required Solidity file: NFTDropCollection.sol, In line 238, Require message length to shorten: 39, The message: NFTDropCollection: use `reveal` instead Solidity file: NFTCollection.sol, In line 264, Require message length to shorten: 37, The message: NFTCollection: NFT was already minted Solidity file: PercentSplitETH.sol, In line 191, Require message length to shorten: 33, The message: Split: ERC20 tokens must be split Solidity file: PercentSplitETH.sol, In line 136, Require message length to shorten: 35, The message: Split: Share must be less than 100% Solidity file: NFTCollectionFactory.sol, In line 262, Require message length to shorten: 40, The message: NFTCollectionFactory: Symbol is required Solidity file: BasicERC721.sol, In line 59, Require message length to shorten: 33, The message: ERC721: approval to current owner Solidity file: BasicERC721.sol, In line 264, Require message length to shorten: 36, The message: ERC721: transfer to 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)
NFTDropMarketFixedPriceSale.sol, 183: change 'balance > 0' to 'balance != 0' WETH9.sol, 55: change 'balance > 0' to 'balance != 0' WETH9.sol, 29: change 'balance > 0' to 'balance != 0' LockedBalance.sol, 113: change 'balance > 0' to 'balance != 0' NFTDropCollection.sol, 131: change '_maxTokenId > 0' to '_maxTokenId != 0'
You can use unchecked in the following calculations since there is no risk to overflow:
FETH.sol (L#572) - expiration = lockupDuration + block.timestamp.ceilDiv(lockupInterval) * lockupInterval; FETH.sol (L#765) - if (escrow.expiration >= block.timestamp && escrow.totalAmount != 0) { ++lockedCount;
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.)
OZAccessControlUpgradeable.sol, getRoleMemberCount, { return _roles[role].members.length(); } BasicERC721.sol, _exists, { return _owners[tokenId] != address(0); } OZAccessControlUpgradeable.sol, getRoleMember, { return _roles[role].members.at(index); } OZAccessControlUpgradeable.sol, hasRole, { return _roles[role].members.contains(account); } NFTCollectionFactory.sol, _getSalt, { return keccak256(abi.encodePacked(creator, nonce)); } AddressLibrary.sol, callAndReturnContractAddress, { return callAndReturnContractAddress(call.target, call.callData); }
The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.
NFTDropCollection.sol, _burn MarketSharedCore.sol, _getSellerOf NFTCollection.sol, _burn OZAccessControlUpgradeable.sol, _revokeRole SequentialMintCollection.sol, _burn ArrayLibrary.sol, capLength BasicERC721.sol, _safeTransfer
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:
BasicERC721.sol, 303
#0 - HardlyDifficult
2022-08-19T00:43:30Z
State variables that could be set immutable
Invalid. versionNFTCollection
increments with each new template. paymentAddress
is set in the initializer for each proxy individually.
Unused state variables
Invalid - these gaps are here to help preserve upgrade compatibility and to leave room for changes in future upgrades.
Unused declared local variables
Invalid, that is called.
Unnecessary array boundaries check when loading an array element twice
Potentially valid but that file was out of scope for this contest.
Cache Array Length Outside of Loop
May be theoretically valid, but won't fix. I tested this: gas-reporter and our gas-stories suite is reporting a small regression using this technique. It also hurts readability a bit so we wouldn't want to include it unless it was a clear win.
++i costs less than i++
Agree and will fix.
Don't initialize variables with default values.
Invalid. This optimization technique is no longer applicable with the current version of Solidity.
Storage double reading. Could save SLOAD
Invalid. Constants do not use SLOAD
Use bytes32 instead of string to save gas whenever possible
FETH and mocks are out of scope.
Use short error messages
Agree but won't fix. We use up to 64 bytes, aiming to respect the incremental cost but 32 bytes is a bit too short to provide descriptive error messages for our u
Use != 0 instead of > 0
Invalid. We tested the recommendation and got the following results:
createNFTDropCollection gas reporter results: using > 0 (current): - 319246 · 319578 · 319361 using != 0 (recommendation): - 319252 · 319584 · 319367 impact: +6 gas
unchecked
FETH is out of scope
Consider inline the following functions to save gas Inline one time use functions
This may save a bit of gas, but occasionally helpers improve readability.
Change if -> revert pattern to require
Invalid - the code instance is a mock file.