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

Initialize variables outside the loop

Summary

For variables with values changing multiple times in a for loop, it is significantly cheaper to initialize these variables outside of the loop. This is because, an SSTORE (storage write) operation that goes from 0 to non-zero is 22k gas units, while non-zero to non-zero is only 5k units. Initializing these variables inside the loop would cost 22k gas on every iteration, while initializing the variables outside the loop would only cost 22k gas on the first iteration, and 5k gas on subsequent iterations.

Vulnerability Details

See summary

Impact

There are 12 instances of this.

Tools Used

Foundry

Recommendations

Consider initializing the variables outside the for loop. As an example, the borrow function could be rewritten like:

function borrow(Borrow[] calldata borrows) public {
bytes32 poolId; // <-- Function initialized outside loop
uint256 debt; // <-- Function initialized outside loop
uint256 collateral; // <-- Function initialized outside loop
for (uint256 i; i < borrows.length; ++i) {
poolId = borrows[i].poolId;
debt = borrows[i].debt;
collateral = borrows[i].collateral;
// get the pool info
Pool memory pool = pools[poolId];
// make sure the pool exists
if (pool.lender == address(0)) revert PoolConfig();
// validate the loan
if (debt < pool.minLoanSize) revert LoanTooSmall();
if (debt > pool.poolBalance) revert LoanTooLarge();
if (collateral == 0) revert ZeroCollateral();
...
}

Support

FAQs

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