15,000 USDC
View results
Submission Details
Severity: gas

Inefficient Loop Condition in getAccountCollateralValue

Summary

Inefficient Loop Condition: Loop condition i < s_collateralTokens.length in the getAccountCollateralValue function (src/DSCEngine.sol#355) should use cached array length instead of referencing length member of the storage array.

Vulnerability Details

The vulnerability lies in the loop condition i < s_collateralTokens.length in the for loop. Instead of using the cached array length, the code directly references the length member of the storage array s_collateralTokens within the loop. This can result in additional gas costs as the loop's length is checked for every iteration, which can be especially expensive if the array is large.

Impact

The impact of this vulnerability is mainly increased gas costs during contract execution. By not caching the array length before the loop, the contract will perform an SLOAD operation to fetch the array's length from storage at each iteration of the loop. This can result in unnecessary and avoidable gas expenses, making the contract less efficient and potentially costly for users.

Tools Used

Slither - static analysis framework.

Recommendations

Cache the array length before entering the loop.

function getAccountCollateralValue(address user) public view returns (uint256 totalCollateralValueInUsd) {
uint256 collateralTokensLength = s_collateralTokens.length; // Cache the array length
for (uint256 i = 0; i < collateralTokensLength; i++) {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
}
return totalCollateralValueInUsd;
}

Support

FAQs

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