YOLOrekt / community-bug-bounty

V1 contracts public bounty project
3 stars 1 forks source link

Loop Gas Optimization #3

Open Jayfromthe13th opened 2 years ago

Jayfromthe13th commented 2 years ago

Impact

Severity: Gas-Optimization ---ARRAY.LENGTH SHOULD NOT BE LOOKED UP IN EVERY LOOP OF A FOR-LOOP

---IT COSTS MORE GAS TO INITIALIZE VARIABLES TO ZERO

---PREFIX INCREMENTS INSTEAD OF POSTFIX INCREMENTS

Vulnerability There are nine lines of code that can utilize these particular gas optimization fixes.

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/core/NFTTracker.sol#L118

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/accessory/WhitelistSFTClaims.sol#L83)

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/game/GameInstance.sol#L364

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/tokens/extensions/ERC1155DynamicURI.sol#L33

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/tokens/extensions/ERC1155SemiFungible.sol#L127

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/utils/LogBinary.sol#L29

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/utils/LogBinary.sol#L71

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/utils/SupportsInterfaceValidator.sol#L39

https://github.com/YOLOrekt/community-bug-bounty/blob/bounty-head/contracts/utils/SupportsInterfaceValidator.sol#L15

Recommendation ---.LENGTH: Caching the length changes each of these to a DUP (3 gas), and gets rid of the extra DUP needed to store the stack offset.In particular, in for loops, when using the length of a storage array as the condition being checked after each loop, caching the array length in memory can yield significant gas savings if the array length is high.

---Initialization: Let the default zero be applied instead of initializing default variable. -uint256 value; is cheaper than uint256 value = 0;. -for (uint i; i counter; ++i) is cheaper than for (uint i=0; i <counter; i++)

---++I Cost less gas than I++, especially when it's used in For-Loops (--I/I-- TOO) -Saves 6 gas PER LOOP

aahna-ashina commented 2 years ago

@Jayfromthe13th What is your technique for calculating gas usage?