15,000 USDC
View results
Submission Details
Severity: gas
Valid

++i/i++ should be unchecked{++i}/unchecked{i++} when it is not possible for them to overflow

Since s_collateralTokens has the same length as tokenAddresses from the constructor and cannot be modified, the second for-loop will run for exactly the same number of iterations as the one in the constructor. The first for-loop would have been revert in the constructor if i ever became greater than or equal to tokenAddresses.length. Therefore, the second for-loop can safely use unchecked { i++; } to increment i. This saves 30-40 gas per loop

File src/DSCEngine.sol: Constructor:
118: for (uint256 i = 0; i < tokenAddresses.length; i++) { //The For-Loop runs until i is greater than tokenAddresses.length
119: s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
120: s_collateralTokens.push(tokenAddresses[i]); //s_collateralTokens becomes equal to tokenAddresses after this For-Loop
121: }
File src/DSCEngine.sol: getAccountCollateralValue:
353: for (uint256 i = 0; i < s_collateralTokens.length;) { //i becomes just as large as in the constructor, so unchecked can be used
354: address token = s_collateralTokens[i];
355: uint256 amount = s_collateralDeposited[user][token];
356: totalCollateralValueInUsd += getUsdValue(token, amount);
357: unchecked {i++;} //Use unchecked to increase i
358: }

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/d1c5501aa79320ca0aeaa73f47f0dbc88c7b77e2/src/DSCEngine.sol#L353C1-L357C10

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.