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

Improvement in the for loops to save gas.

Summary

Use this methods to save gas while using for loops.

  1. No need to explicitly initialize variables with default values (eg : uint256 i=0).

  2. The increment in the for loop’s post condition can be made unchecked.

  3. Caching the length in for loops.

Vulnerability Details

  1. Instead of this loop at https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/d1c5501aa79320ca0aeaa73f47f0dbc88c7b77e2/src/DSCEngine.sol#L118C9-L121C10

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

Use this for loop

for (uint256 i ; i < tokenAddresses.length; ) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
unchecked{
i++;
}
}
  1. Instead of this loop at https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/d1c5501aa79320ca0aeaa73f47f0dbc88c7b77e2/src/DSCEngine.sol#L353C8-L357C10

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

Use this for loop

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

Tools Used

Manual Review

Support

FAQs

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