15,000 USDC
View results
Submission Details
Severity: gas

Inefficient Loop Structure in `getAccountCollateralValue` Function

Summary

The function getAccountCollateralValue employs an inefficient loop structure by using the length of the s_collateralTokens array in the loop condition.

Vulnerability Details

This approach can result in suboptimal gas usage, especially if the s_collateralTokens array is expected to grow in size over time. Using the array's length in the loop condition forces the function to iterate through the entire array on each invocation, even if the user's collateral is only associated with a small subset of tokens.

Impact

gas cost issue

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
// @audit-issue gas optmisation
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;
}

Tools Used

Manual Review and slither

Recommendations

it is more gas efficient to cache the array it in some local variable and use that variable instead,

function getAccountCollateralValue(address user) public view returns (uint256 totalCollateralValueInUsd) {
address[] tokens = s_collateralTokens;
for (uint256 i = 0; i < tokens.length; i++) {
address token = tokens[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.