sujithsomraaj / lifi-swap-facet-v3-audit

1 Day Review - 5/28
0 stars 0 forks source link

Cache variables in `_executeSwaps` to avoid expensive initialization #8

Open sujithsomraaj opened 6 months ago

sujithsomraaj commented 6 months ago

Context: GenericSwapFacetV3.sol#L311

Description: The function _executeSwaps is used to perform multi-hop swapping by looping through the _swapData passed in by the user. Variables in the process are initialized in each loop, leading to expensive initialization. In solidity, the initialization of a variable from its default value is a gas-expensive operation.

Hence, caching those variables outside the loop can result in handsome gas savings that increase linearly with the length of the _swapData array.

Recommendation: Cache and re-use variables outside the loop to save gas fees. Similar approach can also be made in the _depositMultipleERC20Tokens to save additional gas.

function _executeSwaps(
  LibSwap.SwapData[] calldata _swapData,
   bytes32 _transactionId,
   address _receiver
) private {
   // go through all swaps
   uint256 numOfSwaps = _swapData.length;
   ERC20 sendingAsset;
   LibSwap.SwapData calldata currentSwap;
   bool success;
   bytes memory returnData;
   uint256 currentAllowance;
   ...
   ...
}

LI.FI:

Researcher:

0xDEnYO commented 6 months ago

nice one...I wasnt aware of this approach yet. Thanks for pointing it out. Added.