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

[G-01] - Use `do-while` loop instead of `for-loop` to save users gas cost.

Details

do-while does not check the first condition and prevents the assembly from executing lots of opcodes needed for conditions checks and all these places are right for it because these all always execute the code inside loops on the first condition.

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L118

Deployment Cost

Calculation Type Before After Gas Saved
Avg 1004332 1004274 58
// For example ETH / USD, BTC / USD, MKR / USD, etc
- for (uint256 i = 0; i < tokenAddresses.length; i++) {
+ uint256 i;
+
+ do {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
- }
+ i++;
+ } while (i < tokenAddresses.length);
+
i_dsc = DecentralizedStableCoin(dscAddress);

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L353-L357

Calculation Type Before After Gas Saved
Avg 42356 42211 145
// the price, to get the USD value
- for (uint256 i = 0; i < s_collateralTokens.length; i++) {
+ uint256 i;
+ do {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
- }
+ i++;
+ } while (i < s_collateralTokens.length);
+
return totalCollateralValueInUsd;

Support

FAQs

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