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

0 stars 1 forks source link

Gas Optimizations #6

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Use Custom Errors instead of Revert Strings to save Gas

Custom errors from Solidity 0.8.4 are cheaper than revert strings (cheaper deployment cost and runtime cost when the revert condition is met)

Source Custom Errors in Solidity:

Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.

Custom errors are defined using the error statement, which can be used inside and outside of contracts (including interfaces and libraries).

If it's not possible to use error codes due to the pragma used, it is recommended to reduce the strings to less than 32 bytes.

All contracts in scope are affected.

++i costs less gas compared to i++ or i += 1

++i costs less gas compared to i++ or i += 1 for unsigned integer, as pre-increment is cheaper (about 5 gas per iteration). This statement is true even with the optimizer enabled.

i++ increments i and returns the initial value of i. Which means:

uint i = 1;
i++; // == 1 but i == 2

But ++i returns the actual incremented value:

uint i = 1;
++i; // == 2 and i == 2 too, so no need for a temporary variable

In the first case, the compiler has to create a temporary variable (when used) for returning 1 instead of 2 I suggest using ++i instead of i++ to increment the value of an uint variable. Same thing for --i and i--

It is also recommended to not initialize the counter variable and surround the increment with an unchecked region.

Affected source code:

maximebrugel commented 2 years ago

Use Custom Errors instead of Revert Strings to save Gas (Disputed)

Already surfaced in previous audit and mentioned in README.md

Yashiru commented 2 years ago

++i costs less gas compared to i++ or i += 1 (Duplicated)

Duplicated of #2 at For loop optimizaion