code-423n4 / 2022-06-putty-findings

5 stars 0 forks source link

Gas Optimizations #288

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

1. STATE VARIABLES SHOULD BE CACHED IN STACK VARIABLES RATHER THAN RE-READING THEM FROM STORAGE

The instances below point to the second access of a state variable within a function. Caching will replace each Gwarmaccess (100 gas) with a much cheaper stack read.

PuttyV2.sol::fillOrder():

Cache weth in following lines:

PuttyV2.sol::exercise():

Cache weth in following lines:

PuttyV2.sol::withdraw():

Cache fee in following lines:

2. <ARRAY>.LENGTH SHOULD NOT BE LOOKED UP IN EVERY LOOP OF A FOR-LOOP

Even memory arrays incur the overhead of bit tests and bit shifts to calculate the array length. Storage array length checks incur an extra Gwarmaccess (100 gas) PER-LOOP.

Cache <array>.length in following lines:

3. use ++i instead of i++

4. IT COSTS MORE GAS TO INITIALIZE VARIABLES TO ZERO THAN TO LET THE DEFAULT OF ZERO BE APPLIED

no need to assign 0 to unsigned variables:

5. EXPRESSIONS FOR CONSTANT VALUES SUCH AS A CALL TO KECCAK256(), SHOULD USE IMMUTABLE RATHER THAN CONSTANT

6. USE CUSTOM ERRORS RATHER THAN REVERT()/REQUIRE() STRINGS TO SAVE DEPLOYMENT GAS

https://blog.soliditylang.org/2021/04/21/custom-errors/