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

Using `unchecked` in `for` loops can save plenty of gas

Summary

In the DSCEngine.sol contract, unchecked can reduce a significant amount of gas by adding the increment of counter i in a for loop under an unchecked section.

Vulnerability Details

In cases when we know that a particular variable cannot go below or beyond a specific numerical limit, implementing unchecked is good for reducing gas usage. For instance, you can find the gas usage by my deployment on Sepolia network, the as-is deployment consumed about 1,138,542 gas, whereas, when I implemented the unchecked method for 2 for loops, the gas dropped to 1,130,555 which is a difference of 7987 gas.

Original Contract

Contract with unchecked for loop

Impact

Considerable save on gas.

Tools Used

  • Manual audit

  • Foundry

Recommendations

Implementing this simple change as shown below can help serve the impact:

Line 130 under constructor:

constructor(
address[] memory tokenAddresses,
address[] memory priceFeedAddresses,
address dscAddress
) {
// USD Price Feeds
if (tokenAddresses.length != priceFeedAddresses.length) {
revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength();
}
// For example ETH / USD, BTC / USD, MKR / USD, etc
for (uint256 i = 0; i < tokenAddresses.length; ) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
unchecked {
++i;
}
}
i_dsc = DecentralizedStableCoin(dscAddress);
}

The same can be done in the for loop on Line 432under thegetAccountCollateralValue()` function:

function getAccountCollateralValue(
address user
) public view returns (uint256 totalCollateralValueInUsd) {
// loop through each collateral token, get the amount they have deposited and map it to
// the price, to get the USD value
for (uint256 i = 0; i < s_collateralTokens.length; ) {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
unchecked {
++i;
}
}
return totalCollateralValueInUsd;
}

Support

FAQs

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