15,000 USDC
View results
Submission Details
Severity: gas

Event Optimization for the depositCollateral and _redeemCollateral Function

Summary

Analyze the depositCollateral and _redeemCollateral functions within the smart contract and recommend reducing gas consumption while maintaining the contract's intended functionality.

Vulnerability Details

The original implementation of the depositCollateral and _redeemCollateral function emits the event CollateralDeposited before ensuring the success of the token transfer. This approach may lead to unnecessary event emissions if the token transfer fails, increasing gas costs.

Impact

The inefficient event emission can lead to higher transaction costs.

Tools Used

The analysis for this gas optimization report was conducted manually by inspecting the smart contract code. No automated tools were utilized for this analysis.

Recommendations

Event Emission After Successful Token Transfer: Rearrange the code to emit the CollateralDeposited and CollateralRedeemed event after ensuring the success of the token transfer and before updating the contract's state. This will avoid unnecessary event emissions and potential inconsistencies in the contract's state.

Optimized depositCollateral function -

function depositCollateral(address tokenCollateralAddress, uint256 amountCollateral)
public
moreThanZero(amountCollateral)
isAllowedToken(tokenCollateralAddress)
nonReentrant
{
s_collateralDeposited[msg.sender][tokenCollateralAddress] += amountCollateral;
bool success = IERC20(tokenCollateralAddress).transferFrom(msg.sender, address(this), amountCollateral);
if (!success) {
revert DSCEngine__TransferFailed();
}
emit CollateralDeposited(msg.sender, tokenCollateralAddress, amountCollateral);
}

Optimized _redeemCollateral function -

function _redeemCollateral(address from, address to, address tokenCollateralAddress, uint256 amountCollateral)
private
{
s_collateralDeposited[from][tokenCollateralAddress] -= amountCollateral;
bool success = IERC20(tokenCollateralAddress).transfer(to, amountCollateral);
if (!success) {
revert DSCEngine__TransferFailed();
}
emit CollateralRedeemed(from, to, tokenCollateralAddress, amountCollateral);
}

Support

FAQs

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