code-423n4 / 2022-02-nested-findings

0 stars 0 forks source link

Gas Optimizations #43

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

[G1] Cache shareholders array.

[G1 - Details]:

Caching arrays is a powerful way of lowering the gas fees. Since in a for loop accessing memory array’s indexes would consume more gas than accessing the same array’s cached indexes as the length of the array becomes larger and larger, it is crucial to do the caching wherever possible.

[G1 - References]:

FeeSplitter.sol line 320 # (_addShareholder function)

[G1 - Mitigation]:

Cache the array in a similar way:

function _addShareholder(address _account, uint96 _weight) private {
    require(_weight != 0, "FS: ZERO_WEIGHT");
    require(_account != address(0), "FS: INVALID_ADDRESS");

    Shareholder[] memory shareholdersCache = shareholders;
    for (uint256 i = 0; i < shareholders.length; i++) {
        require(shareholdersCache[i].account != _account, "FS: ALREADY_SHAREHOLDER");
    }

    shareholders.push(Shareholder(_account, _weight));
    totalWeights += _weight;
    emit ShareholdersAdded(_account, _weight);
}
adrien-supizet commented 2 years ago

Confirmed

maximebrugel commented 2 years ago

The array wont be very large

harleythedogC4 commented 2 years ago

My personal judgments:

  1. "Cache shareholders array". Valid and small-optimization.
harleythedogC4 commented 2 years ago

Now, here is the methodology I used for calculating a score for each gas report. I first assigned each submission to be either small-optimization (1 point), medium-optimization (5 points) or large-optimization (10 points), depending on how useful the optimization is. The score of a gas report is the sum of these points, divided by the maximum number of points achieved by a gas report. This maximum number was 10 points, achieved by #67.

The number of points achieved by this report is 1 points. Thus the final score of this gas report is (1/10)*100 = 10.