code-423n4 / 2022-03-lifinance-findings

6 stars 4 forks source link

Gas Optimizations #99

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Functions Visibility Can Be Declared External

Context: AnyswapFacet.sol#L35-L66, AnyswapFacet.sol#L74-L123, CBridgeFacet.sol#L57-L84, CBridgeFacet.sol#L92-L134, GenericSwapFacet.sol#L22-L43, HopFacet.sol#L61-L87, HopFacet.sol#L95-L126, NXTPFacet.sol#L46-L76, NXTPFacet.sol#L85-L115, WithdrawFacet.sol#L20-L38

Description: Several functions across multiple contracts have a public visibility and can be marked with external visibility to save gas.

Recommendation: Change the functions visibility to external to save gas.

Catching The Array Length Prior To Loop

Context: DexManagerFacet.sol#L30-L40, DexManagerFacet.sol#L44-L58, DexManagerFacet.sol#L62-L77, Swapper.sol#L12-L23, LibDiamond.sol#L62-L81, LibDiamond.sol#L83-L99, LibDiamond.sol#L101-L118, LibDiamond.sol#L120-L130

Description: One can save gas by caching the array length (in stack) and using that set variable in the loop.

Recommendation: Simply do something like so before the for loop: uint length = variable.length. Then add length in place of variable.length in the for loop.

Function Ordering via Method ID

Description: Contracts most called functions could simply save gas by function ordering via Method ID. Calling a function at runtime will be cheaper if the function is positioned earlier in the order (has a relatively lower Method ID) because 22 gas are added to the cost of a function for every position that came before it. The caller can save on gas if you prioritize most called functions. One could use This tool to help find alternative function names with lower Method IDs while keeping the original name intact.

Recommendation: Find a lower method ID name for the most called functions for example mostCalled() vs. mostCalled_41q() is cheaper by 44 gas.

H3xept commented 2 years ago

Re Functions Visibility Can Be Declared External

Fixed in previous commit.

H3xept commented 2 years ago

Re Catching The Array Length Prior To Loop:

Fixed in previous commit.

H3xept commented 2 years ago

Re Function Ordering via Method ID

We internally decided to avoid this as the gas savings do not justify the resulting less-readable code

H3xept commented 2 years ago

Re Catching The Array Length Prior To Loop

Duplicate of #44

H3xept commented 2 years ago

Re Functions Visibility Can Be Declared External

Duplicate of #197