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

5 stars 0 forks source link

Gas Optimizations #262

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

1. Save gas with short-circuit optimization

When evaluating boolean expressions (logical AND and OR) you can stop as soon as you find the first condition which satisfies or negates the expression.

This can be used to optimize gas by reordering conditions in expressions. For example, this expression has 2 conditions

block.timestamp > positionExpirations[longPositionId] || isExercised

First condition reading from storage obviously cost more gas than second condition which simply a boolean variable in stack. We can swap their orders to optimize gas like

isExercised || block.timestamp > positionExpirations[longPositionId]

Affected Codes

https://github.com/code-423n4/2022-06-putty/blob/3b6b844bc39e897bd0bbb69897f2deff12dc3893/contracts/src/PuttyV2.sol#L481

https://github.com/code-423n4/2022-06-putty/blob/3b6b844bc39e897bd0bbb69897f2deff12dc3893/contracts/src/PuttyV2.sol#L327

https://github.com/code-423n4/2022-06-putty/blob/3b6b844bc39e897bd0bbb69897f2deff12dc3893/contracts/src/PuttyV2.sol#L351

https://github.com/code-423n4/2022-06-putty/blob/3b6b844bc39e897bd0bbb69897f2deff12dc3893/contracts/src/PuttyV2.sol#L427