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

4 stars 0 forks source link

Gas Optimizations #324

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

1 Use unchecked Math for calculations which will never overflow or underflow

There are many calculations which will never over/under flow because of verifications done prior to those calculations. Those can be put inside unchecked block to save gas.

for eg.

2 Read data from memory instead of storage when possible to save gas

Reading from storage uses SLOAD opcode which is more expensive than MLOAD which is used for memory read.

3. Use solidity custom errors to save gas

solidity 0.8.4 introduces custom errors which are cheaper than using revert strings in terms of gas. This can be used to save gas.

for eg.


  // Before
  require(condition, "Revert strings");

  // After
  error CustomError();
  if (!condition) {
    revert CustomError();
  }

more details can be found here

4. Constant expressions are expressions not constants

Constant expressions are not really constants but expressions, hence need to be evaluated every time they are used. Using actual constants can save gas.

5. canExecMatchOneToMany function can be optimized to save more gas

In InfinityOrderBookComplication.sol#L68

a. move this block to the end of the loop since first iteration will always evaluate to false || false

b. itemsIntersect does not needs to be checked in return statement since it is already checked inside the loop body (because of [a])

c. in InfinityOrderBookComplication.sol#L101-L103, isOrdersTimeValid can be ignored since it will always be true (checked inside the loop, because of [a])

d. return false immediately if _isTimeValid is false

e. return false immediately after the loop if numItems == makerOrder.constraints[0] is false

6. Long revert strings (> 32bytes) will cost extra gas

For eg. In InfinityExchange.sol#L395

nneverlander commented 2 years ago

Thanks