Summary
s_collateralTokens
and s_collateralDeposited
are state variables, they are stored in the contract's storage and can be expensive to read from storage. If these variables do not change frequently, it is possible to optimize gas costs by caching them in local variables.
Vulnerability Details
We can cache the state variables "s_collateralTokens" and "s_collateralDeposited" in local variables within the function. This way, the function will read the state variables from storage only once, resulting in potential gas savings
https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L350-L359
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;
}
Recommendations
@@ -1,12 +1,9 @@
function getAccountCollateralValue(address user) public view returns (uint256 totalCollateralValueInUsd) {
- address[] memory collateralTokens = s_collateralTokens; // Cache state variable in local variable
- mapping(address => uint256) storage collateralDeposited = s_collateralDeposited; // Cache state variable in local variable
-
// 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; i++) {
- address token = collateralTokens[i];
- uint256 amount = collateralDeposited[user][token];
+ address token = s_collateralTokens[i];
+ uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
}
return totalCollateralValueInUsd;