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

For loops can be optimized to save gas

Summary

Currently there are two for loops in the DSCEngine.sol contract - one in the constructor and one during the collateral value calculation.

Vulnerability Details

Both for loops can be optimized to reduce gas costs during deployment and during calculation of the user healthFactor which is done on most external calls to the DSCEngine.sol.

Impact

Unnecessary gas consumption

Tools Used

Manual Review

Recommendations

  1. Store the loop end variable as a local variable before the actual for loop.

  2. Increment can be added in a unchecked block as overflow is almost impossible.

Old Loop in Constructor:

for (uint256 i = 0; i < tokenAddresses.length; i++) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
}

Optimized Loop in Constructor:

uint256 lenght = tokenAddresses.length;
for (uint256 i = 0; i < lenght;) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
unchecked {
i++
}
}

Old Loop in collateral value calculation:

for (uint256 i = 0; i < s_collateralTokens.length; i++) {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
}

Optimized Loop in collateral value calculation:

uint256 collateralTokensLenght = s_collateralTokens.length;
for (uint256 i = 0; i < collateralTokensLenght ;) {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
unchecked {
i++
}
}

Support

FAQs

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