15,000 USDC
View results
Submission Details
Severity: gas

Gas inefficiency due to uncached storage array length

Summary

Gas inefficiency due to uncached storage array length

Vulnerability Details

The DSCEngine.sol:353 contains the getAccountCollateralValue function, which calculates the total collateral value in USD for a specific user. However, the function uses a for loop to iterate over the s_collateralTokens storage array and references s_collateralTokens.length in each iteration. This inefficient practice leads to unnecessary storage reads, resulting in increased gas costs.

Vulnerable Code Snippet:

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

Impact

The inefficient use of the s_collateralTokens.length member in the for loop can lead to higher gas costs for contract users.

Tools Used

Manual Review

Recommendations

Cache the length of the s_collateralTokens storage array in a local variable before entering the for loop. Since the array length remains unchanged within the loop, this optimization will decrease the number of storage reads and significantly improve the contract's gas efficiency.

Support

FAQs

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