Platform: Code4rena
Start Date: 07/04/2022
Pot Size: $100,000 USDC
Total HM: 20
Participants: 62
Period: 7 days
Judge: LSDan
Total Solo HM: 11
Id: 107
League: ETH
Rank: 21/62
Findings: 2
Award: $559.16
π Selected for report: 0
π Solo Findings: 0
π Selected for report: Dravee
Also found by: 0x1f8b, 0xDjango, 0xkatana, AuditsAreUS, Cityscape, Foundation, Funen, Hawkeye, IllIllI, JC, JMukesh, Jujic, Kthere, PPrieditis, Picodes, Ruhum, TerrierLover, TrungOre, WatchPug, berndartmueller, catchup, cccz, cmichel, delfin454000, dy, ellahi, hickuphh3, horsefacts, hubble, hyh, ilan, jayjonah8, kebabsec, kenta, minhquanym, pauliax, rayn, reassor, rfa, robee, samruna
449.5934 USDC - $449.59
Title: Using safeERC20 for non ERC20 Severity: Low Risk
You can't use SafeERC20 for non ERC20 protocols (as for example ERC721) due to undefined behavior of it. The following files does that: yVaultLPFarming.sol, 14 : using SafeERC20 for IYVault;
Title: Add a timelock Severity: Low Risk
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-jpegd/tree/main/contracts/vaults/NFTVault.sol#L336 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/vaults/NFTVault.sol#L271 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/vaults/yVault/strategies/StrategyPUSDConvex.sol#L177 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/vaults/NFTVault.sol#L222
Title: Init function calls an owner function Severity: Low Risk
Init function that calls an onlyOwner function is problematic since sometimes the initializer or the one applies the constructor isn't necessary the owner of the protocol. And if a contract does it then you might get a situation that all the onlyOwner functions are blocked since only the factory contract may use them but isn't necessary support it. yVault.sol.constructor - calls setController yVault.sol.constructor - calls setAvailableTokensRate
Title: Does not validate the input fee parameter Severity: Low Risk
Some fee parameters of functions are not checked for invalid values. Validate the parameters:
Controller.constructor (_feeAddress) NFTVault.setOrganizationFeeRate (_organizationFeeRate) Controller.setFeeAddress (_feeAddress) StrategyPUSDConvex.constructor (_performanceFee) StrategyPUSDConvex.setPerformanceFee (_performanceFee)
Title: Check transfer receiver is not 0 to avoid burned money Severity: Low Risk
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-jpegd/tree/main/contracts/helpers/CryptoPunksHelper.sol#L43 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/farming/LPFarming.sol#L128 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/farming/LPFarming.sol#L225 https://github.com/code-423n4/2022-04-jpegd/tree/main/contracts/farming/LPFarming.sol#L339
Title: Init frontrun Severity: Low Risk
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:
FungibleAssetVaultForDAO.sol, initialize, 66 JPEGStaking.sol, initialize, 21 NFTVault.sol, initialize, 139 CryptoPunksHelper.sol, initialize, 19 EtherRocksHelper.sol, initialize, 19
Title: Missing commenting Severity: Low Risk
The following functions are missing commenting as describe below: yVaultLPFarming.sol, _withdrawReward (internal), @return is missing LPFarming.sol, _withdrawReward (internal), @return is missing yVault.sol, decimals (public), @return is missing LPFarming.sol, _normalizeBlockNumber (internal), parameter blockNumber not commented
Title: Not verified input Severity: Low Risk
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. StrategyPUSDConvex.sol.setUSDCVault _vault yVault.sol.constructor _controller yVault.sol.setFarmingPool _farm CryptoPunksHelper.sol.safeTransferFrom _from
Title: Not verified owner Severity: Low Risk
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. NFTVault.sol._openPosition _owner
Title: Solidity compiler versions mismatch Severity: Low Risk
The project is compiled with different versions of solidity, which is not recommended because it can lead to undefined behaviors.
Title: Missing non reentrancy modifier Severity: Low Risk
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..
NFTVault.sol, claimExpiredInsuranceNFT is missing a reentrancy modifier JPEGStaking.sol, initialize is missing a reentrancy modifier NFTVault.sol, setOrganizationFeeRate is missing a reentrancy modifier NFTVault.sol, setLiquidationLimitRate is missing a reentrancy modifier
Title: Unbounded loop on array that can only grow can lead to DoS Severity: Low/Med Risk
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.
LPFarming.sol (L347): Unbounded loop on the array poolInfo that can be publicly pushed by ['add'] and can't be pulled LPFarming.sol (L279): Unbounded loop on the array poolInfo that can be publicly pushed by ['add'] and can't be pulled
Title: transfer return value of a general ERC20 is ignored Severity: High Risk
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):
NFTVault.sol, 560 (_openPosition), nftContract.transferFrom(_owner, address(this), _nftIndex);
Title: Require with not comprehensive message Severity: Low Risk
The following requires has a non comprehensive messages. This is very important to add a comprehensive message for any require. Such that the user has enough information to know the reason of failure: Solidity file: StrategyPUSDConvex.sol, In line 266 with Require message: jpeg Solidity file: JPEGLock.sol, In line 71 with Require message: locked
π Selected for report: Dravee
Also found by: 0v3rf10w, 0x1f8b, 0xDjango, 0xNazgul, 0xkatana, Cityscape, Cr4ckM3, FSchmoede, Foundation, Funen, Hawkeye, IllIllI, JMukesh, Meta0xNull, PPrieditis, Picodes, TerrierLover, Tomio, WatchPug, berndartmueller, catchup, delfin454000, dirk_y, ellahi, hickuphh3, ilan, kebabsec, kenta, nahnah, rayn, rfa, robee, rokinot, saian, securerodd, slywaters, sorrynotsorry
109.5676 USDC - $109.57
Title: Unnecessary index init Severity: GAS
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:
NFTVault.sol, 181 StrategyPUSDConvex.sol, 231 LPFarming.sol, 281 StrategyPUSDConvex.sol, 145 LPFarming.sol, 348
Title: Use unchecked to save gas for certain additive calculations that cannot overflow Severity: GAS
You can use unchecked in the following calculations since there is no risk to overflow:
JPEGLock.sol (L#57) - owner: _account, unlockAt: block.timestamp + lockTime, lockAmount: _lockAmount NFTVault.sol (L#887) - require( position.liquidatedAt + settings.insuraceRepurchaseTimeLimit >= block.timestamp, "insurance_expired" ); NFTVault.sol (L#927) - require( position.liquidatedAt + settings.insuraceRepurchaseTimeLimit < block.timestamp, "insurance_not_expired" );
Title: Prefix increments are cheaper than postfix increments Severity: GAS
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: StrategyPUSDConvex.sol, i, 231 change to prefix increment and unchecked: StrategyPUSDConvex.sol, i, 145 change to prefix increment and unchecked: NFTVault.sol, i, 181 just change to unchecked: LPFarming.sol, pid, 281 change to prefix increment and unchecked: LPFarming.sol, i, 348
Title: Unnecessary functions Severity: GAS
The following functions are not used at all. Therefore you can remove them to save deployment gas and improve code clearness. EtherRocksHelper.sol, _encodeFlashEscrowPayload CryptoPunksHelper.sol, _encodeFlashEscrowPayload
Title: Storage double reading. Could save SLOAD Severity: GAS
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:
FungibleAssetVaultForDAO.sol: debtAmount is read twice in repay
Title: Use != 0 instead of > 0 Severity: GAS
Using != 0 is slightly cheaper than > 0. (see https://github.com/code-423n4/2021-12-maple-findings/issues/75 for similar issue)
yVaultLPFarming.sol, 101: change '_amount > 0' to '_amount != 0' yVaultLPFarming.sol, 118: change '_amount > 0' to '_amount != 0' yVault.sol, 143: change '_amount > 0' to '_amount != 0' LPFarming.sol, 239: change '_amount > 0' to '_amount != 0' JPEGStaking.sol, 32: change '_amount > 0' to '_amount != 0' NFTVault.sol, 764: change '_amount > 0' to '_amount != 0' yVaultLPFarming.sol, 119: change 'balance > 0' to 'balance != 0' NFTVault.sol, 687: change '_amount > 0' to '_amount != 0' yVault.sol, 167: change '_shares > 0' to '_shares != 0' FungibleAssetVaultForDAO.sol, 142: change 'amount > 0' to 'amount != 0' JPEGStaking.sol, 46: change 'balance > 0' to 'balance != 0' LPFarming.sol, 218: change '_amount > 0' to '_amount != 0' FungibleAssetVaultForDAO.sol, 180: change 'amount > 0' to 'amount != 0' JPEGStaking.sol, 46: change '_amount > 0' to '_amount != 0' FungibleAssetVaultForDAO.sol, 194: change 'amount > 0' to 'amount != 0' NFTVault.sol, 278: change '_newFloor > 0' to '_newFloor != 0' yVault.sol, 151: change 'balance > 0' to 'balance != 0' LPFarming.sol, 114: change '_rewardPerBlock > 0' to '_rewardPerBlock != 0' JPEGLock.sol, 40: change '_newTime > 0' to '_newTime != 0' FungibleAssetVaultForDAO.sol, 164: change 'amount > 0' to 'amount != 0' StrategyPUSDConvex.sol, 322: change 'balance > 0' to 'balance != 0'
Title: Unused state variables Severity: GAS
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.
FungibleAssetVaultForDAO.sol, __gap NFTVault.sol, __gap JPEGStaking.sol, __gap
Title: Unnecessary Reentrancy Guards Severity: GAS
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:
JPEGLock.sol no need both nonReentrant and onlyOwner modifiers in lockFor
Title: Do not cache msg.sender Severity: Gas
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-jpegd/tree/main/contracts/vaults/NFTVault.sol#L859
Title: Short the following require messages Severity: GAS
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: JPEG.sol, In line 21, Require message length to shorten: 35, The message: JPEG: must have minter role to mint
Title: Unnecessary equals boolean Severity: GAS
Boolean variables can be checked within conditionals directly without the use of equality operators to true/false.
Controller.sol, 87: approvedStrategies[_token][_strategy] == true, EtherRocksHelper.sol, 82: newOwner == address(this), //this should never be false CryptoPunksHelper.sol, 80: punks.punkIndexToAddress(_idx) == address(this), //this should never be false
Title: Inline one time use functions Severity: GAS
The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.
StableCoin.sol, _beforeTokenTransfer FungibleAssetVaultForDAO.sol, _getCollateralValue NFTVault.sol, _jpegPriceUSD NFTVault.sol, _openPosition FungibleAssetVaultForDAO.sol, _collateralPriceUsd StrategyPUSDConvex.sol, _swapUniswapV2
Title: Unused imports Severity: GAS
In the following files there are contract imports that aren't used Import of unnecessary files costs deployment gas (and is a bad coding practice that is important to ignore)
yVault.sol, line 9, import "../../interfaces/IYVault.sol";
Title: Cache powers of 10 used several times Severity: GAS
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:
NFTVault.sol, 466 : You should cache the used power of 10 as constant state variable since it's used several times (2): : uint256(answer) * 10**(18 - decimals);
FungibleAssetVaultForDAO.sol, 113 : You should cache the used power of 10 as constant state variable since it's used several times (2): : uint256(answer) * 10**(18 - decimals);
FungibleAssetVaultForDAO.sol, 112 : You should cache the used power of 10 as constant state variable since it's used several times (2): ? uint256(answer) / 10**(decimals - 18)
NFTVault.sol, 465 : You should cache the used power of 10 as constant state variable since it's used several times (2): ? uint256(answer) / 10**(decimals - 18)
Title: Public functions to external Severity: GAS
The following functions could be set external to save gas and improve code quality. External call cost is less expensive than of public functions.
yVault.sol, decimals yVault.sol, renounceOwnership JPEGLock.sol, renounceOwnership EtherRocksHelper.sol, renounceOwnership yVault.sol, setFarmingPool LPFarming.sol, renounceOwnership yVaultLPFarming.sol, renounceOwnership CryptoPunksHelper.sol, renounceOwnership Controller.sol, withdraw
Title: Use calldata instead of memory Severity: GAS
Use calldata instead of memory for function parameters In some cases, having function arguments in calldata instead of memory is more optimal.
FungibleAssetVaultForDAO.initialize (_creditLimitRate) NFTVault.setCreditLimitRate (_creditLimitRate) NFTVault.setOrganizationFeeRate (_organizationFeeRate) NFTVault.setLiquidationLimitRate (_liquidationLimitRate) NFTVault.setInsurancePurchaseRate (_insurancePurchaseRate) yVault.constructor (_availableTokensRate) NFTVault.setInsuranceLiquidationPenaltyRate (_insuranceLiquidationPenaltyRate) StrategyPUSDConvex.constructor (_performanceFee) NFTVault.setDebtInterestApr (_debtInterestApr) NFTVault.setValueIncreaseLockRate (_valueIncreaseLockRate)
Title: Unnecessary cast Severity: Gas
Rate NFTVault.sol.setLiquidationLimitRate - unnecessary casting Rate(_liquidationLimitRate) Rate NFTVault.sol.setDebtInterestApr - unnecessary casting Rate(_debtInterestApr) Rate NFTVault.sol.setOrganizationFeeRate - unnecessary casting Rate(_organizationFeeRate) Rate FungibleAssetVaultForDAO.sol.initialize - unnecessary casting Rate(_creditLimitRate) Rate NFTVault.sol.setInsuranceLiquidationPenaltyRate - unnecessary casting Rate(_insuranceLiquidationPenaltyRate) Rate NFTVault.sol.setValueIncreaseLockRate - unnecessary casting Rate(_valueIncreaseLockRate) Rate yVault.sol.constructor - unnecessary casting Rate(_availableTokensRate) Rate NFTVault.sol.setCreditLimitRate - unnecessary casting Rate(_creditLimitRate) Rate NFTVault.sol.setInsurancePurchaseRate - unnecessary casting Rate(_insurancePurchaseRate)
Title: Caching array length can save gas Severity: 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++) { ... } LPFarming.sol, poolInfo, 348 NFTVault.sol, _typeInitializers, 181 StrategyPUSDConvex.sol, rewardTokens._strategyConfig, 145
Title: Internal functions to private Severity: GAS
The following functions could be set private to save gas and improve code quality:
CryptoPunksHelper.sol, _encodeFlashEscrowPayload StableCoin.sol, _beforeTokenTransfer LPFarming.sol, _updatePool LPFarming.sol, _blockNumber LPFarming.sol, _massUpdatePools NFTVault.sol, _getNFTValueUSD NFTVault.sol, _calculateDebt CryptoPunksHelper.sol, _transferFrom EtherRocksHelper.sol, _encodeFlashEscrowPayload FungibleAssetVaultForDAO.sol, _getCollateralValue NFTVault.sol, _ethPriceUSD NFTVault.sol, _jpegPriceUSD NFTVault.sol, _openPosition NFTVault.sol, _getCreditLimit FungibleAssetVaultForDAO.sol, _collateralPriceUsd LPFarming.sol, _normalizeBlockNumber NFTVault.sol, _normalizeAggregatorAnswer StrategyPUSDConvex.sol, _swapUniswapV2 LPFarming.sol, _withdrawReward NFTVault.sol, _getNFTValueETH NFTVault.sol, _getLiquidationLimit NFTVault.sol, _calculateAdditionalInterest NFTVault.sol, _validateRate NFTVault.sol, _validateCreditLimitAndLiquidationRate NFTVault.sol, _getDebtAmount EtherRocksHelper.sol, _transferFrom
Title: Change transferFrom to transfer Severity: GAS
'transferFrom(address(this), , **)' could be replaced by the following more gas efficient 'transfer(, **)' This replacement is more gas efficient and improves the code quality.
NFTVault.sol, 910 : nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); NFTVault.sol, 938 : nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); NFTVault.sol, 814 : nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex); NFTVault.sol, 868 : nftContract.safeTransferFrom(address(this), msg.sender, _nftIndex);
Title: State variables that could be set immutable Severity: GAS
In the following files there are state variables that could be set immutable to save gas.
oracle in FungibleAssetVaultForDAO.sol jpeg in JPEGStaking.sol stablecoin in FungibleAssetVaultForDAO.sol
Title: Consider inline the following functions to save gas Severity: 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.) LPFarming.sol, _blockNumber, { return _normalizeBlockNumber(block.number); } NFTVault.sol, _ethPriceUSD, { return _normalizeAggregatorAnswer(ethAggregator); } NFTVault.sol, _jpegPriceUSD, { return _normalizeAggregatorAnswer(jpegAggregator); } FungibleAssetVaultForDAO.sol, _getCollateralValue, { return (amount * _collateralPriceUsd()) / _collateralUnit; } NFTVault.sol, _calculateDebt, { return totalPortion == 0 ? 0 : (total * userPortion) / totalPortion; }