Beginner FriendlySolidity
100 EXP
View results
Submission Details
Severity: medium
Invalid

gas optimization issue in the onlyBeneficiaryWithIsInherited modifier

Summary

The onlyBeneficiaryWithIsInherited modifier inefficiently reads the beneficiaries.length from storage in each loop iteration, resulting in unnecessary gas consumption

Vulnerability Details

In the current implementation, beneficiaries.length is read from storage in every iteration of the while loop:

modifier onlyBeneficiaryWithIsInherited() {
uint256 i = 0;
while (i < beneficiaries.length + 1) {
if (msg.sender == beneficiaries[i] && isInherited) {
break;
}
i++;
}
_;
}

Reading from storage costs 100 gas per read. Since this length check happens in every loop iteration, the gas cost increases linearly with the number of beneficiaries that need to be checked before finding a match.

Impact

  • Increased gas costs for functions using this modifier

  • The gas cost grows linearly with the position of the caller in the beneficiaries array

  • Unnecessary storage reads that could be optimized

Before any improvements:

[PASS] test_buyOutEstateNFTFailNotBeneficiary() (gas: 318646)
[PASS] test_buyOutEstateNFTFailNotInherited() (gas: 294218)
[PASS] test_buyOutEstateNFTSuccess() (gas: 477637)

After loop is optimised, gas cost is smaller in every test scenario:

[PASS] test_buyOutEstateNFTFailNotBeneficiary() (gas: 318333)
[PASS] test_buyOutEstateNFTFailNotInherited() (gas: 293905)
[PASS] test_buyOutEstateNFTSuccess() (gas: 477434)

Tools Used

Foundry test and manual code review

Recommendations

Cache the array length in memory at the beginning of the modifier to avoid repeated storage reads:

modifier onlyBeneficiaryWithIsInherited() {
uint256 i = 0;
uint256 length = beneficiaries.length;
while (i < length + 1) {
if (msg.sender == beneficiaries[i] && isInherited) {
break;
}
i++;
}
_;
}
Updates

Lead Judging Commences

0xtimefliez Lead Judge 3 months ago
Submission Judgement Published
Invalidated
Reason: Non-acceptable severity

Support

FAQs

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