code-423n4 / 2022-07-swivel-findings

0 stars 1 forks source link

Gas Optimizations #164

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

GAS

1. Improve logic

Move the following line from VaultTracker.sol#L155-L158:

    Vault memory from = vaults[f];
-   Vault memory to = vaults[t];

    if (a > from.notional) { revert Exception(31, a, from.notional, address(0), address(0)); }
+   Vault memory to = vaults[t];

2. Avoid unused returns

Having a method that always returns the same value is not correct in terms of consumption, if you want to modify a value, and the method will perform a revert in case of failure, it is not necessary to return a true, since it will never be false. It is less expensive not to return anything, and it also eliminates the need to double-check the returned value by the caller.

Affected source code:

3. ++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--

Affected source code:

4. delete optimization

Use delete instead of set to default value (false or 0).

5 gas could be saved per entry in the following affected lines:

5. Reduce math operations

Use scientific notation (e.g. 10e17) rather than exponentiation (e.g. 10**18)

Change 2**256 - 1 to type(uint256).max: