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

Using `unchecked` in `for` loops can save plenty of gas

Summary

In the Lender.sol contract,unchecked can be used to reduce a significant amount of gas by adding the increment of counter i in a for loop under an unchecked section.

Vulnerability Details

In cases when we know that a certain number cannot go below or beyond a certain limit, implementing unchecked is good to reduce gas usage. For instance, you can find the gas usage by my deployment on sepolia network, the as-is deployment consumed about 3,399,220 gas, whereas, when I implemented the unchecked method for a single function, startAuction() function. The gas dropped to 3,396,784 which is a difference of 2436 gas.

Original Contract

Contract with just a single changed instance of the optimization

There are a total of 6 functions using for loops, namely: borrow(), repay(), giveLoan(), startAuction(), seizeLoan(), and refinance(). Implementing this change for each function will mean saving tx. gas of about:

6 * 2436 = 14616 gas

Impact

Considerable save on gas.

Tools Used

  • Manual audit

  • Foundry

Recommendations

You can find my implementation on the testnet too. Implementing this simple change as shown below can help serve the impact:

function startAuction(uint256[] calldata loanIds) public {
for (uint256 i = 0; i < loanIds.length; ) {
uint256 loanId = loanIds[i];
// get the loan info
Loan memory loan = loans[loanId];
// validate the loan
if (msg.sender != loan.lender) revert Unauthorized();
if (loan.auctionStartTimestamp != type(uint256).max)
revert AuctionStarted();
// set the auction start timestamp
loans[loanId].auctionStartTimestamp = block.timestamp;
emit AuctionStart(
loan.borrower,
loan.lender,
loanId,
loan.debt,
loan.collateral,
block.timestamp,
loan.auctionLength
);
unchecked {
++i;
}
}
}

Support

FAQs

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