15,000 USDC
View results
Submission Details
Severity: gas

DSCEngine.sol::getAccountCollateralValue function make the state variables outside the loop to save gas

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) {
// 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 = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
}
return totalCollateralValueInUsd;
}

Recommendations

diff --git a/getAccountCollateralValue.sol b/getAccountCollateralValue.org.sol
index c467f22..cca8026 100644
--- a/getAccountCollateralValue.sol
+++ b/getAccountCollateralValue.org.sol
@@ -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;

Support

FAQs

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