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

Gas optimisation and informal findings

[G-01] For the iteration of loop, low level unchecked can be used

For loops in contract the i = 0 assignment can be avoided and also i++ can be done in the unchecked block to avoid extra calculation.

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L118-L121

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L353-L357

Recommendation

Use the unchecked syntax as below. Also define a variable for length before iterating and fetching it from global storage every time.

1) uint tokensLength = s_collateralTokens.length;
for (uint256 i; i < tokensLength;) {
address token = s_collateralTokens[i];
uint256 amount = s_collateralDeposited[user][token];
totalCollateralValueInUsd += getUsdValue(token, amount);
unchecked {
++i;
}
}
2) uint tokenAddLength = tokenAddresses.length;
for (uint256 i; i < tokenAddLength;) {
s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
s_collateralTokens.push(tokenAddresses[i]);
unchecked {
++i;
}
}

Gas Savings

Mentioned below is the gas saving report.

Before

src/DSCEngine.sol:DSCEngine contract
Deployment Cost Deployment Size
1004332 5445
Function Name min avg median max # calls
burnDsc 398 12101 2675 33232 3
depositCollateral 435 36856 34512 52032 55
depositCollateralAndMintDsc 67909 128763 154933 154933 23
getAccountCollateralValue 42356 42356 42356 42356 1
getHealthFactor 9640 9640 9640 9640 6
liquidate 12786 67874 74400 96860 6
mintDsc 310 59669 66945 117545 32
redeemCollateral 413 11233 7830 43436 7
redeemCollateralForDsc 33402 40761 40761 48120 2

After

src/DSCEngine.sol:DSCEngine contract
Deployment Cost Deployment Size
998206 5367
Function Name min avg median max # calls
burnDsc 398 12019 2675 32985 3
depositCollateral 435 37590 34512 52032 33
depositCollateralAndMintDsc 67785 128484 154615 154615 23
getAccountCollateralValue 42038 42038 42038 42038 1
getHealthFactor 9322 9322 9322 9322 6
liquidate 12468 67276 73644 96612 6
mintDsc 310 57980 66627 117227 17
redeemCollateral 413 12544 7830 43181 5
redeemCollateralForDsc 33155 40386 40386 47618 2

[I-01] Index on amount in event

There is an index on amount field in the event.

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L87

Recommendation

The idex on amount field can be removed.

event CollateralDeposited(address indexed user, address indexed token, uint256 amount);

[I-02] Sender health check in the liquidate

There is a _revertIfHealthFactorIsBroken() check on the sender. If the sender itself is in liquidation state then the transaction will revert.

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L261

Recommendation

Please verify if this in the intended behavior. It doen't look like it is.

Support

FAQs

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