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

avoid iterating over all collateral tokens

Summary

To optimize the function getAccountCollateralValue and avoid iterating over all collateral tokens, you can use an accumulator variable to calculate the total collateral value in USD. Here's how you can do it:

Vulnerability Detail

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;
}

You can optimize this function by replacing the for loop with an accumulator variable. Here's an example of how to do it:

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 = totalCollateralValueInUsd + getUsdValue(token, amount); //@audit or totalCollateralValueInUsd += getUsdValue(token, amount);
}
return totalCollateralValueInUsd;
}

The optimization involves removing the for loop and instead using a variable totalCollateralValueInUsd that gets updated directly in each iteration. This way, you avoid the additional iterations and reduce the gas cost by avoiding multiple addition operations in each iteration.

However, it's essential to keep in mind that this optimization is only suitable if the length of s_collateralTokens is not too large since if the list is very long, the function could exceed the gas execution limit. If you expect the list of collateral tokens to be large, you might consider a more advanced approach, such as using compact storage design patterns or dividing the function into smaller batches to avoid exceeding the gas limit.

Support

FAQs

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