code-423n4 / 2021-12-defiprotocol-findings

0 stars 0 forks source link

Loops can be implemented more efficiently #140

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

0x0x0x

Vulnerability details

Proof of Concept

Example:


for (uint i = 0; i < arr.length; i++) {

//Operations not effecting the length of the array.

}

Loading length of array costs gas. Therefore, the length should be cached, if the length of the array doesn't change inside the loop. Furthermore, there is no need to assign the initial value 0. This costs extra gas.

Recommended implementation:


uint length = arr.length;

for (uint i; i < length; i++) {

//Operations not effecting the length of the array.

}

By doing so the length is only loaded once rather than loading it as many times as iterations (Therefore, less gas is spent).

Occurences


./Auction.sol:88:        for (uint256 i = 0; i < inputTokens.length; i++) {
./Auction.sol:92:        for (uint256 i = 0; i < outputTokens.length; i++) {
./Auction.sol:105:        for (uint256 i = 0; i < pendingWeights.length; i++) {
./Auction.sol:152:        for (uint256 i = 0; i < bountyIds.length; i++) {
./Basket.sol:75:        for (uint i = 0; i < length; i++) {
./Basket.sol:79:            for (uint256 x = 0; x < tokenList.length; x++) {
./Basket.sol:275:        for (uint256 i = 0; i < weights.length; i++) {
./Basket.sol:282:        for (uint256 i = 0; i < weights.length; i++) {
./Basket.sol:290:        for (uint256 i = 0; i < weights.length; i++) {
./Factory.sol:109:        for (uint256 i = 0; i < bProposal.weights.length; i++) {