From 8cbbde6c0475f7c3bcfeb1568c4bab554fa1e400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Tue, 25 Jun 2024 10:19:15 +0700 Subject: [PATCH 01/11] added V4 --- src/Facets/GenericSwapFacetV4.sol | 543 ++++ test/solidity/Facets/GenericSwapFacetV4.t.sol | 2222 +++++++++++++++++ 2 files changed, 2765 insertions(+) create mode 100644 src/Facets/GenericSwapFacetV4.sol create mode 100644 test/solidity/Facets/GenericSwapFacetV4.t.sol diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Facets/GenericSwapFacetV4.sol new file mode 100644 index 000000000..7bfa130e8 --- /dev/null +++ b/src/Facets/GenericSwapFacetV4.sol @@ -0,0 +1,543 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.17; + +import { ILiFi } from "../Interfaces/ILiFi.sol"; +import { LibUtil } from "../Libraries/LibUtil.sol"; +import { LibSwap } from "../Libraries/LibSwap.sol"; +import { LibAllowList } from "../Libraries/LibAllowList.sol"; +import { LibAsset } from "../Libraries/LibAsset.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol"; +import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; +import { console2 } from "forge-std/console2.sol"; + +/// @title GenericSwapFacetV4 +/// @author LI.FI (https://li.fi) +/// @notice Provides gas-optimized functionality for fee collection and for swapping through any APPROVED DEX +/// @dev Can only execute calldata for APPROVED function selectors +/// @custom:version 1.0.0 +contract GenericSwapFacetV4 is ILiFi { + using SafeTransferLib for ERC20; + + /// External Methods /// + + // SINGLE SWAPS + + /// @notice Performs a single swap from an ERC20 token to another ERC20 token + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToERC20( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external { + _depositAndSwapERC20Single(_swapData, _receiver); + + address receivingAssetId = _swapData.receivingAssetId; + address sendingAssetId = _swapData.sendingAssetId; + + // get contract's balance (which will be sent in full to user) + uint256 amountReceived = ERC20(receivingAssetId).balanceOf( + address(this) + ); + + // ensure that minAmountOut was received + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + // transfer funds to receiver + ERC20(receivingAssetId).safeTransfer(_receiver, amountReceived); + + // emit events (both required for tracking) + uint256 fromAmount = _swapData.fromAmount; + emit LibSwap.AssetSwapped( + _transactionId, + _swapData.callTo, + sendingAssetId, + receivingAssetId, + fromAmount, + amountReceived, + block.timestamp + ); + + emit ILiFi.LiFiGenericSwapCompleted( + _transactionId, + _integrator, + _referrer, + _receiver, + sendingAssetId, + receivingAssetId, + fromAmount, + amountReceived + ); + } + + /// @notice Performs a single swap from an ERC20 token to the network's native token + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToNative( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external { + _depositAndSwapERC20Single(_swapData, _receiver); + + // get contract's balance (which will be sent in full to user) + uint256 amountReceived = address(this).balance; + + // ensure that minAmountOut was received + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + // transfer funds to receiver + // solhint-disable-next-line avoid-low-level-calls + (bool success, ) = _receiver.call{ value: amountReceived }(""); + if (!success) revert NativeAssetTransferFailed(); + + // emit events (both required for tracking) + address sendingAssetId = _swapData.sendingAssetId; + uint256 fromAmount = _swapData.fromAmount; + emit LibSwap.AssetSwapped( + _transactionId, + _swapData.callTo, + sendingAssetId, + address(0), + fromAmount, + amountReceived, + block.timestamp + ); + + emit ILiFi.LiFiGenericSwapCompleted( + _transactionId, + _integrator, + _referrer, + _receiver, + sendingAssetId, + address(0), + fromAmount, + amountReceived + ); + } + + /// @notice Performs a single swap from the network's native token to ERC20 token + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3NativeToERC20( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external payable { + address callTo = _swapData.callTo; + // ensure that contract (callTo) and function selector are whitelisted + if ( + !(LibAllowList.contractIsAllowed(callTo) && + LibAllowList.selectorIsAllowed(bytes4(_swapData.callData[:4]))) + ) revert ContractCallNotAllowed(); + + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = callTo.call{ value: msg.value }( + _swapData.callData + ); + if (!success) { + LibUtil.revertWith(res); + } + + _returnPositiveSlippageNative(_receiver); + + // get contract's balance (which will be sent in full to user) + address receivingAssetId = _swapData.receivingAssetId; + uint256 amountReceived = ERC20(receivingAssetId).balanceOf( + address(this) + ); + + // transfer funds to receiver + ERC20(receivingAssetId).safeTransfer(_receiver, amountReceived); + + // emit events (both required for tracking) + uint256 fromAmount = _swapData.fromAmount; + emit LibSwap.AssetSwapped( + _transactionId, + callTo, + address(0), + receivingAssetId, + fromAmount, + amountReceived, + block.timestamp + ); + + emit ILiFi.LiFiGenericSwapCompleted( + _transactionId, + _integrator, + _referrer, + _receiver, + address(0), + receivingAssetId, + fromAmount, + amountReceived + ); + } + + // MULTIPLE SWAPS + + /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3ERC20ToNative( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external { + _depositMultipleERC20Tokens(_swapData); + _executeSwaps(_swapData, _transactionId, _receiver); + _transferNativeTokensAndEmitEvent( + _transactionId, + _integrator, + _referrer, + _receiver, + _minAmountOut, + _swapData + ); + } + + /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with ERC20 + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3ERC20ToERC20( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external { + _depositMultipleERC20Tokens(_swapData); + _executeSwaps(_swapData, _transactionId, _receiver); + _transferERC20TokensAndEmitEvent( + _transactionId, + _integrator, + _referrer, + _receiver, + _minAmountOut, + _swapData + ); + } + + /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 + /// @param _transactionId the transaction id associated with the operation + /// @param _integrator the name of the integrator + /// @param _referrer the address of the referrer + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3NativeToERC20( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external payable { + _executeSwaps(_swapData, _transactionId, _receiver); + _transferERC20TokensAndEmitEvent( + _transactionId, + _integrator, + _referrer, + _receiver, + _minAmountOut, + _swapData + ); + } + + /// Private helper methods /// + function _depositMultipleERC20Tokens( + LibSwap.SwapData[] calldata _swapData + ) private { + // initialize variables before loop to save gas + uint256 numOfSwaps = _swapData.length; + LibSwap.SwapData calldata currentSwap; + + // go through all swaps and deposit tokens, where required + for (uint256 i = 0; i < numOfSwaps; ) { + currentSwap = _swapData[i]; + if (currentSwap.requiresDeposit) { + // we will not check msg.value as tx will fail anyway if not enough value available + // thus we only deposit ERC20 tokens here + ERC20(currentSwap.sendingAssetId).safeTransferFrom( + msg.sender, + address(this), + currentSwap.fromAmount + ); + } + unchecked { + ++i; + } + } + } + + function _depositAndSwapERC20Single( + LibSwap.SwapData calldata _swapData, + address _receiver + ) private { + ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); + uint256 fromAmount = _swapData.fromAmount; + // deposit funds + sendingAsset.safeTransferFrom(msg.sender, address(this), fromAmount); + + // ensure that contract (callTo) and function selector are whitelisted + address callTo = _swapData.callTo; + address approveTo = _swapData.approveTo; + bytes calldata callData = _swapData.callData; + if ( + !(LibAllowList.contractIsAllowed(callTo) && + LibAllowList.selectorIsAllowed(bytes4(callData[:4]))) + ) revert ContractCallNotAllowed(); + + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = callTo.call(callData); + if (!success) { + LibUtil.revertWith(res); + } + + _returnPositiveSlippageERC20(sendingAsset, _receiver); + } + + // @dev: this function will not work with swapData that has multiple swaps with the same sendingAssetId + // as the _returnPositiveSlippage... functionality will refund all remaining tokens after the first swap + // We accept this fact since the use case is not common yet. As an alternative you can always use the + // "swapTokensGeneric" function of the original GenericSwapFacet + function _executeSwaps( + LibSwap.SwapData[] calldata _swapData, + bytes32 _transactionId, + address _receiver + ) private { + // initialize variables before loop to save gas + uint256 numOfSwaps = _swapData.length; + ERC20 sendingAsset; + address sendingAssetId; + address receivingAssetId; + LibSwap.SwapData calldata currentSwap; + bool success; + bytes memory returnData; + uint256 currentAllowance; + + // go through all swaps + for (uint256 i = 0; i < numOfSwaps; ) { + currentSwap = _swapData[i]; + sendingAssetId = currentSwap.sendingAssetId; + sendingAsset = ERC20(currentSwap.sendingAssetId); + receivingAssetId = currentSwap.receivingAssetId; + + // check if callTo address is whitelisted + if ( + !LibAllowList.contractIsAllowed(currentSwap.callTo) || + !LibAllowList.selectorIsAllowed( + bytes4(currentSwap.callData[:4]) + ) + ) { + revert ContractCallNotAllowed(); + } + + // if approveTo address is different to callTo, check if it's whitelisted, too + if ( + currentSwap.approveTo != currentSwap.callTo && + !LibAllowList.contractIsAllowed(currentSwap.approveTo) + ) { + revert ContractCallNotAllowed(); + } + + if (LibAsset.isNativeAsset(sendingAssetId)) { + // Native + // execute the swap + (success, returnData) = currentSwap.callTo.call{ + value: currentSwap.fromAmount + }(currentSwap.callData); + if (!success) { + LibUtil.revertWith(returnData); + } + + // return any potential leftover sendingAsset tokens + // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) + if (sendingAssetId != receivingAssetId) + _returnPositiveSlippageNative(_receiver); + } else { + // ERC20 + // check if the current allowance is sufficient + currentAllowance = sendingAsset.allowance( + address(this), + currentSwap.approveTo + ); + if (currentAllowance < currentSwap.fromAmount) { + sendingAsset.safeApprove(currentSwap.approveTo, 0); + sendingAsset.safeApprove( + currentSwap.approveTo, + type(uint256).max + ); + } + + // execute the swap + (success, returnData) = currentSwap.callTo.call( + currentSwap.callData + ); + if (!success) { + LibUtil.revertWith(returnData); + } + + // return any potential leftover sendingAsset tokens + // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) + if (sendingAssetId != receivingAssetId) + _returnPositiveSlippageERC20(sendingAsset, _receiver); + } + + // emit AssetSwapped event + // @dev: this event might in some cases emit inaccurate information. e.g. if a token is swapped and this contract already held a balance of the receivingAsset + // then the event will show swapOutputAmount + existingBalance as toAmount. We accept this potential inaccuracy in return for gas savings and may update this + // at a later stage when the described use case becomes more common + emit LibSwap.AssetSwapped( + _transactionId, + currentSwap.callTo, + sendingAssetId, + receivingAssetId, + currentSwap.fromAmount, + LibAsset.isNativeAsset(receivingAssetId) + ? address(this).balance + : ERC20(receivingAssetId).balanceOf(address(this)), + block.timestamp + ); + + unchecked { + ++i; + } + } + } + + function _transferERC20TokensAndEmitEvent( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) private { + // determine the end result of the swap + address finalAssetId = _swapData[_swapData.length - 1] + .receivingAssetId; + uint256 amountReceived = ERC20(finalAssetId).balanceOf(address(this)); + + // make sure minAmountOut was received + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + // transfer to receiver + ERC20(finalAssetId).safeTransfer(_receiver, amountReceived); + + // emit event + emit ILiFi.LiFiGenericSwapCompleted( + _transactionId, + _integrator, + _referrer, + _receiver, + _swapData[0].sendingAssetId, + finalAssetId, + _swapData[0].fromAmount, + amountReceived + ); + } + + function _transferNativeTokensAndEmitEvent( + bytes32 _transactionId, + string calldata _integrator, + string calldata _referrer, + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) private { + console2.log("in _transferNativeTokensAndEmitEvent"); + uint256 amountReceived = address(this).balance; + + // make sure minAmountOut was received + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + // transfer funds to receiver + // solhint-disable-next-line avoid-low-level-calls + (bool success, ) = _receiver.call{ value: amountReceived }(""); + if (!success) { + console2.log("HEYA"); + revert NativeAssetTransferFailed(); + } + + // emit event + emit ILiFi.LiFiGenericSwapCompleted( + _transactionId, + _integrator, + _referrer, + _receiver, + _swapData[0].sendingAssetId, + address(0), + _swapData[0].fromAmount, + amountReceived + ); + } + + // returns any unused 'sendingAsset' tokens (=> positive slippage) to the receiver address + function _returnPositiveSlippageERC20( + ERC20 sendingAsset, + address receiver + ) private { + // if a balance exists in sendingAsset, it must be positive slippage + if (address(sendingAsset) != address(0)) { + uint256 sendingAssetBalance = sendingAsset.balanceOf( + address(this) + ); + + if (sendingAssetBalance > 0) { + sendingAsset.safeTransfer(receiver, sendingAssetBalance); + } + } + } + + // returns any unused native tokens (=> positive slippage) to the receiver address + function _returnPositiveSlippageNative(address receiver) private { + // if a native balance exists in sendingAsset, it must be positive slippage + uint256 nativeBalance = address(this).balance; + + if (nativeBalance > 0) { + // solhint-disable-next-line avoid-low-level-calls + (bool success, ) = receiver.call{ value: nativeBalance }(""); + if (!success) revert NativeAssetTransferFailed(); + } + } +} diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol new file mode 100644 index 000000000..e7bb66baf --- /dev/null +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -0,0 +1,2222 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity 0.8.17; + +import { Test, DSTest } from "forge-std/Test.sol"; +import { console } from "../utils/Console.sol"; +import { DiamondTest, LiFiDiamond } from "../utils/DiamondTest.sol"; +import { Vm } from "forge-std/Vm.sol"; +import { GenericSwapFacet } from "lifi/Facets/GenericSwapFacet.sol"; +import { GenericSwapFacetV4 } from "lifi/Facets/GenericSwapFacetV4.sol"; +import { LibSwap } from "lifi/Libraries/LibSwap.sol"; +import { LibAllowList } from "lifi/Libraries/LibAllowList.sol"; +import { FeeCollector } from "lifi/Periphery/FeeCollector.sol"; +import { ERC20 } from "solmate/tokens/ERC20.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "lifi/Errors/GenericErrors.sol"; + +import { UniswapV2Router02 } from "../utils/Interfaces.sol"; +// import { MockUniswapDEX } from "../utils/MockUniswapDEX.sol"; +import { TestHelpers, MockUniswapDEX, NonETHReceiver } from "../utils/TestHelpers.sol"; +import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; + +// Stub GenericSwapFacet Contract +contract TestGenericSwapFacetV4 is GenericSwapFacetV4, GenericSwapFacet { + function addDex(address _dex) external { + LibAllowList.addAllowedContract(_dex); + } + + function removeDex(address _dex) external { + LibAllowList.removeAllowedContract(_dex); + } + + function setFunctionApprovalBySignature(bytes4 _signature) external { + LibAllowList.addAllowedSelector(_signature); + } +} + +contract TestGenericSwapFacet is GenericSwapFacet { + function addDex(address _dex) external { + LibAllowList.addAllowedContract(_dex); + } + + function removeDex(address _dex) external { + LibAllowList.removeAllowedContract(_dex); + } + + function setFunctionApprovalBySignature(bytes4 _signature) external { + LibAllowList.addAllowedSelector(_signature); + } +} + +contract GenericSwapFacetV4Test is DSTest, DiamondTest, TestHelpers { + using SafeTransferLib for ERC20; + + event LiFiGenericSwapCompleted( + bytes32 indexed transactionId, + string integrator, + string referrer, + address receiver, + address fromAssetId, + address toAssetId, + uint256 fromAmount, + uint256 toAmount + ); + + // These values are for Mainnet + address internal constant USDC_ADDRESS = + 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; + address internal constant USDT_ADDRESS = + 0xdAC17F958D2ee523a2206206994597C13D831ec7; + address internal constant WETH_ADDRESS = + 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; + address internal constant DAI_ADDRESS = + 0x6B175474E89094C44Da98b954EedeAC495271d0F; + address internal constant USDC_HOLDER = + 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; + address internal constant DAI_HOLDER = + 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; + address internal constant SOME_WALLET = + 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; + address internal constant UNISWAP_V2_ROUTER = + 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; + address internal constant FEE_COLLECTOR = + 0xbD6C7B0d2f68c2b7805d88388319cfB6EcB50eA9; + + // ----- + + LiFiDiamond internal diamond; + TestGenericSwapFacet internal genericSwapFacet; + TestGenericSwapFacetV4 internal genericSwapFacetV4; + ERC20 internal usdc; + ERC20 internal usdt; + ERC20 internal dai; + ERC20 internal weth; + UniswapV2Router02 internal uniswap; + FeeCollector internal feeCollector; + + function fork() internal { + string memory rpcUrl = vm.envString("ETH_NODE_URI_MAINNET"); + uint256 blockNumber = 19834820; + vm.createSelectFork(rpcUrl, blockNumber); + } + + function setUp() public { + fork(); + + diamond = createDiamond(); + genericSwapFacet = new TestGenericSwapFacet(); + genericSwapFacetV4 = new TestGenericSwapFacetV4(); + usdc = ERC20(USDC_ADDRESS); + usdt = ERC20(USDT_ADDRESS); + dai = ERC20(DAI_ADDRESS); + weth = ERC20(WETH_ADDRESS); + uniswap = UniswapV2Router02(UNISWAP_V2_ROUTER); + feeCollector = FeeCollector(FEE_COLLECTOR); + + // add genericSwapFacet (v1) to diamond (for gas usage comparison) + bytes4[] memory functionSelectors = new bytes4[](4); + functionSelectors[0] = genericSwapFacet.swapTokensGeneric.selector; + functionSelectors[1] = genericSwapFacet.addDex.selector; + functionSelectors[2] = genericSwapFacet.removeDex.selector; + functionSelectors[3] = genericSwapFacet + .setFunctionApprovalBySignature + .selector; + addFacet(diamond, address(genericSwapFacet), functionSelectors); + + // add genericSwapFacet (v3) to diamond + bytes4[] memory functionSelectorsV3 = new bytes4[](6); + functionSelectorsV3[0] = genericSwapFacetV4 + .swapTokensSingleV3ERC20ToERC20 + .selector; + functionSelectorsV3[1] = genericSwapFacetV4 + .swapTokensSingleV3ERC20ToNative + .selector; + functionSelectorsV3[2] = genericSwapFacetV4 + .swapTokensSingleV3NativeToERC20 + .selector; + functionSelectorsV3[3] = genericSwapFacetV4 + .swapTokensMultipleV3ERC20ToERC20 + .selector; + functionSelectorsV3[4] = genericSwapFacetV4 + .swapTokensMultipleV3ERC20ToNative + .selector; + functionSelectorsV3[5] = genericSwapFacetV4 + .swapTokensMultipleV3NativeToERC20 + .selector; + + addFacet(diamond, address(genericSwapFacetV4), functionSelectorsV3); + + genericSwapFacet = TestGenericSwapFacet(address(diamond)); + genericSwapFacetV4 = TestGenericSwapFacetV4(address(diamond)); + + // whitelist uniswap dex with function selectors + // v1 + genericSwapFacet.addDex(address(uniswap)); + genericSwapFacet.setFunctionApprovalBySignature( + uniswap.swapExactTokensForTokens.selector + ); + genericSwapFacet.setFunctionApprovalBySignature( + uniswap.swapTokensForExactETH.selector + ); + genericSwapFacet.setFunctionApprovalBySignature( + uniswap.swapExactTokensForETH.selector + ); + genericSwapFacet.setFunctionApprovalBySignature( + uniswap.swapExactETHForTokens.selector + ); + // v3 + genericSwapFacetV4.addDex(address(uniswap)); + genericSwapFacetV4.setFunctionApprovalBySignature( + uniswap.swapExactTokensForTokens.selector + ); + genericSwapFacetV4.setFunctionApprovalBySignature( + uniswap.swapTokensForExactETH.selector + ); + genericSwapFacetV4.setFunctionApprovalBySignature( + uniswap.swapExactTokensForETH.selector + ); + genericSwapFacetV4.setFunctionApprovalBySignature( + uniswap.swapExactETHForTokens.selector + ); + + // whitelist feeCollector with function selectors + // v1 + genericSwapFacet.addDex(FEE_COLLECTOR); + genericSwapFacet.setFunctionApprovalBySignature( + feeCollector.collectTokenFees.selector + ); + genericSwapFacet.setFunctionApprovalBySignature( + feeCollector.collectNativeFees.selector + ); + // v3 + genericSwapFacetV4.addDex(FEE_COLLECTOR); + genericSwapFacetV4.setFunctionApprovalBySignature( + feeCollector.collectTokenFees.selector + ); + genericSwapFacetV4.setFunctionApprovalBySignature( + feeCollector.collectNativeFees.selector + ); + + vm.label(address(genericSwapFacet), "LiFiDiamond"); + vm.label(WETH_ADDRESS, "WETH_TOKEN"); + vm.label(DAI_ADDRESS, "DAI_TOKEN"); + vm.label(USDC_ADDRESS, "USDC_TOKEN"); + vm.label(UNISWAP_V2_ROUTER, "UNISWAP_V2_ROUTER"); + } + + // SINGLE SWAP ERC20 >> ERC20 + function _produceSwapDataERC20ToERC20( + address facetAddress + ) + private + returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) + { + // Swap USDC to DAI + address[] memory path = new address[](2); + path[0] = USDC_ADDRESS; + path[1] = DAI_ADDRESS; + + uint256 amountIn = 100 * 10 ** usdc.decimals(); + + // Calculate minimum input amount + uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); + minAmountOut = amounts[0]; + + // prepare swapData + swapData = new LibSwap.SwapData[](1); + swapData[0] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + USDC_ADDRESS, + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + uniswap.swapExactTokensForTokens.selector, + amountIn, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + true + ); + + vm.startPrank(USDC_HOLDER); + usdc.approve(facetAddress, amountIn); + vm.stopPrank(); + } + + function test_CanSwapSingleERC20ToERC20_V1() public { + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); + + vm.startPrank(USDC_HOLDER); + // expected exact amountOut based on the liquidity available in the specified block for this test case + uint256 expAmountOut = 99491781613896927553; + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + DAI_ADDRESS, // toAssetId, + swapData[0].fromAmount, // fromAmount, + expAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V1", gasUsed); + + // bytes memory callData = abi.encodeWithSelector( + // genericSwapFacet.swapTokensGeneric.selector, + // "", + // "integrator", + // "referrer", + // payable(SOME_WALLET), + // minAmountOut, + // swapData + // ); + + // console.log("Calldata V1:"); + // console.logBytes(callData); + + // vm.stopPrank(); + } + + function test_CanSwapSingleERC20ToERC20_V2() public { + // get swapData for USDC > DAI swap + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); + + // pre-register max approval between diamond and dex to get realistic gas usage + vm.startPrank(address(genericSwapFacet)); + usdc.approve(swapData[0].approveTo, type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USDC_HOLDER); + + // expected exact amountOut based on the liquidity available in the specified block for this test case + uint256 expAmountOut = 99491781613896927553; + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + DAI_ADDRESS, // toAssetId, + swapData[0].fromAmount, // fromAmount, + expAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V2", gasUsed); + + // bytes memory callData = abi.encodeWithSelector( + // genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20.selector, + // "", + // "integrator", + // "referrer", + // payable(SOME_WALLET), + // minAmountOut, + // swapData[0] + // ); + + // console.log("Calldata V2:"); + // console.logBytes(callData); + vm.stopPrank(); + } + + function test_WillRevertIfSlippageIsTooHighSingleERC20ToERC20() public { + // get swapData for USDC > DAI swap + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); + vm.startPrank(USDC_HOLDER); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + DAI_ADDRESS, + minAmountOut - 1, + 0 + ); + + // update SwapData + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + vm.expectRevert( + abi.encodeWithSelector( + CumulativeSlippageTooHigh.selector, + minAmountOut, + minAmountOut - 1 + ) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsSingleERC20() + public + { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacetV4)); + + vm.startPrank(USDC_HOLDER); + + // update approveTo address in swapData + swapData[0].approveTo = SOME_WALLET; + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + } + + function test_CanSwapSingleERC20ToERC20WithNonZeroAllowance() public { + // get swapData for USDC > DAI swap + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); + + // expected exact amountOut based on the liquidity available in the specified block for this test case + uint256 expAmountOut = 99491781613896927553; + + // pre-register max approval between diamond and dex to get realistic gas usage + vm.startPrank(address(genericSwapFacet)); + usdc.approve(swapData[0].approveTo, 1); + vm.stopPrank(); + + vm.startPrank(USDC_HOLDER); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + DAI_ADDRESS, // toAssetId, + swapData[0].fromAmount, // fromAmount, + expAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + function test_CanSwapSingleERC20ToERC20WithZeroAllowance() public { + // get swapData for USDC > DAI swap + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); + + // expected exact amountOut based on the liquidity available in the specified block for this test case + uint256 expAmountOut = 99491781613896927553; + + // pre-register max approval between diamond and dex to get realistic gas usage + vm.startPrank(address(genericSwapFacet)); + usdc.approve(swapData[0].approveTo, 0); + vm.stopPrank(); + + vm.startPrank(USDC_HOLDER); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + DAI_ADDRESS, // toAssetId, + swapData[0].fromAmount, // fromAmount, + expAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + // SINGLE SWAP ERC20 >> Native + function _produceSwapDataERC20ToNative( + address facetAddress + ) + private + returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) + { + // Swap USDC to Native ETH + address[] memory path = new address[](2); + path[0] = USDC_ADDRESS; + path[1] = WETH_ADDRESS; + + minAmountOut = 2 ether; + + // Calculate minimum input amount + uint256[] memory amounts = uniswap.getAmountsIn(minAmountOut, path); + uint256 amountIn = amounts[0]; + + // prepare swapData + swapData = new LibSwap.SwapData[](1); + swapData[0] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + USDC_ADDRESS, + address(0), + amountIn, + abi.encodeWithSelector( + uniswap.swapTokensForExactETH.selector, + minAmountOut, + amountIn, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + true + ); + + vm.startPrank(USDC_HOLDER); + usdc.approve(facetAddress, amountIn); + vm.stopPrank(); + } + + function test_CanSwapSingleERC20ToNative_V1() public { + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); + + vm.startPrank(USDC_HOLDER); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + address(0), // toAssetId, + swapData[0].fromAmount, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + + vm.stopPrank(); + } + + function test_CanSwapSingleERC20ToNative_V2() public { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); + + // pre-register max approval between diamond and dex to get realistic gas usage + vm.startPrank(address(genericSwapFacet)); + usdc.approve(swapData[0].approveTo, type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USDC_HOLDER); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + address(0), // toAssetId, + swapData[0].fromAmount, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + + vm.stopPrank(); + } + + function test_WillRevertIfSlippageIsTooHighSingleERC20ToNative() public { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); + + vm.startPrank(USDC_HOLDER); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + minAmountOut - 1, + 0 + ); + + // update SwapData + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + vm.expectRevert( + abi.encodeWithSelector( + CumulativeSlippageTooHigh.selector, + minAmountOut, + minAmountOut - 1 + ) + ); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + function test_ERC20SwapWillRevertIfSwapFails() public { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); + + vm.startPrank(USDC_HOLDER); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + 0, + 0 + ); + + // update SwapData + bytes memory revertReason = abi.encodePacked("Just because"); + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + swapData[0].callData = abi.encodeWithSelector( + mockDEX.mockSwapWillRevertWithReason.selector, + revertReason + ); + + vm.expectRevert(revertReason); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + function test_WillRevertIfDEXIsNotWhitelistedSingleERC20() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacetV4)); + + vm.startPrank(USDC_HOLDER); + + // remove dex from whitelist + genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + } + + function test_SingleERC20ToNativeWillRevertIfNativeAssetTransferFails() + public + { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); + + vm.startPrank(USDC_HOLDER); + + // deploy a contract that cannot receive ETH + NonETHReceiver nonETHReceiver = new NonETHReceiver(); + + vm.expectRevert(NativeAssetTransferFailed.selector); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(address(nonETHReceiver)), // use nonETHReceiver for testing + minAmountOut, + swapData[0] + ); + + vm.stopPrank(); + } + + // SINGLE SWAP NATIVE >> ERC20 + function _produceSwapDataNativeToERC20() + private + view + returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) + { + // Swap native to USDC + address[] memory path = new address[](2); + path[0] = WETH_ADDRESS; + path[1] = USDC_ADDRESS; + + uint256 amountIn = 2 ether; + + // Calculate minimum input amount + uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); + minAmountOut = amounts[1]; + + // prepare swapData + swapData = new LibSwap.SwapData[](1); + swapData[0] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + address(0), + USDC_ADDRESS, + amountIn, + abi.encodeWithSelector( + uniswap.swapExactETHForTokens.selector, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + true + ); + } + + function test_CanSwapSingleNativeToERC20_V1() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataNativeToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + address(0), // fromAssetId, + USDC_ADDRESS, // toAssetId, + swapData[0].fromAmount, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric{ value: swapData[0].fromAmount }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: ", gasUsed); + } + + function test_CanSwapSingleNativeToERC20_V2() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataNativeToERC20(); + + uint256 gasLeftBef = gasleft(); + + genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ + value: swapData[0].fromAmount + }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + } + + function test_WillRevertIfDEXIsNotWhitelistedSingleNative() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataNativeToERC20(); + + // remove dex from whitelist + genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ + value: swapData[0].fromAmount + }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + } + + function test_NativeSwapWillRevertIfSwapFails() public { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataNativeToERC20(); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + 0, + 0 + ); + + // update SwapData + bytes memory revertReason = abi.encodePacked("Some reason"); + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + swapData[0].callData = abi.encodeWithSelector( + mockDEX.mockSwapWillRevertWithReason.selector, + revertReason + ); + + vm.expectRevert(revertReason); + + genericSwapFacetV4.swapTokensSingleV3NativeToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + } + + function test_WillRevertIfSlippageIsTooHighSingleNativeToERC20() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 minAmountOut + ) = _produceSwapDataNativeToERC20(); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + USDC_ADDRESS, + minAmountOut - 1, + 0 + ); + + // update SwapData + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + vm.expectRevert( + abi.encodeWithSelector( + CumulativeSlippageTooHigh.selector, + minAmountOut, + minAmountOut - 1 + ) + ); + + genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: 2 ether }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData[0] + ); + } + + // MULTISWAP FROM ERC20 TO ERC20 + + function _produceSwapDataMultiswapFromERC20TOERC20( + address facetAddress + ) + private + returns ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) + { + // Swap1: USDC to DAI + address[] memory path = new address[](2); + path[0] = USDC_ADDRESS; + path[1] = DAI_ADDRESS; + + amountIn = 10 * 10 ** usdc.decimals(); + + // Calculate expected DAI amount to be received + uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); + uint256 swappedAmountDAI = amounts[0]; + + // prepare swapData + swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + USDC_ADDRESS, + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + uniswap.swapExactTokensForTokens.selector, + amountIn, + swappedAmountDAI, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + true + ); + + // Swap2: DAI to WETH + path = new address[](2); + path[0] = DAI_ADDRESS; + path[1] = WETH_ADDRESS; + + // Calculate required DAI input amount + amounts = uniswap.getAmountsOut(swappedAmountDAI, path); + minAmountOut = amounts[1]; + + swapData[1] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + DAI_ADDRESS, + WETH_ADDRESS, + swappedAmountDAI, + abi.encodeWithSelector( + uniswap.swapExactTokensForTokens.selector, + swappedAmountDAI, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + false + ); + + vm.startPrank(USDC_HOLDER); + usdc.approve(facetAddress, 10 * 10 ** usdc.decimals()); + } + + function test_CanSwapMultipleFromERC20_V1() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + WETH_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + + vm.stopPrank(); + } + + function test_CanSwapMultipleFromERC20_V2() public { + // ACTIVATE THIS CODE TO TEST GAS USAGE EXCL. MAX APPROVAL + vm.startPrank(address(genericSwapFacet)); + dai.approve(address(uniswap), type(uint256).max); + vm.stopPrank(); + + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + USDC_ADDRESS, // fromAssetId, + WETH_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + + // bytes memory callData = abi.encodeWithSelector( + // genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20.selector, + // "", + // "integrator", + // "referrer", + // payable(SOME_WALLET), + // minAmountOut, + // swapData + // ); + + // console.log("Calldata V2:"); + // console.logBytes(callData); + + vm.stopPrank(); + } + + function test_MultiSwapERC20WillRevertIfSwapFails() public { + // get swapData USDC > ETH (native) + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacet) + ); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + 0, + 0 + ); + + // update SwapData + bytes memory revertReason = abi.encodePacked("Some reason"); + swapData[1].callTo = swapData[1].approveTo = address(mockDEX); + + swapData[1].callData = abi.encodeWithSelector( + mockDEX.mockSwapWillRevertWithReason.selector, + revertReason + ); + + vm.expectRevert(revertReason); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + vm.stopPrank(); + } + + function test_WillRevertIfDEXIsNotWhitelistedMulti() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + // remove dex from whitelist + genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + } + + function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsMulti() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + // update approveTo address in swapData + swapData[1].callTo = SOME_WALLET; + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + } + + function test_WillRevertIfSlippageIsTooHighMultiToERC20() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + WETH_ADDRESS, + minAmountOut - 1, + 0 + ); + + // update SwapData + swapData[1].callTo = swapData[1].approveTo = address(mockDEX); + + vm.expectRevert( + abi.encodeWithSelector( + CumulativeSlippageTooHigh.selector, + minAmountOut, + minAmountOut - 1 + ) + ); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + vm.stopPrank(); + } + + // MULTISWAP FROM NATIVE TO ERC20 + + function _produceSwapDataMultiswapFromNativeToERC20() + private + view + returns ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) + { + // Swap1: Native to DAI + address[] memory path = new address[](2); + path[0] = WETH_ADDRESS; + path[1] = DAI_ADDRESS; + + amountIn = 2 ether; + + // Calculate expected DAI amount to be received + uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); + uint256 swappedAmountDAI = amounts[1]; + + // prepare swapData + swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + address(0), + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + uniswap.swapExactETHForTokens.selector, + swappedAmountDAI, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + true + ); + + // Swap2: DAI to USDC + path = new address[](2); + path[0] = DAI_ADDRESS; + path[1] = USDC_ADDRESS; + + // Calculate required DAI input amount + amounts = uniswap.getAmountsOut(swappedAmountDAI, path); + minAmountOut = amounts[1]; + + swapData[1] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + DAI_ADDRESS, + USDC_ADDRESS, + swappedAmountDAI, + abi.encodeWithSelector( + uniswap.swapExactTokensForTokens.selector, + swappedAmountDAI, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + false + ); + } + + function test_CanSwapMultipleFromNativeToERC20_V1() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromNativeToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + address(0), // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric{ value: amountIn }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + } + + function test_CanSwapMultipleFromNativeToERC20_V2() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromNativeToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + address(0), // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ + value: amountIn + }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + } + + function test_MultiSwapNativeWillRevertIfSwapFails() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromNativeToERC20(); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + 0, + 0 + ); + + // update SwapData + bytes memory revertReason = abi.encodePacked("Some reason"); + swapData[0].callTo = swapData[0].approveTo = address(mockDEX); + + swapData[0].callData = abi.encodeWithSelector( + mockDEX.mockSwapWillRevertWithReason.selector, + revertReason + ); + + vm.expectRevert(revertReason); + + genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ + value: amountIn + }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + } + + function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsMultiNative() + public + { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapFromERC20TOERC20( + address(genericSwapFacetV4) + ); + + // update approveTo address in swapData + swapData[0].approveTo = SOME_WALLET; + + vm.expectRevert(ContractCallNotAllowed.selector); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + } + + // MULTISWAP COLLECT ERC20 FEE AND SWAP to ERC20 + + function _produceSwapDataMultiswapERC20FeeAndSwapToERC20() + private + view + returns ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) + { + amountIn = 100 * 10 ** dai.decimals(); + + uint integratorFee = 5 * 10 ** dai.decimals(); + uint lifiFee = 0; + address integratorAddress = address(0xb33f); // some random address + + // Swap1: Collect ERC20 fee (DAI) + // prepare swapData + swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + FEE_COLLECTOR, + FEE_COLLECTOR, + DAI_ADDRESS, + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + feeCollector.collectTokenFees.selector, + DAI_ADDRESS, + integratorFee, + lifiFee, + integratorAddress + ), + true + ); + + uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; + + // Swap2: DAI to USDC + address[] memory path = new address[](2); + path[0] = DAI_ADDRESS; + path[1] = USDC_ADDRESS; + + // Calculate required DAI input amount + uint256[] memory amounts = uniswap.getAmountsOut( + amountOutFeeCollection, + path + ); + minAmountOut = amounts[1]; + + swapData[1] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + DAI_ADDRESS, + USDC_ADDRESS, + amountOutFeeCollection, + abi.encodeWithSelector( + uniswap.swapExactTokensForTokens.selector, + amountOutFeeCollection, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + false + ); + } + + function test_CanCollectERC20FeesAndSwapToERC20_V1() public { + vm.startPrank(DAI_HOLDER); + dai.approve(address(genericSwapFacet), 100 * 10 ** dai.decimals()); + + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + DAI_ADDRESS, // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + + vm.stopPrank(); + } + + function test_CanCollectERC20FeesAndSwapToERC20_V2() public { + // ACTIVATE THIS CODE TO TEST GAS USAGE EXCL. MAX APPROVAL + vm.startPrank(address(genericSwapFacet)); + dai.approve(address(uniswap), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(DAI_HOLDER); + dai.approve(address(genericSwapFacet), 100 * 10 ** dai.decimals()); + + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + DAI_ADDRESS, // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + + vm.stopPrank(); + } + + // MULTISWAP COLLECT NATIVE FEE AND SWAP TO ERC20 + + function _produceSwapDataMultiswapNativeFeeAndSwapToERC20() + private + view + returns ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) + { + amountIn = 1 ether; + + uint integratorFee = 0.1 ether; + uint lifiFee = 0; + address integratorAddress = address(0xb33f); // some random address + + // Swap1: Collect native fee + // prepare swapData + swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + FEE_COLLECTOR, + FEE_COLLECTOR, + address(0), + address(0), + amountIn, + abi.encodeWithSelector( + feeCollector.collectNativeFees.selector, + integratorFee, + lifiFee, + integratorAddress + ), + true + ); + + uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; + + // Swap2: native to USDC + address[] memory path = new address[](2); + path[0] = WETH_ADDRESS; + path[1] = USDC_ADDRESS; + + // Calculate required DAI input amount + uint256[] memory amounts = uniswap.getAmountsOut( + amountOutFeeCollection, + path + ); + minAmountOut = amounts[1]; + + swapData[1] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + address(0), + USDC_ADDRESS, + amountOutFeeCollection, + abi.encodeWithSelector( + uniswap.swapExactETHForTokens.selector, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + false + ); + } + + function test_CanCollectNativeFeesAndSwap_V1() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapNativeFeeAndSwapToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + address(0), // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric{ value: amountIn }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + } + + function test_CanCollectNativeFeesAndSwap_V2() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapNativeFeeAndSwapToERC20(); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + address(0), // fromAssetId, + USDC_ADDRESS, // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ + value: amountIn + }( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + } + + // MULTISWAP COLLECT ERC20 FEE AND SWAP TO NATIVE + + function _produceSwapDataMultiswapERC20FeeAndSwapToNative( + address facetAddress + ) + private + returns ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) + { + amountIn = 100 * 10 ** dai.decimals(); + + uint integratorFee = 5 * 10 ** dai.decimals(); + uint lifiFee = 0; + address integratorAddress = address(0xb33f); // some random address + + // Swap1: Collect ERC20 fee (5 DAI) + // prepare swapData + swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + FEE_COLLECTOR, + FEE_COLLECTOR, + DAI_ADDRESS, + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + feeCollector.collectTokenFees.selector, + DAI_ADDRESS, + integratorFee, + lifiFee, + integratorAddress + ), + true + ); + + uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; + + // Swap2: DAI to native + address[] memory path = new address[](2); + path[0] = DAI_ADDRESS; + path[1] = WETH_ADDRESS; + + // Calculate required DAI input amount + uint256[] memory amounts = uniswap.getAmountsOut( + amountOutFeeCollection, + path + ); + minAmountOut = amounts[1]; + + swapData[1] = LibSwap.SwapData( + address(uniswap), + address(uniswap), + DAI_ADDRESS, + address(0), + amountOutFeeCollection, + abi.encodeWithSelector( + uniswap.swapExactTokensForETH.selector, + amountOutFeeCollection, + minAmountOut, + path, + address(genericSwapFacet), + block.timestamp + 20 minutes + ), + false + ); + + vm.startPrank(DAI_HOLDER); + dai.approve(facetAddress, amountIn); + } + + function test_CanCollectERC20FeesAndSwapToNative_V1() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( + address(genericSwapFacetV4) + ); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + DAI_ADDRESS, // fromAssetId, + address(0), // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacet.swapTokensGeneric( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V1: ", gasUsed); + } + + function test_CanCollectERC20FeesAndSwapToNative_V2() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( + address(genericSwapFacetV4) + ); + + uint256 gasLeftBef = gasleft(); + + vm.expectEmit(true, true, true, true, address(diamond)); + emit LiFiGenericSwapCompleted( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator, + "referrer", // referrer, + SOME_WALLET, // receiver, + DAI_ADDRESS, // fromAssetId, + address(0), // toAssetId, + amountIn, // fromAmount, + minAmountOut // toAmount (with liquidity in that selected block) + ); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), + minAmountOut, + swapData + ); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used V2: ", gasUsed); + } + + function test_WillRevertIfSlippageIsTooHighMultiToNative() public { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + , + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( + address(genericSwapFacetV4) + ); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + address(0), + minAmountOut - 1, + 0 + ); + + // update SwapData + swapData[1].callTo = swapData[1].approveTo = address(mockDEX); + + vm.expectRevert( + abi.encodeWithSelector( + CumulativeSlippageTooHigh.selector, + minAmountOut, + minAmountOut - 1 + ) + ); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(SOME_WALLET), // receiver + minAmountOut, + swapData + ); + + vm.stopPrank(); + } + + function test_MultiSwapCollectERC20FeesAndSwapToNativeWillRevertIfNativeAssetTransferFails() + public + { + // get swapData + ( + LibSwap.SwapData[] memory swapData, + uint256 amountIn, + uint256 minAmountOut + ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( + address(genericSwapFacetV4) + ); + + // deploy a contract that cannot receive ETH + NonETHReceiver nonETHReceiver = new NonETHReceiver(); + + vm.expectRevert(NativeAssetTransferFailed.selector); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( + "", + "integrator", + "referrer", + payable(address(nonETHReceiver)), + minAmountOut, + swapData + ); + } + + // Test functionality that refunds unused input tokens by DEXs + function test_leavesNoERC20SendingAssetDustSingleSwap() public { + vm.startPrank(USDC_HOLDER); + uint256 initialBalance = usdc.balanceOf(USDC_HOLDER); + + uint256 amountIn = 100 * 10 ** usdc.decimals(); + uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage + uint256 expAmountOut = 100 * 10 ** dai.decimals(); + + // deploy mockDEX to simulate positive slippage + MockUniswapDEX mockDex = new MockUniswapDEX(); + + // prepare swapData using MockDEX + address[] memory path = new address[](2); + path[0] = USDC_ADDRESS; + path[1] = DAI_ADDRESS; + + LibSwap.SwapData memory swapData = LibSwap.SwapData( + address(mockDex), + address(mockDex), + USDC_ADDRESS, + DAI_ADDRESS, + amountIn, + abi.encodeWithSelector( + mockDex.swapTokensForExactTokens.selector, + expAmountOut, + amountIn, + path, + address(genericSwapFacet), // receiver + block.timestamp + 20 minutes + ), + true + ); + + // fund DEX and set swap outcome + deal(path[1], address(mockDex), expAmountOut); + mockDex.setSwapOutput( + amountInActual, // will only pull 99% of the amountIn that we usually expect to be pulled + ERC20(path[1]), + expAmountOut + ); + + // whitelist DEX & function selector + genericSwapFacet.addDex(address(mockDex)); + genericSwapFacet.setFunctionApprovalBySignature( + mockDex.swapTokensForExactTokens.selector + ); + + usdc.approve(address(genericSwapFacet), amountIn); + + genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator + "referrer", // referrer + payable(USDC_HOLDER), // receiver + expAmountOut, + swapData + ); + + assertEq(usdc.balanceOf(address(genericSwapFacet)), 0); + assertEq(usdc.balanceOf(USDC_HOLDER), initialBalance - amountInActual); + + vm.stopPrank(); + } + + function test_leavesNoERC20SendingAssetDustMultiSwap() public { + vm.startPrank(USDC_HOLDER); + uint256 initialBalance = usdc.balanceOf(USDC_HOLDER); + uint256 initialBalanceFeeCollector = usdc.balanceOf(FEE_COLLECTOR); + uint256 initialBalanceDAI = dai.balanceOf(USDC_HOLDER); + + uint256 amountIn = 100 * 10 ** usdc.decimals(); + uint256 expAmountOut = 95 * 10 ** dai.decimals(); + + // prepare swapData + // Swap1: Collect ERC20 fee (5 USDC) + uint integratorFee = 5 * 10 ** usdc.decimals(); + address integratorAddress = address(0xb33f); // some random address + LibSwap.SwapData[] memory swapData = new LibSwap.SwapData[](2); + swapData[0] = LibSwap.SwapData( + FEE_COLLECTOR, + FEE_COLLECTOR, + USDC_ADDRESS, + USDC_ADDRESS, + amountIn, + abi.encodeWithSelector( + feeCollector.collectTokenFees.selector, + USDC_ADDRESS, + integratorFee, + 0, //lifiFee + integratorAddress + ), + true + ); + + uint256 amountOutFeeCollection = amountIn - integratorFee; + + // deploy, fund and whitelist a MockDEX + uint256 amountInActual = (amountOutFeeCollection * 99) / 100; // 1% positive slippage + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + DAI_ADDRESS, + expAmountOut, + amountInActual + ); + + // Swap2: Swap 95 USDC to DAI + address[] memory path = new address[](2); + path[0] = USDC_ADDRESS; + path[1] = DAI_ADDRESS; + + swapData[1] = LibSwap.SwapData( + address(mockDEX), + address(mockDEX), + USDC_ADDRESS, + DAI_ADDRESS, + amountOutFeeCollection, + abi.encodeWithSelector( + mockDEX.swapTokensForExactTokens.selector, + expAmountOut, + amountOutFeeCollection, + path, + address(genericSwapFacet), // receiver + block.timestamp + 20 minutes + ), + false + ); + + usdc.approve(address(genericSwapFacet), amountIn); + + genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator + "referrer", // referrer + payable(USDC_HOLDER), // receiver + expAmountOut, + swapData + ); + + assertEq(usdc.balanceOf(address(genericSwapFacet)), 0); + assertEq( + usdc.balanceOf(FEE_COLLECTOR), + initialBalanceFeeCollector + integratorFee + ); + assertEq( + usdc.balanceOf(USDC_HOLDER), + initialBalance - amountInActual - integratorFee + ); + assertEq(dai.balanceOf(USDC_HOLDER), initialBalanceDAI + expAmountOut); + + vm.stopPrank(); + } + + function test_leavesNoNativeSendingAssetDustSingleSwap() public { + uint256 initialBalanceETH = address(SOME_WALLET).balance; + uint256 initialBalanceUSDC = usdc.balanceOf(address(SOME_WALLET)); + + uint256 amountIn = 1 ether; + uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage + uint256 expAmountOut = 100 * 10 ** usdc.decimals(); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + USDC_ADDRESS, + expAmountOut, + amountInActual + ); + + // prepare swapData using MockDEX + address[] memory path = new address[](2); + path[0] = WETH_ADDRESS; + path[1] = USDC_ADDRESS; + + LibSwap.SwapData memory swapData = LibSwap.SwapData( + address(mockDEX), + address(mockDEX), + address(0), + USDC_ADDRESS, + amountIn, + abi.encodeWithSelector( + mockDEX.swapETHForExactTokens.selector, + expAmountOut, + path, + address(genericSwapFacet), // receiver + block.timestamp + 20 minutes + ), + true + ); + + // execute the swap + genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: amountIn }( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator + "referrer", // referrer + payable(SOME_WALLET), // receiver + expAmountOut, + swapData + ); + + // we expect that the receiver has received the unused native tokens... + assertEq( + address(SOME_WALLET).balance, + initialBalanceETH + (amountIn - amountInActual) + ); + //... and that the swap result was received as well + assertEq( + usdc.balanceOf(SOME_WALLET), + initialBalanceUSDC + expAmountOut + ); + } + + function test_ReturnPositiveSlippageNativeWillRevertIfNativeTransferFails() + public + { + uint256 amountIn = 1 ether; + uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage + uint256 expAmountOut = 100 * 10 ** usdc.decimals(); + + // deploy, fund and whitelist a MockDEX + MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( + address(genericSwapFacetV4), + USDC_ADDRESS, + expAmountOut, + amountInActual + ); + + // prepare swapData using MockDEX + address[] memory path = new address[](2); + path[0] = WETH_ADDRESS; + path[1] = USDC_ADDRESS; + + LibSwap.SwapData memory swapData = LibSwap.SwapData( + address(mockDEX), + address(mockDEX), + address(0), + USDC_ADDRESS, + amountIn, + abi.encodeWithSelector( + mockDEX.swapETHForExactTokens.selector, + expAmountOut, + path, + address(genericSwapFacet), // receiver + block.timestamp + 20 minutes + ), + true + ); + + // deploy a contract that cannot receive ETH + NonETHReceiver nonETHReceiver = new NonETHReceiver(); + + vm.expectRevert(NativeAssetTransferFailed.selector); + + // execute the swap + genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: amountIn }( + 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, + "integrator", // integrator + "referrer", // referrer + payable(address(nonETHReceiver)), // receiver + expAmountOut, + swapData + ); + } +} From f67947133725a10126f09003f6aa791613d182f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 27 Jun 2024 16:01:46 +0700 Subject: [PATCH 02/11] added RouteProcessor4.sol --- src/Periphery/RouteProcessor4.sol | 1178 +++++++++++++++++ test/solidity/Facets/GenericSwapFacetV4.t.sol | 3 + tmpfile | 0 3 files changed, 1181 insertions(+) create mode 100644 src/Periphery/RouteProcessor4.sol create mode 100644 tmpfile diff --git a/src/Periphery/RouteProcessor4.sol b/src/Periphery/RouteProcessor4.sol new file mode 100644 index 000000000..6faad2a4a --- /dev/null +++ b/src/Periphery/RouteProcessor4.sol @@ -0,0 +1,1178 @@ +// SPDX-License-Identifier: UNLICENSED + +pragma solidity ^0.8.17; + +import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; + +address constant NATIVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; +address constant IMPOSSIBLE_POOL_ADDRESS = 0x0000000000000000000000000000000000000001; +address constant INTERNAL_INPUT_SOURCE = 0x0000000000000000000000000000000000000000; + +uint8 constant LOCKED = 2; +uint8 constant NOT_LOCKED = 1; +uint8 constant PAUSED = 2; +uint8 constant NOT_PAUSED = 1; + +/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) +uint160 constant MIN_SQRT_RATIO = 4295128739; +/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) +uint160 constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; + +/// @title A route processor for the Sushi Aggregator +/// @author Ilya Lyalin +contract RouteProcessor4 is Ownable { + using SafeERC20 for IERC20; + using Approve for IERC20; + using SafeERC20 for IERC20Permit; + using InputStream for uint256; + + event Route( + address indexed from, + address to, + address indexed tokenIn, + address indexed tokenOut, + uint256 amountIn, + uint256 amountOutMin, + uint256 amountOut + ); + + error MinimalOutputBalanceViolation(uint256 amountOut); + + IBentoBoxMinimal public immutable bentoBox; + mapping(address => bool) public priviledgedUsers; + address private lastCalledPool; + + uint8 private unlocked = NOT_LOCKED; + uint8 private paused = NOT_PAUSED; + modifier lock() { + require(unlocked == NOT_LOCKED, "RouteProcessor is locked"); + require(paused == NOT_PAUSED, "RouteProcessor is paused"); + unlocked = LOCKED; + _; + unlocked = NOT_LOCKED; + } + + modifier onlyOwnerOrPriviledgedUser() { + require( + msg.sender == owner() || priviledgedUsers[msg.sender], + "RP: caller is not the owner or a privileged user" + ); + _; + } + + constructor(address _bentoBox, address[] memory priviledgedUserList) { + bentoBox = IBentoBoxMinimal(_bentoBox); + lastCalledPool = IMPOSSIBLE_POOL_ADDRESS; + + for (uint256 i = 0; i < priviledgedUserList.length; i++) { + priviledgedUsers[priviledgedUserList[i]] = true; + } + } + + function setPriviledge(address user, bool priviledge) external onlyOwner { + priviledgedUsers[user] = priviledge; + } + + function pause() external onlyOwnerOrPriviledgedUser { + paused = PAUSED; + } + + function resume() external onlyOwnerOrPriviledgedUser { + paused = NOT_PAUSED; + } + + /// @notice For native unwrapping + receive() external payable {} + + /// @notice Processes the route generated off-chain. Has a lock + /// @param tokenIn Address of the input token + /// @param amountIn Amount of the input token + /// @param tokenOut Address of the output token + /// @param amountOutMin Minimum amount of the output token + /// @return amountOut Actual amount of the output token + function processRoute( + address tokenIn, + uint256 amountIn, + address tokenOut, + uint256 amountOutMin, + address to, + bytes memory route + ) external payable lock returns (uint256 amountOut) { + return + processRouteInternal( + tokenIn, + amountIn, + tokenOut, + amountOutMin, + to, + route + ); + } + + /// @notice Transfers some value to and then processes the route + /// @param transferValueTo Address where the value should be transferred + /// @param amountValueTransfer How much value to transfer + /// @param tokenIn Address of the input token + /// @param amountIn Amount of the input token + /// @param tokenOut Address of the output token + /// @param amountOutMin Minimum amount of the output token + /// @return amountOut Actual amount of the output token + function transferValueAndprocessRoute( + address payable transferValueTo, + uint256 amountValueTransfer, + address tokenIn, + uint256 amountIn, + address tokenOut, + uint256 amountOutMin, + address to, + bytes memory route + ) external payable lock returns (uint256 amountOut) { + (bool success, bytes memory returnBytes) = transferValueTo.call{ + value: amountValueTransfer + }(""); + if (!success) { + assembly { + revert(add(32, returnBytes), mload(returnBytes)) + } + } + return + processRouteInternal( + tokenIn, + amountIn, + tokenOut, + amountOutMin, + to, + route + ); + } + + /// @notice Processes the route generated off-chain + /// @param tokenIn Address of the input token + /// @param amountIn Amount of the input token + /// @param tokenOut Address of the output token + /// @param amountOutMin Minimum amount of the output token + /// @return amountOut Actual amount of the output token + function processRouteInternal( + address tokenIn, + uint256 amountIn, + address tokenOut, + uint256 amountOutMin, + address to, + bytes memory route + ) private returns (uint256 amountOut) { + uint256 balanceInInitial = tokenIn == NATIVE_ADDRESS + ? 0 + : IERC20(tokenIn).balanceOf(msg.sender); + uint256 balanceOutInitial = tokenOut == NATIVE_ADDRESS + ? address(to).balance + : IERC20(tokenOut).balanceOf(to); + + uint256 realAmountIn = amountIn; + { + uint256 step = 0; + uint256 stream = InputStream.createStream(route); + while (stream.isNotEmpty()) { + uint8 commandCode = stream.readUint8(); + if (commandCode == 1) { + uint256 usedAmount = processMyERC20(stream); + if (step == 0) realAmountIn = usedAmount; + } else if (commandCode == 2) + processUserERC20(stream, amountIn); + else if (commandCode == 3) { + uint256 usedAmount = processNative(stream); + if (step == 0) realAmountIn = usedAmount; + } else if (commandCode == 4) processOnePool(stream); + else if (commandCode == 5) processInsideBento(stream); + else if (commandCode == 6) applyPermit(tokenIn, stream); + else revert("RouteProcessor: Unknown command code"); + ++step; + } + } + + uint256 balanceInFinal = tokenIn == NATIVE_ADDRESS + ? 0 + : IERC20(tokenIn).balanceOf(msg.sender); + require( + balanceInFinal + amountIn >= balanceInInitial, + "RouteProcessor: Minimal input balance violation" + ); + + uint256 balanceOutFinal = tokenOut == NATIVE_ADDRESS + ? address(to).balance + : IERC20(tokenOut).balanceOf(to); + if (balanceOutFinal < balanceOutInitial + amountOutMin) + revert MinimalOutputBalanceViolation( + balanceOutFinal - balanceOutInitial + ); + + amountOut = balanceOutFinal - balanceOutInitial; + + emit Route( + msg.sender, + to, + tokenIn, + tokenOut, + realAmountIn, + amountOutMin, + amountOut + ); + } + + /// @notice Applies ERC-2612 permit + /// @param tokenIn permitted token + /// @param stream Streamed program + function applyPermit(address tokenIn, uint256 stream) private { + uint256 value = stream.readUint(); + uint256 deadline = stream.readUint(); + uint8 v = stream.readUint8(); + bytes32 r = stream.readBytes32(); + bytes32 s = stream.readBytes32(); + IERC20Permit(tokenIn).safePermit( + msg.sender, + address(this), + value, + deadline, + v, + r, + s + ); + } + + /// @notice Processes native coin: call swap for all pools that swap from native coin + /// @param stream Streamed program + function processNative( + uint256 stream + ) private returns (uint256 amountTotal) { + amountTotal = address(this).balance; + distributeAndSwap(stream, address(this), NATIVE_ADDRESS, amountTotal); + } + + /// @notice Processes ERC20 token from this contract balance: + /// @notice Call swap for all pools that swap from this token + /// @param stream Streamed program + function processMyERC20( + uint256 stream + ) private returns (uint256 amountTotal) { + address token = stream.readAddress(); + amountTotal = IERC20(token).balanceOf(address(this)); + unchecked { + if (amountTotal > 0) amountTotal -= 1; // slot undrain protection + } + distributeAndSwap(stream, address(this), token, amountTotal); + } + + /// @notice Processes ERC20 token from msg.sender balance: + /// @notice Call swap for all pools that swap from this token + /// @param stream Streamed program + /// @param amountTotal Amount of tokens to take from msg.sender + function processUserERC20(uint256 stream, uint256 amountTotal) private { + address token = stream.readAddress(); + distributeAndSwap(stream, msg.sender, token, amountTotal); + } + + /// @notice Processes ERC20 token for cases when the token has only one output pool + /// @notice In this case liquidity is already at pool balance. This is an optimization + /// @notice Call swap for all pools that swap from this token + /// @param stream Streamed program + function processOnePool(uint256 stream) private { + address token = stream.readAddress(); + swap(stream, INTERNAL_INPUT_SOURCE, token, 0); + } + + /// @notice Processes Bento tokens + /// @notice Call swap for all pools that swap from this token + /// @param stream Streamed program + function processInsideBento(uint256 stream) private { + address token = stream.readAddress(); + uint256 amountTotal = bentoBox.balanceOf(token, address(this)); + unchecked { + if (amountTotal > 0) amountTotal -= 1; // slot undrain protection + } + distributeAndSwap(stream, address(this), token, amountTotal); + } + + /// @notice Distributes amountTotal to several pools according to their shares and calls swap for each pool + /// @param stream Streamed program + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountTotal Total amount of tokenIn for swaps + function distributeAndSwap( + uint256 stream, + address from, + address tokenIn, + uint256 amountTotal + ) private { + uint8 num = stream.readUint8(); + unchecked { + for (uint256 i = 0; i < num; ++i) { + uint16 share = stream.readUint16(); + uint256 amount = (amountTotal * share) / + type(uint16).max /*65535*/; + amountTotal -= amount; + swap(stream, from, tokenIn, amount); + } + } + } + + /// @notice Makes swap + /// @param stream Streamed program + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function swap( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + uint8 poolType = stream.readUint8(); + if (poolType == 0) swapUniV2(stream, from, tokenIn, amountIn); + else if (poolType == 1) swapUniV3(stream, from, tokenIn, amountIn); + else if (poolType == 2) wrapNative(stream, from, tokenIn, amountIn); + else if (poolType == 3) bentoBridge(stream, from, tokenIn, amountIn); + else if (poolType == 4) swapTrident(stream, from, tokenIn, amountIn); + else if (poolType == 5) swapCurve(stream, from, tokenIn, amountIn); + else revert("RouteProcessor: Unknown pool type"); + } + + /// @notice Wraps/unwraps native token + /// @param stream [direction & fake, recipient, wrapToken?] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function wrapNative( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + uint8 directionAndFake = stream.readUint8(); + address to = stream.readAddress(); + + if (directionAndFake & 1 == 1) { + // wrap native + address wrapToken = stream.readAddress(); + if (directionAndFake & 2 == 0) + IWETH(wrapToken).deposit{ value: amountIn }(); + if (to != address(this)) + IERC20(wrapToken).safeTransfer(to, amountIn); + } else { + // unwrap native + if (directionAndFake & 2 == 0) { + if (from == msg.sender) + IERC20(tokenIn).safeTransferFrom( + msg.sender, + address(this), + amountIn + ); + IWETH(tokenIn).withdraw(amountIn); + } + (bool success, ) = payable(to).call{ value: amountIn }(""); + require( + success, + "RouteProcessor.wrapNative: Native token transfer failed" + ); + } + } + + /// @notice Bridge/unbridge tokens to/from Bento + /// @param stream [direction, recipient] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function bentoBridge( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + uint8 direction = stream.readUint8(); + address to = stream.readAddress(); + + if (direction > 0) { + // outside to Bento + // deposit to arbitrary recipient is possible only from address(bentoBox) + if (from == address(this)) + IERC20(tokenIn).safeTransfer(address(bentoBox), amountIn); + else if (from == msg.sender) + IERC20(tokenIn).safeTransferFrom( + msg.sender, + address(bentoBox), + amountIn + ); + else { + // tokens already are at address(bentoBox) + amountIn = + IERC20(tokenIn).balanceOf(address(bentoBox)) + + bentoBox.strategyData(tokenIn).balance - + bentoBox.totals(tokenIn).elastic; + } + bentoBox.deposit(tokenIn, address(bentoBox), to, amountIn, 0); + } else { + // Bento to outside + if (from != INTERNAL_INPUT_SOURCE) { + bentoBox.transfer(tokenIn, from, address(this), amountIn); + } else amountIn = bentoBox.balanceOf(tokenIn, address(this)); + bentoBox.withdraw(tokenIn, address(this), to, 0, amountIn); + } + } + + /// @notice UniswapV2 pool swap + /// @param stream [pool, direction, recipient, fee] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function swapUniV2( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + address pool = stream.readAddress(); + uint8 direction = stream.readUint8(); + address to = stream.readAddress(); + uint24 fee = stream.readUint24(); // pool fee in 1/1_000_000 + + if (from == address(this)) + IERC20(tokenIn).safeTransfer(pool, amountIn); + else if (from == msg.sender) + IERC20(tokenIn).safeTransferFrom(msg.sender, pool, amountIn); + + (uint256 r0, uint256 r1, ) = IUniswapV2Pair(pool).getReserves(); + require(r0 > 0 && r1 > 0, "Wrong pool reserves"); + (uint256 reserveIn, uint256 reserveOut) = direction == 1 + ? (r0, r1) + : (r1, r0); + amountIn = IERC20(tokenIn).balanceOf(pool) - reserveIn; // tokens already were transferred + + uint256 amountInWithFee = amountIn * (1_000_000 - fee); + uint256 amountOut = (amountInWithFee * reserveOut) / + (reserveIn * 1_000_000 + amountInWithFee); + (uint256 amount0Out, uint256 amount1Out) = direction == 1 + ? (uint256(0), amountOut) + : (amountOut, uint256(0)); + IUniswapV2Pair(pool).swap(amount0Out, amount1Out, to, new bytes(0)); + } + + /// @notice Trident pool swap + /// @param stream [pool, swapData] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function swapTrident( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + address pool = stream.readAddress(); + bytes memory swapData = stream.readBytes(); + + if (from != INTERNAL_INPUT_SOURCE) { + bentoBox.transfer(tokenIn, from, pool, amountIn); + } + + IPool(pool).swap(swapData); + } + + /// @notice UniswapV3 pool swap + /// @param stream [pool, direction, recipient] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function swapUniV3( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + address pool = stream.readAddress(); + bool zeroForOne = stream.readUint8() > 0; + address recipient = stream.readAddress(); + + if (from == msg.sender) + IERC20(tokenIn).safeTransferFrom( + msg.sender, + address(this), + uint256(amountIn) + ); + + lastCalledPool = pool; + IUniswapV3Pool(pool).swap( + recipient, + zeroForOne, + int256(amountIn), + zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1, + abi.encode(tokenIn) + ); + require( + lastCalledPool == IMPOSSIBLE_POOL_ADDRESS, + "RouteProcessor.swapUniV3: unexpected" + ); // Just to be sure + } + + /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. + /// @dev In the implementation you must pay the pool tokens owed for the swap. + /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. + /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. + /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. + /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. + /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call + function uniswapV3SwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) public { + require( + msg.sender == lastCalledPool, + "RouteProcessor.uniswapV3SwapCallback: call from unknown source" + ); + int256 amount = amount0Delta > 0 ? amount0Delta : amount1Delta; + require( + amount > 0, + "RouteProcessor.uniswapV3SwapCallback: not positive amount" + ); + + lastCalledPool = IMPOSSIBLE_POOL_ADDRESS; + address tokenIn = abi.decode(data, (address)); + IERC20(tokenIn).safeTransfer(msg.sender, uint256(amount)); + } + + /// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap. + /// @dev In the implementation you must pay the pool tokens owed for the swap. + /// The caller of this method _must_ be checked to be a AlgebraPool deployed by the canonical AlgebraFactory. + /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. + /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. + /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. + /// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call + function algebraSwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) external { + uniswapV3SwapCallback(amount0Delta, amount1Delta, data); + } + + /// @notice Called to `msg.sender` after executing a swap via PancakeV3Pool#swap. + /// @dev In the implementation you must pay the pool tokens owed for the swap. + /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. + /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by + /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. + /// @param data Any data passed through by the caller via the PancakeV3Pool#swap call + function pancakeV3SwapCallback( + int256 amount0Delta, + int256 amount1Delta, + bytes calldata data + ) external { + uniswapV3SwapCallback(amount0Delta, amount1Delta, data); + } + + /// @notice Curve pool swap. Legacy pools that don't return amountOut and have native coins are not supported + /// @param stream [pool, poolType, fromIndex, toIndex, recipient, output token] + /// @param from Where to take liquidity for swap + /// @param tokenIn Input token + /// @param amountIn Amount of tokenIn to take for swap + function swapCurve( + uint256 stream, + address from, + address tokenIn, + uint256 amountIn + ) private { + address pool = stream.readAddress(); + uint8 poolType = stream.readUint8(); + int128 fromIndex = int8(stream.readUint8()); + int128 toIndex = int8(stream.readUint8()); + address to = stream.readAddress(); + address tokenOut = stream.readAddress(); + + uint256 amountOut; + if (tokenIn == NATIVE_ADDRESS) { + amountOut = ICurve(pool).exchange{ value: amountIn }( + fromIndex, + toIndex, + amountIn, + 0 + ); + } else { + if (from == msg.sender) + IERC20(tokenIn).safeTransferFrom( + msg.sender, + address(this), + amountIn + ); + IERC20(tokenIn).approveSafe(pool, amountIn); + if (poolType == 0) + amountOut = ICurve(pool).exchange( + fromIndex, + toIndex, + amountIn, + 0 + ); + else { + uint256 balanceBefore = IERC20(tokenOut).balanceOf( + address(this) + ); + ICurveLegacy(pool).exchange(fromIndex, toIndex, amountIn, 0); + uint256 balanceAfter = IERC20(tokenOut).balanceOf( + address(this) + ); + amountOut = balanceAfter - balanceBefore; + } + } + + if (to != address(this)) { + if (tokenOut == NATIVE_ADDRESS) { + (bool success, ) = payable(to).call{ value: amountOut }(""); + require( + success, + "RouteProcessor.swapCurve: Native token transfer failed" + ); + } else { + IERC20(tokenOut).safeTransfer(to, amountOut); + } + } + } +} + +/// @notice Minimal BentoBox vault interface. +/// @dev `token` is aliased as `address` from `IERC20` for simplicity. +interface IBentoBoxMinimal { + /// @notice Balance per ERC-20 token per account in shares. + function balanceOf(address, address) external view returns (uint256); + + /// @dev Helper function to represent an `amount` of `token` in shares. + /// @param token The ERC-20 token. + /// @param amount The `token` amount. + /// @param roundUp If the result `share` should be rounded up. + /// @return share The token amount represented in shares. + function toShare( + address token, + uint256 amount, + bool roundUp + ) external view returns (uint256 share); + + /// @dev Helper function to represent shares back into the `token` amount. + /// @param token The ERC-20 token. + /// @param share The amount of shares. + /// @param roundUp If the result should be rounded up. + /// @return amount The share amount back into native representation. + function toAmount( + address token, + uint256 share, + bool roundUp + ) external view returns (uint256 amount); + + /// @notice Registers this contract so that users can approve it for BentoBox. + function registerProtocol() external; + + /// @notice Deposit an amount of `token` represented in either `amount` or `share`. + /// @param token The ERC-20 token to deposit. + /// @param from which account to pull the tokens. + /// @param to which account to push the tokens. + /// @param amount Token amount in native representation to deposit. + /// @param share Token amount represented in shares to deposit. Takes precedence over `amount`. + /// @return amountOut The amount deposited. + /// @return shareOut The deposited amount represented in shares. + function deposit( + address token, + address from, + address to, + uint256 amount, + uint256 share + ) external payable returns (uint256 amountOut, uint256 shareOut); + + /// @notice Withdraws an amount of `token` from a user account. + /// @param token_ The ERC-20 token to withdraw. + /// @param from which user to pull the tokens. + /// @param to which user to push the tokens. + /// @param amount of tokens. Either one of `amount` or `share` needs to be supplied. + /// @param share Like above, but `share` takes precedence over `amount`. + function withdraw( + address token_, + address from, + address to, + uint256 amount, + uint256 share + ) external returns (uint256 amountOut, uint256 shareOut); + + /// @notice Transfer shares from a user account to another one. + /// @param token The ERC-20 token to transfer. + /// @param from which user to pull the tokens. + /// @param to which user to push the tokens. + /// @param share The amount of `token` in shares. + function transfer( + address token, + address from, + address to, + uint256 share + ) external; + + /// @dev Reads the Rebase `totals`from storage for a given token + function totals(address token) external view returns (Rebase memory total); + + function strategyData( + address token + ) external view returns (StrategyData memory total); + + /// @dev Approves users' BentoBox assets to a "master" contract. + function setMasterContractApproval( + address user, + address masterContract, + bool approved, + uint8 v, + bytes32 r, + bytes32 s + ) external; + + function harvest( + address token, + bool balance, + uint256 maxChangeAmount + ) external; +} + +interface ICurve { + function exchange( + int128 i, + int128 j, + uint256 dx, + uint256 min_dy + ) external payable returns (uint256); +} + +interface ICurveLegacy { + function exchange( + int128 i, + int128 j, + uint256 dx, + uint256 min_dy + ) external payable; +} + +/// @notice Trident pool interface. +interface IPool { + /// @notice Executes a swap from one token to another. + /// @dev The input tokens must've already been sent to the pool. + /// @param data ABI-encoded params that the pool requires. + /// @return finalAmountOut The amount of output tokens that were sent to the user. + function swap( + bytes calldata data + ) external returns (uint256 finalAmountOut); + + /// @notice Executes a swap from one token to another with a callback. + /// @dev This function allows borrowing the output tokens and sending the input tokens in the callback. + /// @param data ABI-encoded params that the pool requires. + /// @return finalAmountOut The amount of output tokens that were sent to the user. + function flashSwap( + bytes calldata data + ) external returns (uint256 finalAmountOut); + + /// @notice Mints liquidity tokens. + /// @param data ABI-encoded params that the pool requires. + /// @return liquidity The amount of liquidity tokens that were minted for the user. + function mint(bytes calldata data) external returns (uint256 liquidity); + + /// @notice Burns liquidity tokens. + /// @dev The input LP tokens must've already been sent to the pool. + /// @param data ABI-encoded params that the pool requires. + /// @return withdrawnAmounts The amount of various output tokens that were sent to the user. + function burn( + bytes calldata data + ) external returns (TokenAmount[] memory withdrawnAmounts); + + /// @notice Burns liquidity tokens for a single output token. + /// @dev The input LP tokens must've already been sent to the pool. + /// @param data ABI-encoded params that the pool requires. + /// @return amountOut The amount of output tokens that were sent to the user. + function burnSingle( + bytes calldata data + ) external returns (uint256 amountOut); + + /// @return A unique identifier for the pool type. + function poolIdentifier() external pure returns (bytes32); + + /// @return An array of tokens supported by the pool. + function getAssets() external view returns (address[] memory); + + /// @notice Simulates a trade and returns the expected output. + /// @dev The pool does not need to include a trade simulator directly in itself - it can use a library. + /// @param data ABI-encoded params that the pool requires. + /// @return finalAmountOut The amount of output tokens that will be sent to the user if the trade is executed. + function getAmountOut( + bytes calldata data + ) external view returns (uint256 finalAmountOut); + + /// @notice Simulates a trade and returns the expected output. + /// @dev The pool does not need to include a trade simulator directly in itself - it can use a library. + /// @param data ABI-encoded params that the pool requires. + /// @return finalAmountIn The amount of input tokens that are required from the user if the trade is executed. + function getAmountIn( + bytes calldata data + ) external view returns (uint256 finalAmountIn); + + /// @dev This event must be emitted on all swaps. + event Swap( + address indexed recipient, + address indexed tokenIn, + address indexed tokenOut, + uint256 amountIn, + uint256 amountOut + ); + + /// @dev This struct frames output tokens for burns. + struct TokenAmount { + address token; + uint256 amount; + } +} + +interface ITridentCLPool { + function token0() external returns (address); + + function token1() external returns (address); + + function swap( + address recipient, + bool zeroForOne, + int256 amountSpecified, + uint160 sqrtPriceLimitX96, + bool unwrapBento, + bytes calldata data + ) external returns (int256 amount0, int256 amount1); +} + +interface IUniswapV2Pair { + event Approval(address indexed owner, address indexed spender, uint value); + event Transfer(address indexed from, address indexed to, uint value); + + function name() external pure returns (string memory); + + function symbol() external pure returns (string memory); + + function decimals() external pure returns (uint8); + + function totalSupply() external view returns (uint); + + function balanceOf(address owner) external view returns (uint); + + function allowance( + address owner, + address spender + ) external view returns (uint); + + function approve(address spender, uint value) external returns (bool); + + function transfer(address to, uint value) external returns (bool); + + function transferFrom( + address from, + address to, + uint value + ) external returns (bool); + + function DOMAIN_SEPARATOR() external view returns (bytes32); + + function PERMIT_TYPEHASH() external pure returns (bytes32); + + function nonces(address owner) external view returns (uint); + + function permit( + address owner, + address spender, + uint value, + uint deadline, + uint8 v, + bytes32 r, + bytes32 s + ) external; + + event Mint(address indexed sender, uint amount0, uint amount1); + event Burn( + address indexed sender, + uint amount0, + uint amount1, + address indexed to + ); + event Swap( + address indexed sender, + uint amount0In, + uint amount1In, + uint amount0Out, + uint amount1Out, + address indexed to + ); + event Sync(uint112 reserve0, uint112 reserve1); + + function MINIMUM_LIQUIDITY() external pure returns (uint); + + function factory() external view returns (address); + + function token0() external view returns (address); + + function token1() external view returns (address); + + function getReserves() + external + view + returns ( + uint112 reserve0, + uint112 reserve1, + uint32 blockTimestampLast + ); + + function price0CumulativeLast() external view returns (uint); + + function price1CumulativeLast() external view returns (uint); + + function kLast() external view returns (uint); + + function mint(address to) external returns (uint liquidity); + + function burn(address to) external returns (uint amount0, uint amount1); + + function swap( + uint amount0Out, + uint amount1Out, + address to, + bytes calldata data + ) external; + + function skim(address to) external; + + function sync() external; + + function initialize(address, address) external; +} + +interface IUniswapV3Pool { + function token0() external returns (address); + + function token1() external returns (address); + + function swap( + address recipient, + bool zeroForOne, + int256 amountSpecified, + uint160 sqrtPriceLimitX96, + bytes calldata data + ) external returns (int256 amount0, int256 amount1); +} + +interface IWETH { + function deposit() external payable; + + function transfer(address to, uint256 value) external returns (bool); + + function withdraw(uint256) external; +} + +/** @notice Simple read stream */ +library InputStream { + /** @notice Creates stream from data + * @param data data + */ + function createStream( + bytes memory data + ) internal pure returns (uint256 stream) { + assembly { + stream := mload(0x40) + mstore(0x40, add(stream, 64)) + mstore(stream, data) + let length := mload(data) + mstore(add(stream, 32), add(data, length)) + } + } + + /** @notice Checks if stream is not empty + * @param stream stream + */ + function isNotEmpty(uint256 stream) internal pure returns (bool) { + uint256 pos; + uint256 finish; + assembly { + pos := mload(stream) + finish := mload(add(stream, 32)) + } + return pos < finish; + } + + /** @notice Reads uint8 from the stream + * @param stream stream + */ + function readUint8(uint256 stream) internal pure returns (uint8 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 1) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads uint16 from the stream + * @param stream stream + */ + function readUint16(uint256 stream) internal pure returns (uint16 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 2) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads uint24 from the stream + * @param stream stream + */ + function readUint24(uint256 stream) internal pure returns (uint24 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 3) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads uint32 from the stream + * @param stream stream + */ + function readUint32(uint256 stream) internal pure returns (uint32 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 4) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads uint256 from the stream + * @param stream stream + */ + function readUint(uint256 stream) internal pure returns (uint256 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 32) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads bytes32 from the stream + * @param stream stream + */ + function readBytes32(uint256 stream) internal pure returns (bytes32 res) { + assembly { + let pos := mload(stream) + pos := add(pos, 32) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads address from the stream + * @param stream stream + */ + function readAddress(uint256 stream) internal pure returns (address res) { + assembly { + let pos := mload(stream) + pos := add(pos, 20) + res := mload(pos) + mstore(stream, pos) + } + } + + /** @notice Reads bytes from the stream + * @param stream stream + */ + function readBytes( + uint256 stream + ) internal pure returns (bytes memory res) { + assembly { + let pos := mload(stream) + res := add(pos, 32) + let length := mload(res) + mstore(stream, add(res, length)) + } + } +} + +library Approve { + /** + * @dev ERC20 approve that correct works with token.approve which returns bool or nothing (USDT for example) + * @param token The token targeted by the call. + * @param spender token spender + * @param amount token amount + */ + function approveStable( + IERC20 token, + address spender, + uint256 amount + ) internal returns (bool) { + (bool success, bytes memory data) = address(token).call( + abi.encodeWithSelector(token.approve.selector, spender, amount) + ); + return success && (data.length == 0 || abi.decode(data, (bool))); + } + + /** + * @dev ERC20 approve that correct works with token.approve which reverts if amount and + * current allowance are not zero simultaniously (USDT for example). + * In second case it tries to set allowance to 0, and then back to amount. + * @param token The token targeted by the call. + * @param spender token spender + * @param amount token amount + */ + function approveSafe( + IERC20 token, + address spender, + uint256 amount + ) internal returns (bool) { + return + approveStable(token, spender, amount) || + (approveStable(token, spender, 0) && + approveStable(token, spender, amount)); + } +} + +struct Rebase { + uint128 elastic; + uint128 base; +} + +struct StrategyData { + uint64 strategyStartDate; + uint64 targetPercentage; + uint128 balance; // the balance of the strategy that BentoBox thinks is in there +} + +/// @notice A rebasing library +library RebaseLibrary { + /// @notice Calculates the base value in relationship to `elastic` and `total`. + function toBase( + Rebase memory total, + uint256 elastic + ) internal pure returns (uint256 base) { + if (total.elastic == 0) { + base = elastic; + } else { + base = (elastic * total.base) / total.elastic; + } + } + + /// @notice Calculates the elastic value in relationship to `base` and `total`. + function toElastic( + Rebase memory total, + uint256 base + ) internal pure returns (uint256 elastic) { + if (total.base == 0) { + elastic = base; + } else { + elastic = (base * total.elastic) / total.base; + } + } +} diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol index e7bb66baf..3ceb3c8a9 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -7,6 +7,7 @@ import { DiamondTest, LiFiDiamond } from "../utils/DiamondTest.sol"; import { Vm } from "forge-std/Vm.sol"; import { GenericSwapFacet } from "lifi/Facets/GenericSwapFacet.sol"; import { GenericSwapFacetV4 } from "lifi/Facets/GenericSwapFacetV4.sol"; +import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; import { LibSwap } from "lifi/Libraries/LibSwap.sol"; import { LibAllowList } from "lifi/Libraries/LibAllowList.sol"; import { FeeCollector } from "lifi/Periphery/FeeCollector.sol"; @@ -92,6 +93,7 @@ contract GenericSwapFacetV4Test is DSTest, DiamondTest, TestHelpers { ERC20 internal weth; UniswapV2Router02 internal uniswap; FeeCollector internal feeCollector; + RouteProcessor4 internal routeProcessor; function fork() internal { string memory rpcUrl = vm.envString("ETH_NODE_URI_MAINNET"); @@ -111,6 +113,7 @@ contract GenericSwapFacetV4Test is DSTest, DiamondTest, TestHelpers { weth = ERC20(WETH_ADDRESS); uniswap = UniswapV2Router02(UNISWAP_V2_ROUTER); feeCollector = FeeCollector(FEE_COLLECTOR); + routeProcessor = new RouteProcessor4(address(0), new address[](0)); // add genericSwapFacet (v1) to diamond (for gas usage comparison) bytes4[] memory functionSelectors = new bytes4[](4); diff --git a/tmpfile b/tmpfile new file mode 100644 index 000000000..e69de29bb From 7eeb62e9efff9768bb06db9bd4e1927ff46df417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Tue, 9 Jul 2024 11:20:26 +0700 Subject: [PATCH 03/11] all tests fixed for single swaps --- src/Facets/GenericSwapFacetV4.sol | 231 +- src/Periphery/RouteProcessor4.sol | 1 + test/solidity/Facets/AcrossFacetPacked.t.sol | 2 - test/solidity/Facets/AmarokFacetPacked.t.sol | 2 - test/solidity/Facets/GenericSwapFacetV3.t.sol | 240 +- test/solidity/Facets/GenericSwapFacetV4.t.sol | 2363 +++-------------- test/solidity/Facets/StargateFacet.t.sol | 2 - test/solidity/Facets/StargateFacetV2.t.sol | 2 - .../Periphery/ReceiverStargateV2.t.sol | 54 +- test/solidity/utils/TestBase.sol | 18 +- test/solidity/utils/TestHelpers.sol | 81 +- 11 files changed, 589 insertions(+), 2407 deletions(-) diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Facets/GenericSwapFacetV4.sol index 7bfa130e8..023766f61 100644 --- a/src/Facets/GenericSwapFacetV4.sol +++ b/src/Facets/GenericSwapFacetV4.sol @@ -6,8 +6,12 @@ import { LibUtil } from "../Libraries/LibUtil.sol"; import { LibSwap } from "../Libraries/LibSwap.sol"; import { LibAllowList } from "../Libraries/LibAllowList.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; -import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData } from "../Errors/GenericErrors.sol"; + +//TODO: replace with solady import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; + +//TODO: remove import { console2 } from "forge-std/console2.sol"; /// @title GenericSwapFacetV4 @@ -18,141 +22,125 @@ import { console2 } from "forge-std/console2.sol"; contract GenericSwapFacetV4 is ILiFi { using SafeTransferLib for ERC20; + /// Storage /// + + address public immutable dexAggregatorAddress; + + /// Constructor + + /// @notice Initialize the contract + /// @param _dexAggregatorAddress The address of the DEX aggregator + constructor(address _dexAggregatorAddress) { + dexAggregatorAddress = _dexAggregatorAddress; + } + + /// Modifier + modifier onlyCallsToDexAggregator(address callTo) { + if (callTo != dexAggregatorAddress) revert InvalidCallData(); + _; + } + /// External Methods /// // SINGLE SWAPS /// @notice Performs a single swap from an ERC20 token to another ERC20 token - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer + /// @param (unused)_transactionId the transaction id associated with the operation + /// @param (unused) _integrator the name of the integrator + /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3ERC20ToERC20( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, - address payable _receiver, + bytes32, + string calldata, + string calldata, + address _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData - ) external { - _depositAndSwapERC20Single(_swapData, _receiver); - - address receivingAssetId = _swapData.receivingAssetId; - address sendingAssetId = _swapData.sendingAssetId; + ) external onlyCallsToDexAggregator(_swapData.callTo) { + ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); + // deposit funds + sendingAsset.safeTransferFrom( + msg.sender, + address(this), + _swapData.fromAmount + ); - // get contract's balance (which will be sent in full to user) - uint256 amountReceived = ERC20(receivingAssetId).balanceOf( - address(this) + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = _swapData.callTo.call( + _swapData.callData ); + if (!success) { + LibUtil.revertWith(res); + } - // ensure that minAmountOut was received + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); if (amountReceived < _minAmountOut) revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - // transfer funds to receiver - ERC20(receivingAssetId).safeTransfer(_receiver, amountReceived); - - // emit events (both required for tracking) - uint256 fromAmount = _swapData.fromAmount; - emit LibSwap.AssetSwapped( - _transactionId, - _swapData.callTo, - sendingAssetId, - receivingAssetId, - fromAmount, - amountReceived, - block.timestamp - ); - - emit ILiFi.LiFiGenericSwapCompleted( - _transactionId, - _integrator, - _referrer, - _receiver, - sendingAssetId, - receivingAssetId, - fromAmount, - amountReceived - ); + _returnPositiveSlippageERC20(sendingAsset, _receiver); } /// @notice Performs a single swap from an ERC20 token to the network's native token - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer + /// @param (unused)_transactionId the transaction id associated with the operation + /// @param (unused) _integrator the name of the integrator + /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3ERC20ToNative( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, + bytes32, + string calldata, + string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData - ) external { - _depositAndSwapERC20Single(_swapData, _receiver); - - // get contract's balance (which will be sent in full to user) - uint256 amountReceived = address(this).balance; + ) external onlyCallsToDexAggregator(_swapData.callTo) { + ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); - // ensure that minAmountOut was received - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + // deposit funds + sendingAsset.safeTransferFrom( + msg.sender, + address(this), + _swapData.fromAmount + ); - // transfer funds to receiver + // execute swap // solhint-disable-next-line avoid-low-level-calls - (bool success, ) = _receiver.call{ value: amountReceived }(""); - if (!success) revert NativeAssetTransferFailed(); - - // emit events (both required for tracking) - address sendingAssetId = _swapData.sendingAssetId; - uint256 fromAmount = _swapData.fromAmount; - emit LibSwap.AssetSwapped( - _transactionId, - _swapData.callTo, - sendingAssetId, - address(0), - fromAmount, - amountReceived, - block.timestamp + (bool success, bytes memory res) = _swapData.callTo.call( + _swapData.callData ); + if (!success) { + LibUtil.revertWith(res); + } - emit ILiFi.LiFiGenericSwapCompleted( - _transactionId, - _integrator, - _referrer, - _receiver, - sendingAssetId, - address(0), - fromAmount, - amountReceived - ); + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + _returnPositiveSlippageNative(_receiver); } /// @notice Performs a single swap from the network's native token to ERC20 token - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer + /// @param (unused)_transactionId the transaction id associated with the operation + /// @param (unused) _integrator the name of the integrator + /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3NativeToERC20( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, + bytes32, + string calldata, + string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData - ) external payable { + ) external payable onlyCallsToDexAggregator(_swapData.callTo) { address callTo = _swapData.callTo; - // ensure that contract (callTo) and function selector are whitelisted - if ( - !(LibAllowList.contractIsAllowed(callTo) && - LibAllowList.selectorIsAllowed(bytes4(_swapData.callData[:4]))) - ) revert ContractCallNotAllowed(); // execute swap // solhint-disable-next-line avoid-low-level-calls @@ -163,39 +151,13 @@ contract GenericSwapFacetV4 is ILiFi { LibUtil.revertWith(res); } - _returnPositiveSlippageNative(_receiver); - - // get contract's balance (which will be sent in full to user) - address receivingAssetId = _swapData.receivingAssetId; - uint256 amountReceived = ERC20(receivingAssetId).balanceOf( - address(this) - ); - - // transfer funds to receiver - ERC20(receivingAssetId).safeTransfer(_receiver, amountReceived); - - // emit events (both required for tracking) - uint256 fromAmount = _swapData.fromAmount; - emit LibSwap.AssetSwapped( - _transactionId, - callTo, - address(0), - receivingAssetId, - fromAmount, - amountReceived, - block.timestamp - ); + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - emit ILiFi.LiFiGenericSwapCompleted( - _transactionId, - _integrator, - _referrer, - _receiver, - address(0), - receivingAssetId, - fromAmount, - amountReceived - ); + // return any positive slippage (i.e. unused sendingAsset tokens) + _returnPositiveSlippageNative(_receiver); } // MULTIPLE SWAPS @@ -309,24 +271,17 @@ contract GenericSwapFacetV4 is ILiFi { function _depositAndSwapERC20Single( LibSwap.SwapData calldata _swapData, address _receiver - ) private { + ) private onlyCallsToDexAggregator(_swapData.callTo) { ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); uint256 fromAmount = _swapData.fromAmount; // deposit funds sendingAsset.safeTransferFrom(msg.sender, address(this), fromAmount); - // ensure that contract (callTo) and function selector are whitelisted - address callTo = _swapData.callTo; - address approveTo = _swapData.approveTo; - bytes calldata callData = _swapData.callData; - if ( - !(LibAllowList.contractIsAllowed(callTo) && - LibAllowList.selectorIsAllowed(bytes4(callData[:4]))) - ) revert ContractCallNotAllowed(); - // execute swap // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = callTo.call(callData); + (bool success, bytes memory res) = _swapData.callTo.call( + _swapData.callData + ); if (!success) { LibUtil.revertWith(res); } @@ -484,7 +439,6 @@ contract GenericSwapFacetV4 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) private { - console2.log("in _transferNativeTokensAndEmitEvent"); uint256 amountReceived = address(this).balance; // make sure minAmountOut was received @@ -495,7 +449,6 @@ contract GenericSwapFacetV4 is ILiFi { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = _receiver.call{ value: amountReceived }(""); if (!success) { - console2.log("HEYA"); revert NativeAssetTransferFailed(); } @@ -540,4 +493,6 @@ contract GenericSwapFacetV4 is ILiFi { if (!success) revert NativeAssetTransferFailed(); } } + + receive() external payable {} } diff --git a/src/Periphery/RouteProcessor4.sol b/src/Periphery/RouteProcessor4.sol index 6faad2a4a..dad801826 100644 --- a/src/Periphery/RouteProcessor4.sol +++ b/src/Periphery/RouteProcessor4.sol @@ -4,6 +4,7 @@ pragma solidity ^0.8.17; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; +import { console2 } from "forge-std/console2.sol"; address constant NATIVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address constant IMPOSSIBLE_POOL_ADDRESS = 0x0000000000000000000000000000000000000001; diff --git a/test/solidity/Facets/AcrossFacetPacked.t.sol b/test/solidity/Facets/AcrossFacetPacked.t.sol index 97502766a..bf7d47837 100644 --- a/test/solidity/Facets/AcrossFacetPacked.t.sol +++ b/test/solidity/Facets/AcrossFacetPacked.t.sol @@ -33,7 +33,6 @@ contract AcrossFacetPackedTest is TestBase { 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; address internal constant ACROSS_SPOKE_POOL = 0x5c7BCd6E7De5423a257D81B442095A1a6ced35C5; - address internal ADDRESS_USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address internal ACROSS_MERKLE_DISTRIBUTOR = 0xE50b2cEAC4f60E840Ae513924033E753e2366487; address internal ADDRESS_ACX_TOKEN = @@ -45,7 +44,6 @@ contract AcrossFacetPackedTest is TestBase { // hex"6be65179000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000025caeae03fa5e8a977e00000000000000000000000000000000000000000000000000000000000000010000000000000000000000001231deb6f5749ef6ce6943a275a1d3e7486f4eae00000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000001055b9ce9b3807a4c1c9fc153177c53f06a40ba12d85ce795dde69d6eef999a7282c5ebbef91605a598965d1b963839cd0e36ac96ddcf53c200b1dd078301fb60991645e735d8523c0ddcee94e99db3d6cfc776becceb9babb4eee7d809b0a713436657df91f4ec9632556d4568a8604f76803fcf31a7f2297154dbf15fe4dedd4119740befa50ec31eecdc2407e7e294d5347166c79a062cf1b5e23908d76a10be7444d231b26cbed964c0d15c4aaa6fe4993becd1258cc2fa21a0d6ac29d89b57c9229e5ae3e0bd5587e19598f18679e9cb7e83196b39cbbf526076002219b9f74ff541139196c51f181c06194141c0b7d7af034a186a7bf862c7513e5398ccfa151bc3c6ff4689f723450d099644a46b6dbe639ff9ead83bf219648344cabfab2aa64aaa9f3eda6a4c824313a3e5005591c2e954f87e3b9f2228e87cf346f13c19136eca2ce03070ad5a063196e28955317b796ac7122bea188a8a615982531e84b5577546abc99c21005b2c0bd40700159702d4bf99334d3a3bb4cb8482085aefceb8f2e73ecff885d542e44e69206a0c27e6d2cc0401db980cc5c1e67c984b3f0ec51e1e15d3311d4feed306df497d582f55e1bd8e67a4336d1e8614fdf5fbfbcbe4ddc694d5b97547584ec24c28f8bce7a6a724213dc6a92282e7409d1453a960df1a25d1db6799308467dc975a70d97405e48138f20e914f3d44e5b06dd"; IAcrossSpokePool internal across; - ERC20 internal usdt; AcrossFacetPacked internal acrossFacetPacked; AcrossFacetPacked internal acrossStandAlone; AcrossFacet.AcrossData internal validAcrossData; diff --git a/test/solidity/Facets/AmarokFacetPacked.t.sol b/test/solidity/Facets/AmarokFacetPacked.t.sol index 3fb90a49e..7ac78c47c 100644 --- a/test/solidity/Facets/AmarokFacetPacked.t.sol +++ b/test/solidity/Facets/AmarokFacetPacked.t.sol @@ -16,11 +16,9 @@ contract AmarokFacetPackedTest is TestBase { address internal constant CONNEXT_HANDLER = 0x8898B472C54c31894e3B9bb83cEA802a5d0e63C6; - address internal ADDRESS_USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; uint256 internal BSC_CHAIN_ID = 56; IConnextHandler internal amarok; - ERC20 internal usdt; AmarokFacetPacked internal amarokFacetPacked; AmarokFacetPacked internal amarokStandAlone; AmarokFacet.AmarokData internal validAmarokData; diff --git a/test/solidity/Facets/GenericSwapFacetV3.t.sol b/test/solidity/Facets/GenericSwapFacetV3.t.sol index 815ac05fe..0795e2755 100644 --- a/test/solidity/Facets/GenericSwapFacetV3.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV3.t.sol @@ -47,69 +47,31 @@ contract TestGenericSwapFacet is GenericSwapFacet { } } -contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { +contract GenericSwapFacetV3Test is TestHelpers { using SafeTransferLib for ERC20; - event LiFiGenericSwapCompleted( - bytes32 indexed transactionId, - string integrator, - string referrer, - address receiver, - address fromAssetId, - address toAssetId, - uint256 fromAmount, - uint256 toAmount - ); - // These values are for Mainnet - address internal constant USDC_ADDRESS = - 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; - address internal constant USDT_ADDRESS = - 0xdAC17F958D2ee523a2206206994597C13D831ec7; - address internal constant WETH_ADDRESS = - 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; - address internal constant DAI_ADDRESS = - 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC_HOLDER = 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; address internal constant DAI_HOLDER = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; address internal constant SOME_WALLET = 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; - address internal constant UNISWAP_V2_ROUTER = - 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal constant FEE_COLLECTOR = 0xbD6C7B0d2f68c2b7805d88388319cfB6EcB50eA9; // ----- - LiFiDiamond internal diamond; TestGenericSwapFacet internal genericSwapFacet; TestGenericSwapFacetV3 internal genericSwapFacetV3; - ERC20 internal usdc; - ERC20 internal usdt; - ERC20 internal dai; - ERC20 internal weth; - UniswapV2Router02 internal uniswap; - FeeCollector internal feeCollector; - - function fork() internal { - string memory rpcUrl = vm.envString("ETH_NODE_URI_MAINNET"); - uint256 blockNumber = 19834820; - vm.createSelectFork(rpcUrl, blockNumber); - } function setUp() public { - fork(); + customBlockNumberForForking = 19834820; + initTestBase(); diamond = createDiamond(); genericSwapFacet = new TestGenericSwapFacet(); genericSwapFacetV3 = new TestGenericSwapFacetV3(); - usdc = ERC20(USDC_ADDRESS); - usdt = ERC20(USDT_ADDRESS); - dai = ERC20(DAI_ADDRESS); - weth = ERC20(WETH_ADDRESS); - uniswap = UniswapV2Router02(UNISWAP_V2_ROUTER); feeCollector = FeeCollector(FEE_COLLECTOR); // add genericSwapFacet (v1) to diamond (for gas usage comparison) @@ -197,10 +159,10 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { ); vm.label(address(genericSwapFacet), "LiFiDiamond"); - vm.label(WETH_ADDRESS, "WETH_TOKEN"); - vm.label(DAI_ADDRESS, "DAI_TOKEN"); - vm.label(USDC_ADDRESS, "USDC_TOKEN"); - vm.label(UNISWAP_V2_ROUTER, "UNISWAP_V2_ROUTER"); + vm.label(ADDRESS_WETH, "WETH_TOKEN"); + vm.label(ADDRESS_DAI, "DAI_TOKEN"); + vm.label(ADDRESS_USDC, "USDC_TOKEN"); + vm.label(ADDRESS_UNISWAP, "ADDRESS_UNISWAP"); } // SINGLE SWAP ERC20 >> ERC20 @@ -212,8 +174,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { { // Swap USDC to DAI address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; + path[0] = ADDRESS_USDC; + path[1] = ADDRESS_DAI; uint256 amountIn = 100 * 10 ** usdc.decimals(); @@ -226,8 +188,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( address(uniswap), address(uniswap), - USDC_ADDRESS, - DAI_ADDRESS, + ADDRESS_USDC, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( uniswap.swapExactTokensForTokens.selector, @@ -263,8 +225,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_DAI, // toAssetId, swapData[0].fromAmount, // fromAmount, expAmountOut // toAmount (with liquidity in that selected block) ); @@ -322,8 +284,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_DAI, // toAssetId, swapData[0].fromAmount, // fromAmount, expAmountOut // toAmount (with liquidity in that selected block) ); @@ -366,7 +328,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // deploy, fund and whitelist a MockDEX MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - DAI_ADDRESS, + ADDRESS_DAI, minAmountOut - 1, 0 ); @@ -443,8 +405,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_DAI, // toAssetId, swapData[0].fromAmount, // fromAmount, expAmountOut // toAmount (with liquidity in that selected block) ); @@ -484,8 +446,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_DAI, // toAssetId, swapData[0].fromAmount, // fromAmount, expAmountOut // toAmount (with liquidity in that selected block) ); @@ -511,8 +473,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { { // Swap USDC to Native ETH address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = WETH_ADDRESS; + path[0] = ADDRESS_USDC; + path[1] = ADDRESS_WETH; minAmountOut = 2 ether; @@ -525,7 +487,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( address(uniswap), address(uniswap), - USDC_ADDRESS, + ADDRESS_USDC, address(0), amountIn, abi.encodeWithSelector( @@ -560,7 +522,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, + ADDRESS_USDC, // fromAssetId, address(0), // toAssetId, swapData[0].fromAmount, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) @@ -603,7 +565,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, + ADDRESS_USDC, // fromAssetId, address(0), // toAssetId, swapData[0].fromAmount, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) @@ -714,7 +676,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { vm.startPrank(USDC_HOLDER); // remove dex from whitelist - genericSwapFacetV3.removeDex(UNISWAP_V2_ROUTER); + genericSwapFacetV3.removeDex(ADDRESS_UNISWAP); vm.expectRevert(ContractCallNotAllowed.selector); @@ -764,8 +726,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { { // Swap native to USDC address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_WETH; + path[1] = ADDRESS_USDC; uint256 amountIn = 2 ether; @@ -779,7 +741,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { address(uniswap), address(uniswap), address(0), - USDC_ADDRESS, + ADDRESS_USDC, amountIn, abi.encodeWithSelector( uniswap.swapExactETHForTokens.selector, @@ -808,7 +770,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, swapData[0].fromAmount, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -842,7 +804,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, swapData[0].fromAmount, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -870,7 +832,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { ) = _produceSwapDataNativeToERC20(); // remove dex from whitelist - genericSwapFacetV3.removeDex(UNISWAP_V2_ROUTER); + genericSwapFacetV3.removeDex(ADDRESS_UNISWAP); vm.expectRevert(ContractCallNotAllowed.selector); @@ -932,7 +894,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // deploy, fund and whitelist a MockDEX MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - USDC_ADDRESS, + ADDRESS_USDC, minAmountOut - 1, 0 ); @@ -972,8 +934,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { { // Swap1: USDC to DAI address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; + path[0] = ADDRESS_USDC; + path[1] = ADDRESS_DAI; amountIn = 10 * 10 ** usdc.decimals(); @@ -986,8 +948,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( address(uniswap), address(uniswap), - USDC_ADDRESS, - DAI_ADDRESS, + ADDRESS_USDC, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( uniswap.swapExactTokensForTokens.selector, @@ -1002,8 +964,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // Swap2: DAI to WETH path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = WETH_ADDRESS; + path[0] = ADDRESS_DAI; + path[1] = ADDRESS_WETH; // Calculate required DAI input amount amounts = uniswap.getAmountsOut(swappedAmountDAI, path); @@ -1012,8 +974,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[1] = LibSwap.SwapData( address(uniswap), address(uniswap), - DAI_ADDRESS, - WETH_ADDRESS, + ADDRESS_DAI, + ADDRESS_WETH, swappedAmountDAI, abi.encodeWithSelector( uniswap.swapExactTokensForTokens.selector, @@ -1048,8 +1010,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - WETH_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_WETH, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1092,8 +1054,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - WETH_ADDRESS, // toAssetId, + ADDRESS_USDC, // fromAssetId, + ADDRESS_WETH, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1178,7 +1140,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { ); // remove dex from whitelist - genericSwapFacetV3.removeDex(UNISWAP_V2_ROUTER); + genericSwapFacetV3.removeDex(ADDRESS_UNISWAP); vm.expectRevert(ContractCallNotAllowed.selector); @@ -1230,7 +1192,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // deploy, fund and whitelist a MockDEX MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - WETH_ADDRESS, + ADDRESS_WETH, minAmountOut - 1, 0 ); @@ -1271,8 +1233,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { { // Swap1: Native to DAI address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = DAI_ADDRESS; + path[0] = ADDRESS_WETH; + path[1] = ADDRESS_DAI; amountIn = 2 ether; @@ -1286,7 +1248,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { address(uniswap), address(uniswap), address(0), - DAI_ADDRESS, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( uniswap.swapExactETHForTokens.selector, @@ -1300,8 +1262,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // Swap2: DAI to USDC path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_DAI; + path[1] = ADDRESS_USDC; // Calculate required DAI input amount amounts = uniswap.getAmountsOut(swappedAmountDAI, path); @@ -1310,8 +1272,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[1] = LibSwap.SwapData( address(uniswap), address(uniswap), - DAI_ADDRESS, - USDC_ADDRESS, + ADDRESS_DAI, + ADDRESS_USDC, swappedAmountDAI, abi.encodeWithSelector( uniswap.swapExactTokensForTokens.selector, @@ -1342,7 +1304,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1377,7 +1339,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1486,12 +1448,12 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( FEE_COLLECTOR, FEE_COLLECTOR, - DAI_ADDRESS, - DAI_ADDRESS, + ADDRESS_DAI, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( feeCollector.collectTokenFees.selector, - DAI_ADDRESS, + ADDRESS_DAI, integratorFee, lifiFee, integratorAddress @@ -1503,8 +1465,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // Swap2: DAI to USDC address[] memory path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_DAI; + path[1] = ADDRESS_USDC; // Calculate required DAI input amount uint256[] memory amounts = uniswap.getAmountsOut( @@ -1516,8 +1478,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[1] = LibSwap.SwapData( address(uniswap), address(uniswap), - DAI_ADDRESS, - USDC_ADDRESS, + ADDRESS_DAI, + ADDRESS_USDC, amountOutFeeCollection, abi.encodeWithSelector( uniswap.swapExactTokensForTokens.selector, @@ -1550,8 +1512,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_DAI, // fromAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1595,8 +1557,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_DAI, // fromAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1655,8 +1617,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // Swap2: native to USDC address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_WETH; + path[1] = ADDRESS_USDC; // Calculate required DAI input amount uint256[] memory amounts = uniswap.getAmountsOut( @@ -1669,7 +1631,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { address(uniswap), address(uniswap), address(0), - USDC_ADDRESS, + ADDRESS_USDC, amountOutFeeCollection, abi.encodeWithSelector( uniswap.swapExactETHForTokens.selector, @@ -1699,7 +1661,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1734,7 +1696,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "referrer", // referrer, SOME_WALLET, // receiver, address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, + ADDRESS_USDC, // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) ); @@ -1778,12 +1740,12 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( FEE_COLLECTOR, FEE_COLLECTOR, - DAI_ADDRESS, - DAI_ADDRESS, + ADDRESS_DAI, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( feeCollector.collectTokenFees.selector, - DAI_ADDRESS, + ADDRESS_DAI, integratorFee, lifiFee, integratorAddress @@ -1795,8 +1757,8 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // Swap2: DAI to native address[] memory path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = WETH_ADDRESS; + path[0] = ADDRESS_DAI; + path[1] = ADDRESS_WETH; // Calculate required DAI input amount uint256[] memory amounts = uniswap.getAmountsOut( @@ -1808,7 +1770,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[1] = LibSwap.SwapData( address(uniswap), address(uniswap), - DAI_ADDRESS, + ADDRESS_DAI, address(0), amountOutFeeCollection, abi.encodeWithSelector( @@ -1844,7 +1806,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, + ADDRESS_DAI, // fromAssetId, address(0), // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) @@ -1881,7 +1843,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { "integrator", // integrator, "referrer", // referrer, SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, + ADDRESS_DAI, // fromAssetId, address(0), // toAssetId, amountIn, // fromAmount, minAmountOut // toAmount (with liquidity in that selected block) @@ -1947,7 +1909,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // get swapData ( LibSwap.SwapData[] memory swapData, - uint256 amountIn, + , uint256 minAmountOut ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( address(genericSwapFacetV3) @@ -1982,14 +1944,14 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // prepare swapData using MockDEX address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; + path[0] = ADDRESS_USDC; + path[1] = ADDRESS_DAI; LibSwap.SwapData memory swapData = LibSwap.SwapData( address(mockDex), address(mockDex), - USDC_ADDRESS, - DAI_ADDRESS, + ADDRESS_USDC, + ADDRESS_DAI, amountIn, abi.encodeWithSelector( mockDex.swapTokensForExactTokens.selector, @@ -2050,12 +2012,12 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { swapData[0] = LibSwap.SwapData( FEE_COLLECTOR, FEE_COLLECTOR, - USDC_ADDRESS, - USDC_ADDRESS, + ADDRESS_USDC, + ADDRESS_USDC, amountIn, abi.encodeWithSelector( feeCollector.collectTokenFees.selector, - USDC_ADDRESS, + ADDRESS_USDC, integratorFee, 0, //lifiFee integratorAddress @@ -2069,21 +2031,21 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { uint256 amountInActual = (amountOutFeeCollection * 99) / 100; // 1% positive slippage MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - DAI_ADDRESS, + ADDRESS_DAI, expAmountOut, amountInActual ); // Swap2: Swap 95 USDC to DAI address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; + path[0] = ADDRESS_USDC; + path[1] = ADDRESS_DAI; swapData[1] = LibSwap.SwapData( address(mockDEX), address(mockDEX), - USDC_ADDRESS, - DAI_ADDRESS, + ADDRESS_USDC, + ADDRESS_DAI, amountOutFeeCollection, abi.encodeWithSelector( mockDEX.swapTokensForExactTokens.selector, @@ -2132,21 +2094,21 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // deploy, fund and whitelist a MockDEX MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - USDC_ADDRESS, + ADDRESS_USDC, expAmountOut, amountInActual ); // prepare swapData using MockDEX address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_WETH; + path[1] = ADDRESS_USDC; LibSwap.SwapData memory swapData = LibSwap.SwapData( address(mockDEX), address(mockDEX), address(0), - USDC_ADDRESS, + ADDRESS_USDC, amountIn, abi.encodeWithSelector( mockDEX.swapETHForExactTokens.selector, @@ -2190,21 +2152,21 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // deploy, fund and whitelist a MockDEX MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( address(genericSwapFacetV3), - USDC_ADDRESS, + ADDRESS_USDC, expAmountOut, amountInActual ); // prepare swapData using MockDEX address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; + path[0] = ADDRESS_WETH; + path[1] = ADDRESS_USDC; LibSwap.SwapData memory swapData = LibSwap.SwapData( address(mockDEX), address(mockDEX), address(0), - USDC_ADDRESS, + ADDRESS_USDC, amountIn, abi.encodeWithSelector( mockDEX.swapETHForExactTokens.selector, diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol index 3ceb3c8a9..ec77594b3 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -1,26 +1,21 @@ // SPDX-License-Identifier: Unlicense pragma solidity 0.8.17; -import { Test, DSTest } from "forge-std/Test.sol"; -import { console } from "../utils/Console.sol"; -import { DiamondTest, LiFiDiamond } from "../utils/DiamondTest.sol"; -import { Vm } from "forge-std/Vm.sol"; -import { GenericSwapFacet } from "lifi/Facets/GenericSwapFacet.sol"; +import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; import { GenericSwapFacetV4 } from "lifi/Facets/GenericSwapFacetV4.sol"; import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; -import { LibSwap } from "lifi/Libraries/LibSwap.sol"; -import { LibAllowList } from "lifi/Libraries/LibAllowList.sol"; -import { FeeCollector } from "lifi/Periphery/FeeCollector.sol"; -import { ERC20 } from "solmate/tokens/ERC20.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "lifi/Errors/GenericErrors.sol"; -import { UniswapV2Router02 } from "../utils/Interfaces.sol"; -// import { MockUniswapDEX } from "../utils/MockUniswapDEX.sol"; -import { TestHelpers, MockUniswapDEX, NonETHReceiver } from "../utils/TestHelpers.sol"; -import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; +import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; + +import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; // TODO: replace with SOLADY // Stub GenericSwapFacet Contract -contract TestGenericSwapFacetV4 is GenericSwapFacetV4, GenericSwapFacet { +contract TestGenericSwapFacetV4 is GenericSwapFacetV4 { + constructor( + address _dexAggregatorAddress + ) GenericSwapFacetV4(_dexAggregatorAddress) {} + function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); } @@ -34,7 +29,7 @@ contract TestGenericSwapFacetV4 is GenericSwapFacetV4, GenericSwapFacet { } } -contract TestGenericSwapFacet is GenericSwapFacet { +contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); } @@ -48,150 +43,91 @@ contract TestGenericSwapFacet is GenericSwapFacet { } } -contract GenericSwapFacetV4Test is DSTest, DiamondTest, TestHelpers { +contract GenericSwapFacetV4Test is TestHelpers { using SafeTransferLib for ERC20; - event LiFiGenericSwapCompleted( - bytes32 indexed transactionId, - string integrator, - string referrer, - address receiver, - address fromAssetId, - address toAssetId, - uint256 fromAmount, - uint256 toAmount - ); - // These values are for Mainnet - address internal constant USDC_ADDRESS = - 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; - address internal constant USDT_ADDRESS = - 0xdAC17F958D2ee523a2206206994597C13D831ec7; - address internal constant WETH_ADDRESS = - 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; - address internal constant DAI_ADDRESS = - 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant USDC_HOLDER = 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; address internal constant DAI_HOLDER = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; address internal constant SOME_WALLET = 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; - address internal constant UNISWAP_V2_ROUTER = - 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; - address internal constant FEE_COLLECTOR = - 0xbD6C7B0d2f68c2b7805d88388319cfB6EcB50eA9; - - // ----- - LiFiDiamond internal diamond; - TestGenericSwapFacet internal genericSwapFacet; + TestGenericSwapFacetV3 internal genericSwapFacetV3; TestGenericSwapFacetV4 internal genericSwapFacetV4; - ERC20 internal usdc; - ERC20 internal usdt; - ERC20 internal dai; - ERC20 internal weth; - UniswapV2Router02 internal uniswap; - FeeCollector internal feeCollector; RouteProcessor4 internal routeProcessor; - function fork() internal { - string memory rpcUrl = vm.envString("ETH_NODE_URI_MAINNET"); - uint256 blockNumber = 19834820; - vm.createSelectFork(rpcUrl, blockNumber); - } + uint256 defaultMinAmountOutNativeToERC20 = 2991350294; + uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; + uint256 defaultMinAmountOutERC20ToERC20 = 99868787; function setUp() public { - fork(); + customBlockNumberForForking = 20266387; + initTestBase(); diamond = createDiamond(); - genericSwapFacet = new TestGenericSwapFacet(); - genericSwapFacetV4 = new TestGenericSwapFacetV4(); - usdc = ERC20(USDC_ADDRESS); - usdt = ERC20(USDT_ADDRESS); - dai = ERC20(DAI_ADDRESS); - weth = ERC20(WETH_ADDRESS); - uniswap = UniswapV2Router02(UNISWAP_V2_ROUTER); - feeCollector = FeeCollector(FEE_COLLECTOR); routeProcessor = new RouteProcessor4(address(0), new address[](0)); + genericSwapFacetV3 = new TestGenericSwapFacetV3(); + genericSwapFacetV4 = new TestGenericSwapFacetV4( + address(routeProcessor) + ); - // add genericSwapFacet (v1) to diamond (for gas usage comparison) - bytes4[] memory functionSelectors = new bytes4[](4); - functionSelectors[0] = genericSwapFacet.swapTokensGeneric.selector; - functionSelectors[1] = genericSwapFacet.addDex.selector; - functionSelectors[2] = genericSwapFacet.removeDex.selector; - functionSelectors[3] = genericSwapFacet - .setFunctionApprovalBySignature - .selector; - addFacet(diamond, address(genericSwapFacet), functionSelectors); - - // add genericSwapFacet (v3) to diamond - bytes4[] memory functionSelectorsV3 = new bytes4[](6); - functionSelectorsV3[0] = genericSwapFacetV4 + // add genericSwapFacet (v3) to diamond (for gas usage comparison) + bytes4[] memory functionSelectors = new bytes4[](9); + functionSelectors[0] = genericSwapFacetV4 .swapTokensSingleV3ERC20ToERC20 .selector; - functionSelectorsV3[1] = genericSwapFacetV4 + functionSelectors[1] = genericSwapFacetV4 .swapTokensSingleV3ERC20ToNative .selector; - functionSelectorsV3[2] = genericSwapFacetV4 + functionSelectors[2] = genericSwapFacetV4 .swapTokensSingleV3NativeToERC20 .selector; - functionSelectorsV3[3] = genericSwapFacetV4 + functionSelectors[3] = genericSwapFacetV4 .swapTokensMultipleV3ERC20ToERC20 .selector; - functionSelectorsV3[4] = genericSwapFacetV4 + functionSelectors[4] = genericSwapFacetV4 .swapTokensMultipleV3ERC20ToNative .selector; - functionSelectorsV3[5] = genericSwapFacetV4 + functionSelectors[5] = genericSwapFacetV4 .swapTokensMultipleV3NativeToERC20 .selector; + functionSelectors[6] = genericSwapFacetV4.addDex.selector; + functionSelectors[7] = genericSwapFacetV4.removeDex.selector; + functionSelectors[8] = genericSwapFacetV4 + .setFunctionApprovalBySignature + .selector; - addFacet(diamond, address(genericSwapFacetV4), functionSelectorsV3); - - genericSwapFacet = TestGenericSwapFacet(address(diamond)); - genericSwapFacetV4 = TestGenericSwapFacetV4(address(diamond)); + // add v3 to diamond + // v4 will be standalone, so we dont add it here + addFacet(diamond, address(genericSwapFacetV3), functionSelectors); + genericSwapFacetV3 = TestGenericSwapFacetV3(address(diamond)); - // whitelist uniswap dex with function selectors - // v1 - genericSwapFacet.addDex(address(uniswap)); - genericSwapFacet.setFunctionApprovalBySignature( - uniswap.swapExactTokensForTokens.selector - ); - genericSwapFacet.setFunctionApprovalBySignature( - uniswap.swapTokensForExactETH.selector - ); - genericSwapFacet.setFunctionApprovalBySignature( - uniswap.swapExactTokensForETH.selector - ); - genericSwapFacet.setFunctionApprovalBySignature( - uniswap.swapExactETHForTokens.selector - ); + // whitelist dexAggregator dex with function selectors // v3 - genericSwapFacetV4.addDex(address(uniswap)); - genericSwapFacetV4.setFunctionApprovalBySignature( - uniswap.swapExactTokensForTokens.selector - ); - genericSwapFacetV4.setFunctionApprovalBySignature( - uniswap.swapTokensForExactETH.selector - ); - genericSwapFacetV4.setFunctionApprovalBySignature( - uniswap.swapExactTokensForETH.selector + genericSwapFacetV3.addDex(address(routeProcessor)); + genericSwapFacetV3.setFunctionApprovalBySignature( + routeProcessor.processRoute.selector ); + + // v4 + genericSwapFacetV4.addDex(address(routeProcessor)); genericSwapFacetV4.setFunctionApprovalBySignature( - uniswap.swapExactETHForTokens.selector + routeProcessor.processRoute.selector ); // whitelist feeCollector with function selectors - // v1 - genericSwapFacet.addDex(FEE_COLLECTOR); - genericSwapFacet.setFunctionApprovalBySignature( + // v3 + genericSwapFacetV3.addDex(address(feeCollector)); + genericSwapFacetV3.setFunctionApprovalBySignature( feeCollector.collectTokenFees.selector ); - genericSwapFacet.setFunctionApprovalBySignature( + genericSwapFacetV3.setFunctionApprovalBySignature( feeCollector.collectNativeFees.selector ); - // v3 - genericSwapFacetV4.addDex(FEE_COLLECTOR); + // v4 + genericSwapFacetV4.addDex(address(feeCollector)); genericSwapFacetV4.setFunctionApprovalBySignature( feeCollector.collectTokenFees.selector ); @@ -199,2027 +135,320 @@ contract GenericSwapFacetV4Test is DSTest, DiamondTest, TestHelpers { feeCollector.collectNativeFees.selector ); - vm.label(address(genericSwapFacet), "LiFiDiamond"); - vm.label(WETH_ADDRESS, "WETH_TOKEN"); - vm.label(DAI_ADDRESS, "DAI_TOKEN"); - vm.label(USDC_ADDRESS, "USDC_TOKEN"); - vm.label(UNISWAP_V2_ROUTER, "UNISWAP_V2_ROUTER"); - } - - // SINGLE SWAP ERC20 >> ERC20 - function _produceSwapDataERC20ToERC20( - address facetAddress - ) - private - returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) - { - // Swap USDC to DAI - address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; - - uint256 amountIn = 100 * 10 ** usdc.decimals(); - - // Calculate minimum input amount - uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); - minAmountOut = amounts[0]; - - // prepare swapData - swapData = new LibSwap.SwapData[](1); - swapData[0] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - USDC_ADDRESS, - DAI_ADDRESS, - amountIn, - abi.encodeWithSelector( - uniswap.swapExactTokensForTokens.selector, - amountIn, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - true - ); - - vm.startPrank(USDC_HOLDER); - usdc.approve(facetAddress, amountIn); - vm.stopPrank(); + vm.label(address(genericSwapFacetV3), "GenericSwapV3 via Diamond"); + vm.label(address(genericSwapFacetV4), "GenericSwapV4"); + vm.label(address(routeProcessor), "RouteProcessor"); + vm.label(ADDRESS_WETH, "WETH_TOKEN"); + vm.label(ADDRESS_DAI, "DAI_TOKEN"); + vm.label(ADDRESS_USDC, "USDC_TOKEN"); + vm.label(ADDRESS_USDT, "USDT_TOKEN"); + vm.label(ADDRESS_UNISWAP, "ADDRESS_UNISWAP"); } - function test_CanSwapSingleERC20ToERC20_V1() public { - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); - - vm.startPrank(USDC_HOLDER); - // expected exact amountOut based on the liquidity available in the specified block for this test case - uint256 expAmountOut = 99491781613896927553; + // SINGLE NATIVE TO ERC20 (ETH > USDC) + function test_CanExecuteSingleSwapNativeToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { uint256 gasLeftBef = gasleft(); - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, - swapData[0].fromAmount, // fromAmount, - expAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); + (bool success, ) = address(genericSwapFacetV3).call{ + value: defaultNativeAmount + }(_getGenericSwapCallDataSingle(true, SwapCase.NativeToERC20)); + if (!success) revert(); uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V1", gasUsed); - - // bytes memory callData = abi.encodeWithSelector( - // genericSwapFacet.swapTokensGeneric.selector, - // "", - // "integrator", - // "referrer", - // payable(SOME_WALLET), - // minAmountOut, - // swapData - // ); - - // console.log("Calldata V1:"); - // console.logBytes(callData); - - // vm.stopPrank(); + console.log("gas used: V3", gasUsed); } - function test_CanSwapSingleERC20ToERC20_V2() public { - // get swapData for USDC > DAI swap - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); - - // pre-register max approval between diamond and dex to get realistic gas usage - vm.startPrank(address(genericSwapFacet)); - usdc.approve(swapData[0].approveTo, type(uint256).max); - vm.stopPrank(); - - vm.startPrank(USDC_HOLDER); - - // expected exact amountOut based on the liquidity available in the specified block for this test case - uint256 expAmountOut = 99491781613896927553; - + function test_CanExecuteSingleSwapNativeToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { uint256 gasLeftBef = gasleft(); - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, - swapData[0].fromAmount, // fromAmount, - expAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); + (bool success, ) = address(genericSwapFacetV4).call{ + value: defaultNativeAmount + }(_getGenericSwapCallDataSingle(false, SwapCase.NativeToERC20)); + if (!success) revert(); uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V2", gasUsed); - - // bytes memory callData = abi.encodeWithSelector( - // genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20.selector, - // "", - // "integrator", - // "referrer", - // payable(SOME_WALLET), - // minAmountOut, - // swapData[0] - // ); - - // console.log("Calldata V2:"); - // console.logBytes(callData); - vm.stopPrank(); + console.log("gas used: V4", gasUsed); } - function test_WillRevertIfSlippageIsTooHighSingleERC20ToERC20() public { - // get swapData for USDC > DAI swap - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); - vm.startPrank(USDC_HOLDER); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - DAI_ADDRESS, - minAmountOut - 1, - 0 - ); - - // update SwapData - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - vm.expectRevert( - abi.encodeWithSelector( - CumulativeSlippageTooHigh.selector, - minAmountOut, - minAmountOut - 1 - ) - ); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - - vm.stopPrank(); - } + // SINGLE ERC20 TO Native (USDC > ETH) - function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsSingleERC20() + function test_CanExecuteSingleSwapERC20ToNative_V3() public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(32610177968847511) + ) { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacetV4)); - - vm.startPrank(USDC_HOLDER); - - // update approveTo address in swapData - swapData[0].approveTo = SOME_WALLET; - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - } - - function test_CanSwapSingleERC20ToERC20WithNonZeroAllowance() public { - // get swapData for USDC > DAI swap - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); - - // expected exact amountOut based on the liquidity available in the specified block for this test case - uint256 expAmountOut = 99491781613896927553; - - // pre-register max approval between diamond and dex to get realistic gas usage - vm.startPrank(address(genericSwapFacet)); - usdc.approve(swapData[0].approveTo, 1); - vm.stopPrank(); - - vm.startPrank(USDC_HOLDER); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, - swapData[0].fromAmount, // fromAmount, - expAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - - vm.stopPrank(); - } + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); - function test_CanSwapSingleERC20ToERC20WithZeroAllowance() public { - // get swapData for USDC > DAI swap - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToERC20(address(genericSwapFacet)); - - // expected exact amountOut based on the liquidity available in the specified block for this test case - uint256 expAmountOut = 99491781613896927553; - - // pre-register max approval between diamond and dex to get realistic gas usage - vm.startPrank(address(genericSwapFacet)); - usdc.approve(swapData[0].approveTo, 0); - vm.stopPrank(); - - vm.startPrank(USDC_HOLDER); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - DAI_ADDRESS, // toAssetId, - swapData[0].fromAmount, // fromAmount, - expAmountOut // toAmount (with liquidity in that selected block) - ); + uint256 gasLeftBef = gasleft(); - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToNative) ); + if (!success) revert(); - vm.stopPrank(); + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); } - // SINGLE SWAP ERC20 >> Native - function _produceSwapDataERC20ToNative( - address facetAddress - ) - private - returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) - { - // Swap USDC to Native ETH - address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = WETH_ADDRESS; - - minAmountOut = 2 ether; - - // Calculate minimum input amount - uint256[] memory amounts = uniswap.getAmountsIn(minAmountOut, path); - uint256 amountIn = amounts[0]; - - // prepare swapData - swapData = new LibSwap.SwapData[](1); - swapData[0] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - USDC_ADDRESS, + function test_CanExecuteSingleSwapERC20ToNative_V4() + public + assertBalanceChange( address(0), - amountIn, - abi.encodeWithSelector( - uniswap.swapTokensForExactETH.selector, - minAmountOut, - amountIn, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - true - ); - - vm.startPrank(USDC_HOLDER); - usdc.approve(facetAddress, amountIn); + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToNative) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator + vm.startPrank(address(genericSwapFacetV4)); + usdc.approve(address(routeProcessor), type(uint256).max); vm.stopPrank(); - } - - function test_CanSwapSingleERC20ToNative_V1() public { - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); - vm.startPrank(USDC_HOLDER); + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV4), defaultUSDCAmount); uint256 gasLeftBef = gasleft(); - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - address(0), // toAssetId, - swapData[0].fromAmount, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData + (bool success, ) = address(genericSwapFacetV4).call( + _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToNative) ); + if (!success) revert(); uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - - vm.stopPrank(); + console.log("gas used: V4", gasUsed); } - function test_CanSwapSingleERC20ToNative_V2() public { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); - - // pre-register max approval between diamond and dex to get realistic gas usage - vm.startPrank(address(genericSwapFacet)); - usdc.approve(swapData[0].approveTo, type(uint256).max); - vm.stopPrank(); + // SINGLE ERC20 TO ERC20 (USDC > USDT) - vm.startPrank(USDC_HOLDER); + function test_CanExecuteSingleSwapERC20ToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); uint256 gasLeftBef = gasleft(); - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - address(0), // toAssetId, - swapData[0].fromAmount, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) + bytes memory callData = _getGenericSwapCallDataSingle( + true, + SwapCase.ERC20ToERC20 ); - genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToERC20) ); + if (!success) revert(); uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - - vm.stopPrank(); - } - - function test_WillRevertIfSlippageIsTooHighSingleERC20ToNative() public { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); - - vm.startPrank(USDC_HOLDER); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - minAmountOut - 1, - 0 - ); - - // update SwapData - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - vm.expectRevert( - abi.encodeWithSelector( - CumulativeSlippageTooHigh.selector, - minAmountOut, - minAmountOut - 1 - ) - ); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - - vm.stopPrank(); - } - - function test_ERC20SwapWillRevertIfSwapFails() public { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); - - vm.startPrank(USDC_HOLDER); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - 0, - 0 - ); - - // update SwapData - bytes memory revertReason = abi.encodePacked("Just because"); - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - swapData[0].callData = abi.encodeWithSelector( - mockDEX.mockSwapWillRevertWithReason.selector, - revertReason - ); - - vm.expectRevert(revertReason); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - - vm.stopPrank(); - } - - function test_WillRevertIfDEXIsNotWhitelistedSingleERC20() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacetV4)); - - vm.startPrank(USDC_HOLDER); - - // remove dex from whitelist - genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); + console.log("gas used: V3", gasUsed); } - function test_SingleERC20ToNativeWillRevertIfNativeAssetTransferFails() + function test_CanExecuteSingleSwapERC20ToERC20_V4() public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataERC20ToNative(address(genericSwapFacet)); - - vm.startPrank(USDC_HOLDER); - - // deploy a contract that cannot receive ETH - NonETHReceiver nonETHReceiver = new NonETHReceiver(); - - vm.expectRevert(NativeAssetTransferFailed.selector); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(address(nonETHReceiver)), // use nonETHReceiver for testing - minAmountOut, - swapData[0] - ); - + // ensure that max approval exists from GenericSwapFacet to DEX aggregator + vm.startPrank(address(genericSwapFacetV4)); + usdc.approve(address(routeProcessor), type(uint256).max); vm.stopPrank(); - } - - // SINGLE SWAP NATIVE >> ERC20 - function _produceSwapDataNativeToERC20() - private - view - returns (LibSwap.SwapData[] memory swapData, uint256 minAmountOut) - { - // Swap native to USDC - address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; - - uint256 amountIn = 2 ether; - - // Calculate minimum input amount - uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); - minAmountOut = amounts[1]; - - // prepare swapData - swapData = new LibSwap.SwapData[](1); - swapData[0] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - address(0), - USDC_ADDRESS, - amountIn, - abi.encodeWithSelector( - uniswap.swapExactETHForTokens.selector, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - true - ); - } - - function test_CanSwapSingleNativeToERC20_V1() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataNativeToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, - swapData[0].fromAmount, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - genericSwapFacet.swapTokensGeneric{ value: swapData[0].fromAmount }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: ", gasUsed); - } - - function test_CanSwapSingleNativeToERC20_V2() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataNativeToERC20(); + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV4), defaultUSDCAmount); uint256 gasLeftBef = gasleft(); - genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ - value: swapData[0].fromAmount - }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] + (bool success, ) = address(genericSwapFacetV4).call( + _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToERC20) ); + if (!success) revert(); uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - } - - function test_WillRevertIfDEXIsNotWhitelistedSingleNative() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataNativeToERC20(); - - // remove dex from whitelist - genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ - value: swapData[0].fromAmount - }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - } - - function test_NativeSwapWillRevertIfSwapFails() public { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataNativeToERC20(); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - 0, - 0 - ); - - // update SwapData - bytes memory revertReason = abi.encodePacked("Some reason"); - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - swapData[0].callData = abi.encodeWithSelector( - mockDEX.mockSwapWillRevertWithReason.selector, - revertReason - ); - - vm.expectRevert(revertReason); - - genericSwapFacetV4.swapTokensSingleV3NativeToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] - ); - } - - function test_WillRevertIfSlippageIsTooHighSingleNativeToERC20() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 minAmountOut - ) = _produceSwapDataNativeToERC20(); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - USDC_ADDRESS, - minAmountOut - 1, - 0 - ); - - // update SwapData - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - vm.expectRevert( - abi.encodeWithSelector( - CumulativeSlippageTooHigh.selector, - minAmountOut, - minAmountOut - 1 - ) - ); + console.log("gas used: V4", gasUsed); + } + + // ------ HELPER FUNCTIONS + + enum SwapCase { + NativeToERC20, + ERC20ToERC20, + ERC20ToNative + } + + function _getValidDexAggregatorCalldata( + bool isV3, + SwapCase swapCase + ) internal view returns (bytes memory callData) { + if (swapCase == SwapCase.NativeToERC20) { + if (isV3) + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d8000000000000000000000000020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db041422600020C24B58c803c6e487a41D3Fd87788ef0bBdB2a0009c400000000000000000000000000000000"; + else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d80000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db0414226000000000000000000000000000000000abC6543210009c400000000000000000000000000000000"; + } + } + if (swapCase == SwapCase.ERC20ToERC20) { + if (isV3) + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005ec3e74000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f01020C24B58c803c6e487a41D3Fd87788ef0bBdB2a000bb8000000000000000000000000000000000000000000000000000000"; + else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005edbbbb0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f010000000000000000000000000000000abC654321000bb8000000000000000000000000000000000000000000000000000000"; + } + } + if (swapCase == SwapCase.ERC20ToNative) { + if (isV3) { + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000000000000000000000000000000073467d7b86a48a000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff006E1fbeeABA87BAe1100d95f8340dc27aD7C8427b01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff0200020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000"; + } else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000007378cf172f087a0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff00B4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff02000000000000000000000000000000000abC65432100000000000000000000000000"; + } + } + + // should not reach this code + revert(hex"dead"); + } + + function _getValidSingleSwapDataViaDexAggregator( + bool isV3, + SwapCase swapCase + ) internal view returns (LibSwap.SwapData memory swapData) { + ( + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount + ) = _getSwapDataParameters(swapCase); + + swapData = LibSwap.SwapData( + address(routeProcessor), + address(routeProcessor), + sendingAssetId, + receivingAssetId, + inputAmount, + _getValidDexAggregatorCalldata(isV3, swapCase), + swapCase == SwapCase.NativeToERC20 ? false : true + ); + } + + function _getValidMultiSwapData( + bool isV3, + SwapCase swapCase, + bool fromNative + ) internal view returns (LibSwap.SwapData[] memory swapData) { + ( + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount + ) = _getSwapDataParameters(swapCase); - genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: 2 ether }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData[0] + swapData = new LibSwap.SwapData[](2); + swapData[0] = _getFeeCollectorSwapData(fromNative); + swapData[1] = LibSwap.SwapData( + address(routeProcessor), + address(routeProcessor), + sendingAssetId, + receivingAssetId, + inputAmount, + _getValidDexAggregatorCalldata(isV3, swapCase), + swapCase == SwapCase.NativeToERC20 ? false : true ); } - // MULTISWAP FROM ERC20 TO ERC20 - - function _produceSwapDataMultiswapFromERC20TOERC20( - address facetAddress + function _getSwapDataParameters( + SwapCase swapCase ) - private + internal + view returns ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount ) { - // Swap1: USDC to DAI - address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; - - amountIn = 10 * 10 ** usdc.decimals(); - - // Calculate expected DAI amount to be received - uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); - uint256 swappedAmountDAI = amounts[0]; - - // prepare swapData - swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - USDC_ADDRESS, - DAI_ADDRESS, - amountIn, + sendingAssetId = swapCase == SwapCase.NativeToERC20 + ? address(0) + : ADDRESS_USDC; + receivingAssetId = swapCase == SwapCase.ERC20ToNative + ? address(0) + : swapCase == SwapCase.ERC20ToERC20 + ? ADDRESS_USDT + : ADDRESS_USDC; + + inputAmount = swapCase == SwapCase.NativeToERC20 + ? defaultNativeAmount + : defaultUSDCAmount; + } + + function _getGenericSwapCallDataSingle( + bool isV3, + SwapCase swapCase + ) internal view returns (bytes memory callData) { + bytes4 selector = swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20.selector + : swapCase == SwapCase.ERC20ToNative + ? genericSwapFacetV4.swapTokensSingleV3ERC20ToNative.selector + : genericSwapFacetV4.swapTokensSingleV3NativeToERC20.selector; + + uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 + ? defaultMinAmountOutERC20ToERC20 + : swapCase == SwapCase.ERC20ToNative + ? defaultMinAmountOutERC20ToNative + : defaultMinAmountOutNativeToERC20; + + callData = _attachTransactionIdToCallData( abi.encodeWithSelector( - uniswap.swapExactTokensForTokens.selector, - amountIn, - swappedAmountDAI, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - true - ); - - // Swap2: DAI to WETH - path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = WETH_ADDRESS; - - // Calculate required DAI input amount - amounts = uniswap.getAmountsOut(swappedAmountDAI, path); - minAmountOut = amounts[1]; - - swapData[1] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - DAI_ADDRESS, - WETH_ADDRESS, - swappedAmountDAI, - abi.encodeWithSelector( - uniswap.swapExactTokensForTokens.selector, - swappedAmountDAI, + selector, + "", + "", + "", + payable(USER_RECEIVER), minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - false - ); - - vm.startPrank(USDC_HOLDER); - usdc.approve(facetAddress, 10 * 10 ** usdc.decimals()); - } - - function test_CanSwapMultipleFromERC20_V1() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - WETH_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData + _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) + ) ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - - vm.stopPrank(); } - function test_CanSwapMultipleFromERC20_V2() public { - // ACTIVATE THIS CODE TO TEST GAS USAGE EXCL. MAX APPROVAL - vm.startPrank(address(genericSwapFacet)); - dai.approve(address(uniswap), type(uint256).max); - vm.stopPrank(); - - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - USDC_ADDRESS, // fromAssetId, - WETH_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); + function _attachTransactionIdToCallData( + bytes memory callData + ) internal pure returns (bytes memory adjustedCallData) { + bytes memory delimiter = hex"deadbeef"; + bytes memory transactionID = hex"513ae98e50764707a4a573b35df47051"; - // bytes memory callData = abi.encodeWithSelector( - // genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20.selector, - // "", - // "integrator", - // "referrer", - // payable(SOME_WALLET), - // minAmountOut, - // swapData - // ); + bytes memory mergedAppendix = mergeBytes(delimiter, transactionID); - // console.log("Calldata V2:"); - // console.logBytes(callData); - - vm.stopPrank(); - } - - function test_MultiSwapERC20WillRevertIfSwapFails() public { - // get swapData USDC > ETH (native) - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacet) - ); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - 0, - 0 - ); - - // update SwapData - bytes memory revertReason = abi.encodePacked("Some reason"); - swapData[1].callTo = swapData[1].approveTo = address(mockDEX); - - swapData[1].callData = abi.encodeWithSelector( - mockDEX.mockSwapWillRevertWithReason.selector, - revertReason - ); - - vm.expectRevert(revertReason); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - - vm.stopPrank(); - } - - function test_WillRevertIfDEXIsNotWhitelistedMulti() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - // remove dex from whitelist - genericSwapFacetV4.removeDex(UNISWAP_V2_ROUTER); - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - } - - function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsMulti() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - // update approveTo address in swapData - swapData[1].callTo = SOME_WALLET; - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - } - - function test_WillRevertIfSlippageIsTooHighMultiToERC20() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - WETH_ADDRESS, - minAmountOut - 1, - 0 - ); - - // update SwapData - swapData[1].callTo = swapData[1].approveTo = address(mockDEX); - - vm.expectRevert( - abi.encodeWithSelector( - CumulativeSlippageTooHigh.selector, - minAmountOut, - minAmountOut - 1 - ) - ); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - - vm.stopPrank(); - } - - // MULTISWAP FROM NATIVE TO ERC20 - - function _produceSwapDataMultiswapFromNativeToERC20() - private - view - returns ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) - { - // Swap1: Native to DAI - address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = DAI_ADDRESS; - - amountIn = 2 ether; - - // Calculate expected DAI amount to be received - uint256[] memory amounts = uniswap.getAmountsOut(amountIn, path); - uint256 swappedAmountDAI = amounts[1]; - - // prepare swapData - swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - address(0), - DAI_ADDRESS, - amountIn, - abi.encodeWithSelector( - uniswap.swapExactETHForTokens.selector, - swappedAmountDAI, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - true - ); - - // Swap2: DAI to USDC - path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = USDC_ADDRESS; - - // Calculate required DAI input amount - amounts = uniswap.getAmountsOut(swappedAmountDAI, path); - minAmountOut = amounts[1]; - - swapData[1] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - DAI_ADDRESS, - USDC_ADDRESS, - swappedAmountDAI, - abi.encodeWithSelector( - uniswap.swapExactTokensForTokens.selector, - swappedAmountDAI, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - false - ); - } - - function test_CanSwapMultipleFromNativeToERC20_V1() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromNativeToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric{ value: amountIn }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - } - - function test_CanSwapMultipleFromNativeToERC20_V2() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromNativeToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ - value: amountIn - }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - } - - function test_MultiSwapNativeWillRevertIfSwapFails() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromNativeToERC20(); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - 0, - 0 - ); - - // update SwapData - bytes memory revertReason = abi.encodePacked("Some reason"); - swapData[0].callTo = swapData[0].approveTo = address(mockDEX); - - swapData[0].callData = abi.encodeWithSelector( - mockDEX.mockSwapWillRevertWithReason.selector, - revertReason - ); - - vm.expectRevert(revertReason); - - genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ - value: amountIn - }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - } - - function test_WillRevertIfDEXIsNotWhitelistedButApproveToIsMultiNative() - public - { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapFromERC20TOERC20( - address(genericSwapFacetV4) - ); - - // update approveTo address in swapData - swapData[0].approveTo = SOME_WALLET; - - vm.expectRevert(ContractCallNotAllowed.selector); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - } - - // MULTISWAP COLLECT ERC20 FEE AND SWAP to ERC20 - - function _produceSwapDataMultiswapERC20FeeAndSwapToERC20() - private - view - returns ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) - { - amountIn = 100 * 10 ** dai.decimals(); - - uint integratorFee = 5 * 10 ** dai.decimals(); - uint lifiFee = 0; - address integratorAddress = address(0xb33f); // some random address - - // Swap1: Collect ERC20 fee (DAI) - // prepare swapData - swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - FEE_COLLECTOR, - FEE_COLLECTOR, - DAI_ADDRESS, - DAI_ADDRESS, - amountIn, - abi.encodeWithSelector( - feeCollector.collectTokenFees.selector, - DAI_ADDRESS, - integratorFee, - lifiFee, - integratorAddress - ), - true - ); - - uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; - - // Swap2: DAI to USDC - address[] memory path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = USDC_ADDRESS; - - // Calculate required DAI input amount - uint256[] memory amounts = uniswap.getAmountsOut( - amountOutFeeCollection, - path - ); - minAmountOut = amounts[1]; - - swapData[1] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - DAI_ADDRESS, - USDC_ADDRESS, - amountOutFeeCollection, - abi.encodeWithSelector( - uniswap.swapExactTokensForTokens.selector, - amountOutFeeCollection, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - false - ); - } - - function test_CanCollectERC20FeesAndSwapToERC20_V1() public { - vm.startPrank(DAI_HOLDER); - dai.approve(address(genericSwapFacet), 100 * 10 ** dai.decimals()); - - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - - vm.stopPrank(); - } - - function test_CanCollectERC20FeesAndSwapToERC20_V2() public { - // ACTIVATE THIS CODE TO TEST GAS USAGE EXCL. MAX APPROVAL - vm.startPrank(address(genericSwapFacet)); - dai.approve(address(uniswap), type(uint256).max); - vm.stopPrank(); - - vm.startPrank(DAI_HOLDER); - dai.approve(address(genericSwapFacet), 100 * 10 ** dai.decimals()); - - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - - vm.stopPrank(); - } - - // MULTISWAP COLLECT NATIVE FEE AND SWAP TO ERC20 - - function _produceSwapDataMultiswapNativeFeeAndSwapToERC20() - private - view - returns ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) - { - amountIn = 1 ether; - - uint integratorFee = 0.1 ether; - uint lifiFee = 0; - address integratorAddress = address(0xb33f); // some random address - - // Swap1: Collect native fee - // prepare swapData - swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - FEE_COLLECTOR, - FEE_COLLECTOR, - address(0), - address(0), - amountIn, - abi.encodeWithSelector( - feeCollector.collectNativeFees.selector, - integratorFee, - lifiFee, - integratorAddress - ), - true - ); - - uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; - - // Swap2: native to USDC - address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; - - // Calculate required DAI input amount - uint256[] memory amounts = uniswap.getAmountsOut( - amountOutFeeCollection, - path - ); - minAmountOut = amounts[1]; - - swapData[1] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - address(0), - USDC_ADDRESS, - amountOutFeeCollection, - abi.encodeWithSelector( - uniswap.swapExactETHForTokens.selector, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - false - ); - } - - function test_CanCollectNativeFeesAndSwap_V1() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapNativeFeeAndSwapToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric{ value: amountIn }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - } - - function test_CanCollectNativeFeesAndSwap_V2() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapNativeFeeAndSwapToERC20(); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - address(0), // fromAssetId, - USDC_ADDRESS, // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensMultipleV3NativeToERC20{ - value: amountIn - }( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - } - - // MULTISWAP COLLECT ERC20 FEE AND SWAP TO NATIVE - - function _produceSwapDataMultiswapERC20FeeAndSwapToNative( - address facetAddress - ) - private - returns ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) - { - amountIn = 100 * 10 ** dai.decimals(); - - uint integratorFee = 5 * 10 ** dai.decimals(); - uint lifiFee = 0; - address integratorAddress = address(0xb33f); // some random address - - // Swap1: Collect ERC20 fee (5 DAI) - // prepare swapData - swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - FEE_COLLECTOR, - FEE_COLLECTOR, - DAI_ADDRESS, - DAI_ADDRESS, - amountIn, - abi.encodeWithSelector( - feeCollector.collectTokenFees.selector, - DAI_ADDRESS, - integratorFee, - lifiFee, - integratorAddress - ), - true - ); - - uint256 amountOutFeeCollection = amountIn - integratorFee - lifiFee; - - // Swap2: DAI to native - address[] memory path = new address[](2); - path[0] = DAI_ADDRESS; - path[1] = WETH_ADDRESS; - - // Calculate required DAI input amount - uint256[] memory amounts = uniswap.getAmountsOut( - amountOutFeeCollection, - path - ); - minAmountOut = amounts[1]; - - swapData[1] = LibSwap.SwapData( - address(uniswap), - address(uniswap), - DAI_ADDRESS, - address(0), - amountOutFeeCollection, - abi.encodeWithSelector( - uniswap.swapExactTokensForETH.selector, - amountOutFeeCollection, - minAmountOut, - path, - address(genericSwapFacet), - block.timestamp + 20 minutes - ), - false - ); - - vm.startPrank(DAI_HOLDER); - dai.approve(facetAddress, amountIn); - } - - function test_CanCollectERC20FeesAndSwapToNative_V1() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( - address(genericSwapFacetV4) - ); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - address(0), // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacet.swapTokensGeneric( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V1: ", gasUsed); - } - - function test_CanCollectERC20FeesAndSwapToNative_V2() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( - address(genericSwapFacetV4) - ); - - uint256 gasLeftBef = gasleft(); - - vm.expectEmit(true, true, true, true, address(diamond)); - emit LiFiGenericSwapCompleted( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator, - "referrer", // referrer, - SOME_WALLET, // receiver, - DAI_ADDRESS, // fromAssetId, - address(0), // toAssetId, - amountIn, // fromAmount, - minAmountOut // toAmount (with liquidity in that selected block) - ); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), - minAmountOut, - swapData - ); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used V2: ", gasUsed); - } - - function test_WillRevertIfSlippageIsTooHighMultiToNative() public { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - , - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( - address(genericSwapFacetV4) - ); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - address(0), - minAmountOut - 1, - 0 - ); - - // update SwapData - swapData[1].callTo = swapData[1].approveTo = address(mockDEX); - - vm.expectRevert( - abi.encodeWithSelector( - CumulativeSlippageTooHigh.selector, - minAmountOut, - minAmountOut - 1 - ) - ); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(SOME_WALLET), // receiver - minAmountOut, - swapData - ); - - vm.stopPrank(); - } - - function test_MultiSwapCollectERC20FeesAndSwapToNativeWillRevertIfNativeAssetTransferFails() - public - { - // get swapData - ( - LibSwap.SwapData[] memory swapData, - uint256 amountIn, - uint256 minAmountOut - ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( - address(genericSwapFacetV4) - ); - - // deploy a contract that cannot receive ETH - NonETHReceiver nonETHReceiver = new NonETHReceiver(); - - vm.expectRevert(NativeAssetTransferFailed.selector); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative( - "", - "integrator", - "referrer", - payable(address(nonETHReceiver)), - minAmountOut, - swapData - ); - } - - // Test functionality that refunds unused input tokens by DEXs - function test_leavesNoERC20SendingAssetDustSingleSwap() public { - vm.startPrank(USDC_HOLDER); - uint256 initialBalance = usdc.balanceOf(USDC_HOLDER); - - uint256 amountIn = 100 * 10 ** usdc.decimals(); - uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage - uint256 expAmountOut = 100 * 10 ** dai.decimals(); - - // deploy mockDEX to simulate positive slippage - MockUniswapDEX mockDex = new MockUniswapDEX(); - - // prepare swapData using MockDEX - address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; - - LibSwap.SwapData memory swapData = LibSwap.SwapData( - address(mockDex), - address(mockDex), - USDC_ADDRESS, - DAI_ADDRESS, - amountIn, - abi.encodeWithSelector( - mockDex.swapTokensForExactTokens.selector, - expAmountOut, - amountIn, - path, - address(genericSwapFacet), // receiver - block.timestamp + 20 minutes - ), - true - ); - - // fund DEX and set swap outcome - deal(path[1], address(mockDex), expAmountOut); - mockDex.setSwapOutput( - amountInActual, // will only pull 99% of the amountIn that we usually expect to be pulled - ERC20(path[1]), - expAmountOut - ); - - // whitelist DEX & function selector - genericSwapFacet.addDex(address(mockDex)); - genericSwapFacet.setFunctionApprovalBySignature( - mockDex.swapTokensForExactTokens.selector - ); - - usdc.approve(address(genericSwapFacet), amountIn); - - genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator - "referrer", // referrer - payable(USDC_HOLDER), // receiver - expAmountOut, - swapData - ); - - assertEq(usdc.balanceOf(address(genericSwapFacet)), 0); - assertEq(usdc.balanceOf(USDC_HOLDER), initialBalance - amountInActual); - - vm.stopPrank(); - } - - function test_leavesNoERC20SendingAssetDustMultiSwap() public { - vm.startPrank(USDC_HOLDER); - uint256 initialBalance = usdc.balanceOf(USDC_HOLDER); - uint256 initialBalanceFeeCollector = usdc.balanceOf(FEE_COLLECTOR); - uint256 initialBalanceDAI = dai.balanceOf(USDC_HOLDER); - - uint256 amountIn = 100 * 10 ** usdc.decimals(); - uint256 expAmountOut = 95 * 10 ** dai.decimals(); - - // prepare swapData - // Swap1: Collect ERC20 fee (5 USDC) - uint integratorFee = 5 * 10 ** usdc.decimals(); - address integratorAddress = address(0xb33f); // some random address - LibSwap.SwapData[] memory swapData = new LibSwap.SwapData[](2); - swapData[0] = LibSwap.SwapData( - FEE_COLLECTOR, - FEE_COLLECTOR, - USDC_ADDRESS, - USDC_ADDRESS, - amountIn, - abi.encodeWithSelector( - feeCollector.collectTokenFees.selector, - USDC_ADDRESS, - integratorFee, - 0, //lifiFee - integratorAddress - ), - true - ); - - uint256 amountOutFeeCollection = amountIn - integratorFee; - - // deploy, fund and whitelist a MockDEX - uint256 amountInActual = (amountOutFeeCollection * 99) / 100; // 1% positive slippage - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - DAI_ADDRESS, - expAmountOut, - amountInActual - ); - - // Swap2: Swap 95 USDC to DAI - address[] memory path = new address[](2); - path[0] = USDC_ADDRESS; - path[1] = DAI_ADDRESS; - - swapData[1] = LibSwap.SwapData( - address(mockDEX), - address(mockDEX), - USDC_ADDRESS, - DAI_ADDRESS, - amountOutFeeCollection, - abi.encodeWithSelector( - mockDEX.swapTokensForExactTokens.selector, - expAmountOut, - amountOutFeeCollection, - path, - address(genericSwapFacet), // receiver - block.timestamp + 20 minutes - ), - false - ); - - usdc.approve(address(genericSwapFacet), amountIn); - - genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator - "referrer", // referrer - payable(USDC_HOLDER), // receiver - expAmountOut, - swapData - ); - - assertEq(usdc.balanceOf(address(genericSwapFacet)), 0); - assertEq( - usdc.balanceOf(FEE_COLLECTOR), - initialBalanceFeeCollector + integratorFee - ); - assertEq( - usdc.balanceOf(USDC_HOLDER), - initialBalance - amountInActual - integratorFee - ); - assertEq(dai.balanceOf(USDC_HOLDER), initialBalanceDAI + expAmountOut); - - vm.stopPrank(); - } - - function test_leavesNoNativeSendingAssetDustSingleSwap() public { - uint256 initialBalanceETH = address(SOME_WALLET).balance; - uint256 initialBalanceUSDC = usdc.balanceOf(address(SOME_WALLET)); - - uint256 amountIn = 1 ether; - uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage - uint256 expAmountOut = 100 * 10 ** usdc.decimals(); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - USDC_ADDRESS, - expAmountOut, - amountInActual - ); - - // prepare swapData using MockDEX - address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; - - LibSwap.SwapData memory swapData = LibSwap.SwapData( - address(mockDEX), - address(mockDEX), - address(0), - USDC_ADDRESS, - amountIn, - abi.encodeWithSelector( - mockDEX.swapETHForExactTokens.selector, - expAmountOut, - path, - address(genericSwapFacet), // receiver - block.timestamp + 20 minutes - ), - true - ); - - // execute the swap - genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: amountIn }( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator - "referrer", // referrer - payable(SOME_WALLET), // receiver - expAmountOut, - swapData - ); - - // we expect that the receiver has received the unused native tokens... - assertEq( - address(SOME_WALLET).balance, - initialBalanceETH + (amountIn - amountInActual) - ); - //... and that the swap result was received as well - assertEq( - usdc.balanceOf(SOME_WALLET), - initialBalanceUSDC + expAmountOut - ); - } - - function test_ReturnPositiveSlippageNativeWillRevertIfNativeTransferFails() - public - { - uint256 amountIn = 1 ether; - uint256 amountInActual = (amountIn * 99) / 100; // 1% positive slippage - uint256 expAmountOut = 100 * 10 ** usdc.decimals(); - - // deploy, fund and whitelist a MockDEX - MockUniswapDEX mockDEX = deployFundAndWhitelistMockDEX( - address(genericSwapFacetV4), - USDC_ADDRESS, - expAmountOut, - amountInActual - ); - - // prepare swapData using MockDEX - address[] memory path = new address[](2); - path[0] = WETH_ADDRESS; - path[1] = USDC_ADDRESS; - - LibSwap.SwapData memory swapData = LibSwap.SwapData( - address(mockDEX), - address(mockDEX), - address(0), - USDC_ADDRESS, - amountIn, - abi.encodeWithSelector( - mockDEX.swapETHForExactTokens.selector, - expAmountOut, - path, - address(genericSwapFacet), // receiver - block.timestamp + 20 minutes - ), - true - ); - - // deploy a contract that cannot receive ETH - NonETHReceiver nonETHReceiver = new NonETHReceiver(); - - vm.expectRevert(NativeAssetTransferFailed.selector); - - // execute the swap - genericSwapFacetV4.swapTokensSingleV3NativeToERC20{ value: amountIn }( - 0x0000000000000000000000000000000000000000000000000000000000000000, // transactionId, - "integrator", // integrator - "referrer", // referrer - payable(address(nonETHReceiver)), // receiver - expAmountOut, - swapData - ); + adjustedCallData = mergeBytes(callData, mergedAppendix); } } diff --git a/test/solidity/Facets/StargateFacet.t.sol b/test/solidity/Facets/StargateFacet.t.sol index 9251d2bbf..06d7fa6e4 100644 --- a/test/solidity/Facets/StargateFacet.t.sol +++ b/test/solidity/Facets/StargateFacet.t.sol @@ -42,7 +42,6 @@ contract StargateFacetTest is TestBaseFacet { // ----- TestStargateFacet internal stargateFacet; - FeeCollector internal feeCollector; StargateFacet.StargateData internal stargateData; uint256 internal nativeAddToMessageValue; @@ -55,7 +54,6 @@ contract StargateFacetTest is TestBaseFacet { stargateFacet = new TestStargateFacet( IStargateRouter(MAINNET_COMPOSER) ); - feeCollector = new FeeCollector(address(this)); bytes4[] memory functionSelectors = new bytes4[](8); functionSelectors[0] = stargateFacet.initStargate.selector; diff --git a/test/solidity/Facets/StargateFacetV2.t.sol b/test/solidity/Facets/StargateFacetV2.t.sol index ffe72277a..32679a49c 100644 --- a/test/solidity/Facets/StargateFacetV2.t.sol +++ b/test/solidity/Facets/StargateFacetV2.t.sol @@ -51,7 +51,6 @@ contract StargateFacetV2Test is TestBaseFacet { // ----- TestStargateFacetV2 internal stargateFacetV2; - FeeCollector internal feeCollector; StargateFacetV2.StargateData internal stargateData; uint256 internal nativeAddToMessageValue; @@ -62,7 +61,6 @@ contract StargateFacetV2Test is TestBaseFacet { initTestBase(); stargateFacetV2 = new TestStargateFacetV2(TOKEN_MESSAGING); - feeCollector = new FeeCollector(address(this)); defaultUSDCAmount = 100 * 10 ** usdc.decimals(); diff --git a/test/solidity/Periphery/ReceiverStargateV2.t.sol b/test/solidity/Periphery/ReceiverStargateV2.t.sol index b18ff56e6..1c3dda585 100644 --- a/test/solidity/Periphery/ReceiverStargateV2.t.sol +++ b/test/solidity/Periphery/ReceiverStargateV2.t.sol @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Unlicense pragma solidity 0.8.17; -import { Test, TestBase, Vm, LiFiDiamond, DSTest, ILiFi, LibSwap, LibAllowList, console, InvalidAmount, ERC20, UniswapV2Router02 } from "../utils/TestBase.sol"; -import { OnlyContractOwner, UnAuthorized, ExternalCallFailed } from "src/Errors/GenericErrors.sol"; +import { TestHelpers, LiFiDiamond, ILiFi, LibSwap, LibAllowList, console, ERC20, UniswapV2Router02, NonETHReceiver } from "../utils/TestHelpers.sol"; +import { OnlyContractOwner, UnAuthorized, ExternalCallFailed, InvalidAmount } from "src/Errors/GenericErrors.sol"; import { ReceiverStargateV2 } from "lifi/Periphery/ReceiverStargateV2.sol"; import { stdJson } from "forge-std/Script.sol"; @@ -18,7 +18,7 @@ bytes4 constant LZ_COMPOSE_NOT_FOUND_SELECTOR = bytes4( ); bytes32 constant RECEIVED_MESSAGE_HASH = bytes32(uint256(1)); -contract ReceiverStargateV2Test is TestBase { +contract ReceiverStargateV2Test is TestHelpers { using stdJson for string; ReceiverStargateV2 internal receiver; @@ -299,50 +299,6 @@ contract ReceiverStargateV2Test is TestBase { assertTrue(dai.balanceOf(receiverAddress) == amountOutMin); } - - // HELPER FUNCTIONS - function mergeBytes( - bytes memory a, - bytes memory b - ) public pure returns (bytes memory c) { - // Store the length of the first array - uint alen = a.length; - // Store the length of BOTH arrays - uint totallen = alen + b.length; - // Count the loops required for array a (sets of 32 bytes) - uint loopsa = (a.length + 31) / 32; - // Count the loops required for array b (sets of 32 bytes) - uint loopsb = (b.length + 31) / 32; - assembly { - let m := mload(0x40) - // Load the length of both arrays to the head of the new bytes array - mstore(m, totallen) - // Add the contents of a to the array - for { - let i := 0 - } lt(i, loopsa) { - i := add(1, i) - } { - mstore( - add(m, mul(32, add(1, i))), - mload(add(a, mul(32, add(1, i)))) - ) - } - // Add the contents of b to the array - for { - let i := 0 - } lt(i, loopsb) { - i := add(1, i) - } { - mstore( - add(m, add(mul(32, add(1, i)), alen)), - mload(add(b, mul(32, add(1, i)))) - ) - } - mstore(0x40, add(m, add(32, totallen))) - c := m - } - } } interface IMessagingComposer { @@ -363,10 +319,6 @@ interface IMessagingComposer { ) external payable; } -contract NonETHReceiver { - // this contract cannot receive any ETH due to missing receive function -} - contract ReentrantReceiver { bytes internal composeMsg; diff --git a/test/solidity/utils/TestBase.sol b/test/solidity/utils/TestBase.sol index 4b992d891..693fc3b11 100644 --- a/test/solidity/utils/TestBase.sol +++ b/test/solidity/utils/TestBase.sol @@ -5,6 +5,8 @@ import { Test } from "forge-std/Test.sol"; import { DSTest } from "ds-test/test.sol"; import { Vm } from "forge-std/Vm.sol"; import { ILiFi } from "lifi/Interfaces/ILiFi.sol"; +import { FeeCollector } from "lifi/Periphery/FeeCollector.sol"; +import { ILiFi } from "lifi/Interfaces/ILiFi.sol"; import { LibSwap } from "lifi/Libraries/LibSwap.sol"; import { UniswapV2Router02 } from "../utils/Interfaces.sol"; import { DiamondTest, LiFiDiamond } from "../utils/DiamondTest.sol"; @@ -87,14 +89,21 @@ abstract contract TestBase is Test, DiamondTest, ILiFi { bytes32 internal nextUser = keccak256(abi.encodePacked("user address")); UniswapV2Router02 internal uniswap; ERC20 internal usdc; + ERC20 internal usdt; ERC20 internal dai; ERC20 internal weth; LiFiDiamond internal diamond; ILiFi.BridgeData internal bridgeData; LibSwap.SwapData[] internal swapData; + FeeCollector internal feeCollector; uint256 internal defaultDAIAmount; uint256 internal defaultUSDCAmount; uint256 internal defaultNativeAmount; + // amounts for feeCollection + uint256 defaultNativeFeeCollectionAmount = 0.001 ether; + uint256 defaultUSDCFeeCollectionAmount; + uint256 defaultLiFiFeeAmount = 0; + // tokenAddress => userAddress => balance mapping(address => mapping(address => uint256)) internal initialBalances; uint256 internal addToMessageValue; @@ -129,12 +138,14 @@ abstract contract TestBase is Test, DiamondTest, ILiFi { address internal ADDRESS_UNISWAP = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal ADDRESS_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; + address internal ADDRESS_USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address internal ADDRESS_DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal ADDRESS_WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts (Whales: ETH only) address internal constant USER_SENDER = address(0xabc123456); // initially funded with 100,000 DAI, USDC & ETHER address internal constant USER_RECEIVER = address(0xabc654321); address internal constant USER_REFUND = address(0xabcdef281); + address internal constant USER_INTEGRATOR = address(0xdeadbeef); address internal constant USER_DIAMOND_OWNER = 0x5042255A3F3FD7727e419CeA387cAFDfad3C3aF8; address internal constant USER_USDC_WHALE = @@ -184,6 +195,7 @@ abstract contract TestBase is Test, DiamondTest, ILiFi { vm.label(USER_DIAMOND_OWNER, "USER_DIAMOND_OWNER"); vm.label(USER_USDC_WHALE, "USER_USDC_WHALE"); vm.label(USER_DAI_WHALE, "USER_DAI_WHALE"); + vm.label(USER_INTEGRATOR, "USER_INTEGRATOR"); vm.label(ADDRESS_USDC, "ADDRESS_USDC_PROXY"); vm.label( 0xa2327a938Febf5FEC13baCFb16Ae10EcBc4cbDCF, @@ -199,11 +211,13 @@ abstract contract TestBase is Test, DiamondTest, ILiFi { // fill user accounts with starting balance uniswap = UniswapV2Router02(ADDRESS_UNISWAP); usdc = ERC20(ADDRESS_USDC); + usdt = ERC20(ADDRESS_USDT); dai = ERC20(ADDRESS_DAI); weth = ERC20(ADDRESS_WETH); - // deploy & configure diamond + // deploy & configure contracts diamond = createDiamond(); + feeCollector = new FeeCollector(USER_DIAMOND_OWNER); // transfer initial DAI/USDC/WETH balance to USER_SENDER deal(ADDRESS_USDC, USER_SENDER, 100_000 * 10 ** usdc.decimals()); @@ -217,6 +231,8 @@ abstract contract TestBase is Test, DiamondTest, ILiFi { defaultDAIAmount = 100 * 10 ** dai.decimals(); defaultUSDCAmount = 100 * 10 ** usdc.decimals(); defaultNativeAmount = 1 ether; + // amounts for feeCollection + defaultUSDCFeeCollectionAmount = 1 * 10 ** usdc.decimals(); // set path for logfile (esp. interesting for fuzzing tests) logFilePath = "./test/logs/"; diff --git a/test/solidity/utils/TestHelpers.sol b/test/solidity/utils/TestHelpers.sol index 39175fa22..6a6b9ca4c 100644 --- a/test/solidity/utils/TestHelpers.sol +++ b/test/solidity/utils/TestHelpers.sol @@ -1,8 +1,7 @@ // SPDX-License-Identifier: Unlicense pragma solidity =0.8.17; -import { Test } from "forge-std/Test.sol"; -import { ERC20 } from "solmate/tokens/ERC20.sol"; +import { TestBase, ILiFi, LibAllowList, ERC20, DiamondTest, LiFiDiamond, LibSwap, console, UniswapV2Router02 } from "./TestBase.sol"; import { MockUniswapDEX } from "./MockUniswapDEX.sol"; interface DexManager { @@ -12,7 +11,7 @@ interface DexManager { } //common utilities for forge tests -contract TestHelpers is Test { +contract TestHelpers is TestBase { /// @notice will deploy and fund a mock DEX that can simulate the following behaviour for both ERC20/Native: /// positive slippage#1: uses less input tokens as expected /// positive slippage#2: returns more output tokens as expected @@ -77,6 +76,82 @@ contract TestHelpers is Test { mockDex.mockSwapWillRevertWithReason.selector ); } + + /// CALLDATA AND SWAPDATA GENERATION + + function _getFeeCollectorSwapData( + bool fromNative + ) internal view returns (LibSwap.SwapData memory swapData) { + address assetId = fromNative ? address(0) : ADDRESS_USDC; + bytes memory callData = fromNative + ? abi.encodeWithSelector( + feeCollector.collectNativeFees.selector, + defaultNativeFeeCollectionAmount, + 0, + USER_INTEGRATOR + ) + : abi.encodeWithSelector( + feeCollector.collectTokenFees.selector, + ADDRESS_USDC, + defaultUSDCFeeCollectionAmount, + 0, + USER_INTEGRATOR + ); + swapData = LibSwap.SwapData( + address(feeCollector), + address(feeCollector), + assetId, + assetId, + fromNative ? defaultNativeAmount : defaultUSDCAmount, + callData, + fromNative ? false : true + ); + } + + /// VARIOUS HELPER FUNCTIONS + + function mergeBytes( + bytes memory a, + bytes memory b + ) public pure returns (bytes memory c) { + // Store the length of the first array + uint alen = a.length; + // Store the length of BOTH arrays + uint totallen = alen + b.length; + // Count the loops required for array a (sets of 32 bytes) + uint loopsa = (a.length + 31) / 32; + // Count the loops required for array b (sets of 32 bytes) + uint loopsb = (b.length + 31) / 32; + assembly { + let m := mload(0x40) + // Load the length of both arrays to the head of the new bytes array + mstore(m, totallen) + // Add the contents of a to the array + for { + let i := 0 + } lt(i, loopsa) { + i := add(1, i) + } { + mstore( + add(m, mul(32, add(1, i))), + mload(add(a, mul(32, add(1, i)))) + ) + } + // Add the contents of b to the array + for { + let i := 0 + } lt(i, loopsb) { + i := add(1, i) + } { + mstore( + add(m, add(mul(32, add(1, i)), alen)), + mload(add(b, mul(32, add(1, i)))) + ) + } + mstore(0x40, add(m, add(32, totallen))) + c := m + } + } } contract NonETHReceiver { From c15eed0a1e8a888dfa52c346343a03ab1ff9b6a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Tue, 9 Jul 2024 14:38:10 +0700 Subject: [PATCH 04/11] replaced solmate with solady --- src/Facets/GenericSwapFacetV3.sol | 3 - src/Facets/GenericSwapFacetV4.sol | 324 +++++------------- test/solidity/Facets/GenericSwapFacetV4.t.sol | 243 ++++++++++++- test/solidity/utils/TestHelpers.sol | 4 +- 4 files changed, 321 insertions(+), 253 deletions(-) diff --git a/src/Facets/GenericSwapFacetV3.sol b/src/Facets/GenericSwapFacetV3.sol index a228021bf..e0098b68d 100644 --- a/src/Facets/GenericSwapFacetV3.sol +++ b/src/Facets/GenericSwapFacetV3.sol @@ -8,7 +8,6 @@ import { LibAllowList } from "../Libraries/LibAllowList.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol"; import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; -import { console2 } from "forge-std/console2.sol"; /// @title GenericSwapFacetV3 /// @author LI.FI (https://li.fi) @@ -506,7 +505,6 @@ contract GenericSwapFacetV3 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) private { - console2.log("in _transferNativeTokensAndEmitEvent"); uint256 amountReceived = address(this).balance; // make sure minAmountOut was received @@ -517,7 +515,6 @@ contract GenericSwapFacetV3 is ILiFi { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = _receiver.call{ value: amountReceived }(""); if (!success) { - console2.log("HEYA"); revert NativeAssetTransferFailed(); } diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Facets/GenericSwapFacetV4.sol index 023766f61..f83d541d2 100644 --- a/src/Facets/GenericSwapFacetV4.sol +++ b/src/Facets/GenericSwapFacetV4.sol @@ -9,7 +9,7 @@ import { LibAsset } from "../Libraries/LibAsset.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData } from "../Errors/GenericErrors.sol"; //TODO: replace with solady -import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; +import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; //TODO: remove import { console2 } from "forge-std/console2.sol"; @@ -20,7 +20,7 @@ import { console2 } from "forge-std/console2.sol"; /// @dev Can only execute calldata for APPROVED function selectors /// @custom:version 1.0.0 contract GenericSwapFacetV4 is ILiFi { - using SafeTransferLib for ERC20; + using SafeTransferLib for address; /// Storage /// @@ -59,9 +59,9 @@ contract GenericSwapFacetV4 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData calldata _swapData ) external onlyCallsToDexAggregator(_swapData.callTo) { - ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); + address sendingAssetId = _swapData.sendingAssetId; // deposit funds - sendingAsset.safeTransferFrom( + sendingAssetId.safeTransferFrom( msg.sender, address(this), _swapData.fromAmount @@ -81,7 +81,7 @@ contract GenericSwapFacetV4 is ILiFi { if (amountReceived < _minAmountOut) revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - _returnPositiveSlippageERC20(sendingAsset, _receiver); + _returnPositiveSlippageERC20(sendingAssetId, _receiver); } /// @notice Performs a single swap from an ERC20 token to the network's native token @@ -99,10 +99,10 @@ contract GenericSwapFacetV4 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData calldata _swapData ) external onlyCallsToDexAggregator(_swapData.callTo) { - ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); + address sendingAssetId = _swapData.sendingAssetId; // deposit funds - sendingAsset.safeTransferFrom( + sendingAssetId.safeTransferFrom( msg.sender, address(this), _swapData.fromAmount @@ -163,119 +163,106 @@ contract GenericSwapFacetV4 is ILiFi { // MULTIPLE SWAPS /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer + /// @param (*) _transactionId the transaction id associated with the operation + /// @param (*) _integrator the name of the integrator + /// @param (*) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensMultipleV3ERC20ToNative( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, + function swapTokensMultipleV3ERC20ToERC20( + bytes32, + string calldata, + string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) external { - _depositMultipleERC20Tokens(_swapData); - _executeSwaps(_swapData, _transactionId, _receiver); - _transferNativeTokensAndEmitEvent( - _transactionId, - _integrator, - _referrer, - _receiver, - _minAmountOut, - _swapData - ); + //TODO: merge two functions ..MultipleV3ERCTo... + // deposit token of first swap + LibSwap.SwapData calldata currentSwap = _swapData[0]; + + // check if a deposit is required + if (currentSwap.requiresDeposit) { + // we will not check msg.value as tx will fail anyway if not enough value available + // thus we only deposit ERC20 tokens here + currentSwap.sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + currentSwap.fromAmount + ); + } + + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); } - /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with ERC20 - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensMultipleV3ERC20ToERC20( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, + function swapTokensMultipleV3ERC20ToNative( + bytes32, + string calldata, + string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) external { - _depositMultipleERC20Tokens(_swapData); - _executeSwaps(_swapData, _transactionId, _receiver); - _transferERC20TokensAndEmitEvent( - _transactionId, - _integrator, - _referrer, - _receiver, - _minAmountOut, - _swapData - ); + // deposit token of first swap + LibSwap.SwapData calldata currentSwap = _swapData[0]; + + // check if a deposit is required + if (currentSwap.requiresDeposit) { + // we will not check msg.value as tx will fail anyway if not enough value available + // thus we only deposit ERC20 tokens here + currentSwap.sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + currentSwap.fromAmount + ); + } + + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); } /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 - /// @param _transactionId the transaction id associated with the operation - /// @param _integrator the name of the integrator - /// @param _referrer the address of the referrer + /// @param (*) _transactionId the transaction id associated with the operation + /// @param (*) _integrator the name of the integrator + /// @param (*) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensMultipleV3NativeToERC20( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, + bytes32, + string calldata, + string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) external payable { - _executeSwaps(_swapData, _transactionId, _receiver); - _transferERC20TokensAndEmitEvent( - _transactionId, - _integrator, - _referrer, - _receiver, - _minAmountOut, - _swapData - ); + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); } /// Private helper methods /// function _depositMultipleERC20Tokens( LibSwap.SwapData[] calldata _swapData - ) private { - // initialize variables before loop to save gas - uint256 numOfSwaps = _swapData.length; - LibSwap.SwapData calldata currentSwap; - - // go through all swaps and deposit tokens, where required - for (uint256 i = 0; i < numOfSwaps; ) { - currentSwap = _swapData[i]; - if (currentSwap.requiresDeposit) { - // we will not check msg.value as tx will fail anyway if not enough value available - // thus we only deposit ERC20 tokens here - ERC20(currentSwap.sendingAssetId).safeTransferFrom( - msg.sender, - address(this), - currentSwap.fromAmount - ); - } - unchecked { - ++i; - } - } - } + ) private {} function _depositAndSwapERC20Single( LibSwap.SwapData calldata _swapData, address _receiver ) private onlyCallsToDexAggregator(_swapData.callTo) { - ERC20 sendingAsset = ERC20(_swapData.sendingAssetId); + address sendingAssetId = _swapData.sendingAssetId; uint256 fromAmount = _swapData.fromAmount; // deposit funds - sendingAsset.safeTransferFrom(msg.sender, address(this), fromAmount); + sendingAssetId.safeTransferFrom(msg.sender, address(this), fromAmount); // execute swap // solhint-disable-next-line avoid-low-level-calls @@ -286,7 +273,7 @@ contract GenericSwapFacetV4 is ILiFi { LibUtil.revertWith(res); } - _returnPositiveSlippageERC20(sendingAsset, _receiver); + _returnPositiveSlippageERC20(sendingAssetId, _receiver); } // @dev: this function will not work with swapData that has multiple swaps with the same sendingAssetId @@ -295,179 +282,56 @@ contract GenericSwapFacetV4 is ILiFi { // "swapTokensGeneric" function of the original GenericSwapFacet function _executeSwaps( LibSwap.SwapData[] calldata _swapData, - bytes32 _transactionId, address _receiver - ) private { + ) private returns (uint256 finalAmountOut) { // initialize variables before loop to save gas - uint256 numOfSwaps = _swapData.length; - ERC20 sendingAsset; address sendingAssetId; address receivingAssetId; LibSwap.SwapData calldata currentSwap; bool success; bytes memory returnData; - uint256 currentAllowance; // go through all swaps - for (uint256 i = 0; i < numOfSwaps; ) { + for (uint256 i = 0; i < _swapData.length; ) { currentSwap = _swapData[i]; sendingAssetId = currentSwap.sendingAssetId; - sendingAsset = ERC20(currentSwap.sendingAssetId); receivingAssetId = currentSwap.receivingAssetId; - // check if callTo address is whitelisted - if ( - !LibAllowList.contractIsAllowed(currentSwap.callTo) || - !LibAllowList.selectorIsAllowed( - bytes4(currentSwap.callData[:4]) - ) - ) { - revert ContractCallNotAllowed(); + // execute the swap + (success, returnData) = currentSwap.callTo.call{ + value: LibAsset.isNativeAsset(sendingAssetId) + ? currentSwap.fromAmount + : 0 + }(currentSwap.callData); + if (!success) { + LibUtil.revertWith(returnData); } - // if approveTo address is different to callTo, check if it's whitelisted, too - if ( - currentSwap.approveTo != currentSwap.callTo && - !LibAllowList.contractIsAllowed(currentSwap.approveTo) - ) { - revert ContractCallNotAllowed(); + // check if this is the final swap + if (i == _swapData.length - 1) { + finalAmountOut = abi.decode(returnData, (uint256)); } - if (LibAsset.isNativeAsset(sendingAssetId)) { - // Native - // execute the swap - (success, returnData) = currentSwap.callTo.call{ - value: currentSwap.fromAmount - }(currentSwap.callData); - if (!success) { - LibUtil.revertWith(returnData); - } - - // return any potential leftover sendingAsset tokens - // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) - if (sendingAssetId != receivingAssetId) + // return any potential leftover sendingAsset tokens + // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) + if (sendingAssetId != receivingAssetId) + if (LibAsset.isNativeAsset(sendingAssetId)) { + // Native _returnPositiveSlippageNative(_receiver); - } else { - // ERC20 - // check if the current allowance is sufficient - currentAllowance = sendingAsset.allowance( - address(this), - currentSwap.approveTo - ); - if (currentAllowance < currentSwap.fromAmount) { - sendingAsset.safeApprove(currentSwap.approveTo, 0); - sendingAsset.safeApprove( - currentSwap.approveTo, - type(uint256).max - ); - } - - // execute the swap - (success, returnData) = currentSwap.callTo.call( - currentSwap.callData - ); - if (!success) { - LibUtil.revertWith(returnData); + } else { + // ERC20 + _returnPositiveSlippageERC20(sendingAssetId, _receiver); } - // return any potential leftover sendingAsset tokens - // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) - if (sendingAssetId != receivingAssetId) - _returnPositiveSlippageERC20(sendingAsset, _receiver); - } - - // emit AssetSwapped event - // @dev: this event might in some cases emit inaccurate information. e.g. if a token is swapped and this contract already held a balance of the receivingAsset - // then the event will show swapOutputAmount + existingBalance as toAmount. We accept this potential inaccuracy in return for gas savings and may update this - // at a later stage when the described use case becomes more common - emit LibSwap.AssetSwapped( - _transactionId, - currentSwap.callTo, - sendingAssetId, - receivingAssetId, - currentSwap.fromAmount, - LibAsset.isNativeAsset(receivingAssetId) - ? address(this).balance - : ERC20(receivingAssetId).balanceOf(address(this)), - block.timestamp - ); - unchecked { ++i; } } } - function _transferERC20TokensAndEmitEvent( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) private { - // determine the end result of the swap - address finalAssetId = _swapData[_swapData.length - 1] - .receivingAssetId; - uint256 amountReceived = ERC20(finalAssetId).balanceOf(address(this)); - - // make sure minAmountOut was received - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - - // transfer to receiver - ERC20(finalAssetId).safeTransfer(_receiver, amountReceived); - - // emit event - emit ILiFi.LiFiGenericSwapCompleted( - _transactionId, - _integrator, - _referrer, - _receiver, - _swapData[0].sendingAssetId, - finalAssetId, - _swapData[0].fromAmount, - amountReceived - ); - } - - function _transferNativeTokensAndEmitEvent( - bytes32 _transactionId, - string calldata _integrator, - string calldata _referrer, - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) private { - uint256 amountReceived = address(this).balance; - - // make sure minAmountOut was received - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - - // transfer funds to receiver - // solhint-disable-next-line avoid-low-level-calls - (bool success, ) = _receiver.call{ value: amountReceived }(""); - if (!success) { - revert NativeAssetTransferFailed(); - } - - // emit event - emit ILiFi.LiFiGenericSwapCompleted( - _transactionId, - _integrator, - _referrer, - _receiver, - _swapData[0].sendingAssetId, - address(0), - _swapData[0].fromAmount, - amountReceived - ); - } - // returns any unused 'sendingAsset' tokens (=> positive slippage) to the receiver address function _returnPositiveSlippageERC20( - ERC20 sendingAsset, + address sendingAsset, address receiver ) private { // if a balance exists in sendingAsset, it must be positive slippage diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol index ec77594b3..eca5b197a 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -75,27 +75,27 @@ contract GenericSwapFacetV4Test is TestHelpers { // add genericSwapFacet (v3) to diamond (for gas usage comparison) bytes4[] memory functionSelectors = new bytes4[](9); - functionSelectors[0] = genericSwapFacetV4 + functionSelectors[0] = genericSwapFacetV3 .swapTokensSingleV3ERC20ToERC20 .selector; - functionSelectors[1] = genericSwapFacetV4 + functionSelectors[1] = genericSwapFacetV3 .swapTokensSingleV3ERC20ToNative .selector; - functionSelectors[2] = genericSwapFacetV4 + functionSelectors[2] = genericSwapFacetV3 .swapTokensSingleV3NativeToERC20 .selector; - functionSelectors[3] = genericSwapFacetV4 + functionSelectors[3] = genericSwapFacetV3 .swapTokensMultipleV3ERC20ToERC20 .selector; - functionSelectors[4] = genericSwapFacetV4 + functionSelectors[4] = genericSwapFacetV3 .swapTokensMultipleV3ERC20ToNative .selector; - functionSelectors[5] = genericSwapFacetV4 + functionSelectors[5] = genericSwapFacetV3 .swapTokensMultipleV3NativeToERC20 .selector; - functionSelectors[6] = genericSwapFacetV4.addDex.selector; - functionSelectors[7] = genericSwapFacetV4.removeDex.selector; - functionSelectors[8] = genericSwapFacetV4 + functionSelectors[6] = genericSwapFacetV3.addDex.selector; + functionSelectors[7] = genericSwapFacetV3.removeDex.selector; + functionSelectors[8] = genericSwapFacetV3 .setFunctionApprovalBySignature .selector; @@ -251,11 +251,6 @@ contract GenericSwapFacetV4Test is TestHelpers { uint256 gasLeftBef = gasleft(); - bytes memory callData = _getGenericSwapCallDataSingle( - true, - SwapCase.ERC20ToERC20 - ); - (bool success, ) = address(genericSwapFacetV3).call( _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToERC20) ); @@ -292,6 +287,185 @@ contract GenericSwapFacetV4Test is TestHelpers { console.log("gas used: V4", gasUsed); } + // FEE COLLECTION + SWAP NATIVE TO ERC20 (ETH > USDC) + + function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + vm.startPrank(USER_SENDER); + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call{ + value: defaultNativeAmount + defaultNativeFeeCollectionAmount + }( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.NativeToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV4).call{ + value: defaultNativeAmount + defaultNativeFeeCollectionAmount + }( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.NativeToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // FEE COLLECTION + SWAP ERC20 TO Native (USDC > ETH) + + function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V3() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(32610177968847511) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV3), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.ERC20ToNative + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V4() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToNative) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector + vm.startPrank(address(genericSwapFacetV4)); + usdc.approve(address(routeProcessor), type(uint256).max); + usdc.approve(address(feeCollector), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV4), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV4).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.ERC20ToNative + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // FEE COLLECTION + SWAP ERC20 TO ERC20 (USDC > USDT) + + function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV3), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.ERC20ToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector + vm.startPrank(address(genericSwapFacetV4)); + usdc.approve(address(routeProcessor), type(uint256).max); + usdc.approve(address(feeCollector), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV4), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV4).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.ERC20ToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + // ------ HELPER FUNCTIONS enum SwapCase { @@ -303,7 +477,7 @@ contract GenericSwapFacetV4Test is TestHelpers { function _getValidDexAggregatorCalldata( bool isV3, SwapCase swapCase - ) internal view returns (bytes memory callData) { + ) internal pure returns (bytes memory callData) { if (swapCase == SwapCase.NativeToERC20) { if (isV3) // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) @@ -365,8 +539,7 @@ contract GenericSwapFacetV4Test is TestHelpers { function _getValidMultiSwapData( bool isV3, - SwapCase swapCase, - bool fromNative + SwapCase swapCase ) internal view returns (LibSwap.SwapData[] memory swapData) { ( address sendingAssetId, @@ -375,7 +548,10 @@ contract GenericSwapFacetV4Test is TestHelpers { ) = _getSwapDataParameters(swapCase); swapData = new LibSwap.SwapData[](2); - swapData[0] = _getFeeCollectorSwapData(fromNative); + swapData[0] = _getFeeCollectorSwapData( + swapCase == SwapCase.NativeToERC20 ? true : false + ); + swapData[1] = LibSwap.SwapData( address(routeProcessor), address(routeProcessor), @@ -383,7 +559,7 @@ contract GenericSwapFacetV4Test is TestHelpers { receivingAssetId, inputAmount, _getValidDexAggregatorCalldata(isV3, swapCase), - swapCase == SwapCase.NativeToERC20 ? false : true + false ); } @@ -441,6 +617,35 @@ contract GenericSwapFacetV4Test is TestHelpers { ); } + function _getGenericSwapCallDataFeeCollectionPlusSwap( + bool isV3, + SwapCase swapCase + ) internal view returns (bytes memory callData) { + bytes4 selector = swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20.selector + : swapCase == SwapCase.ERC20ToNative + ? genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative.selector + : genericSwapFacetV4.swapTokensMultipleV3NativeToERC20.selector; + + uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 + ? defaultMinAmountOutERC20ToERC20 + : swapCase == SwapCase.ERC20ToNative + ? defaultMinAmountOutERC20ToNative + : defaultMinAmountOutNativeToERC20; + + callData = _attachTransactionIdToCallData( + abi.encodeWithSelector( + selector, + "", + "", + "", + payable(USER_RECEIVER), + minAmountOut, + _getValidMultiSwapData(isV3, swapCase) + ) + ); + } + function _attachTransactionIdToCallData( bytes memory callData ) internal pure returns (bytes memory adjustedCallData) { diff --git a/test/solidity/utils/TestHelpers.sol b/test/solidity/utils/TestHelpers.sol index 6a6b9ca4c..597604ca2 100644 --- a/test/solidity/utils/TestHelpers.sol +++ b/test/solidity/utils/TestHelpers.sol @@ -102,7 +102,9 @@ contract TestHelpers is TestBase { address(feeCollector), assetId, assetId, - fromNative ? defaultNativeAmount : defaultUSDCAmount, + fromNative + ? defaultNativeAmount + defaultNativeFeeCollectionAmount + : defaultUSDCAmount + defaultUSDCFeeCollectionAmount, callData, fromNative ? false : true ); From a98e5c5182c727a7ec3aa2ea9818bb90176dd6b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Tue, 9 Jul 2024 14:46:13 +0700 Subject: [PATCH 05/11] functions merged --- src/Facets/GenericSwapFacetV4.sol | 11 ++++------- test/solidity/Facets/GenericSwapFacetV4.t.sol | 14 +++++++++----- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Facets/GenericSwapFacetV4.sol index f83d541d2..3918d1ada 100644 --- a/src/Facets/GenericSwapFacetV4.sol +++ b/src/Facets/GenericSwapFacetV4.sol @@ -140,13 +140,11 @@ contract GenericSwapFacetV4 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData calldata _swapData ) external payable onlyCallsToDexAggregator(_swapData.callTo) { - address callTo = _swapData.callTo; - // execute swap // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = callTo.call{ value: msg.value }( - _swapData.callData - ); + (bool success, bytes memory res) = _swapData.callTo.call{ + value: msg.value + }(_swapData.callData); if (!success) { LibUtil.revertWith(res); } @@ -169,7 +167,7 @@ contract GenericSwapFacetV4 is ILiFi { /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensMultipleV3ERC20ToERC20( + function swapTokensMultipleV3ERC20ToAny( bytes32, string calldata, string calldata, @@ -177,7 +175,6 @@ contract GenericSwapFacetV4 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) external { - //TODO: merge two functions ..MultipleV3ERCTo... // deposit token of first swap LibSwap.SwapData calldata currentSwap = _swapData[0]; diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol index eca5b197a..c3ffb8979 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -621,11 +621,15 @@ contract GenericSwapFacetV4Test is TestHelpers { bool isV3, SwapCase swapCase ) internal view returns (bytes memory callData) { - bytes4 selector = swapCase == SwapCase.ERC20ToERC20 - ? genericSwapFacetV4.swapTokensMultipleV3ERC20ToERC20.selector - : swapCase == SwapCase.ERC20ToNative - ? genericSwapFacetV4.swapTokensMultipleV3ERC20ToNative.selector - : genericSwapFacetV4.swapTokensMultipleV3NativeToERC20.selector; + bytes4 selector = isV3 + ? swapCase == SwapCase.NativeToERC20 + ? genericSwapFacetV3.swapTokensMultipleV3NativeToERC20.selector + : swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV3.swapTokensMultipleV3ERC20ToERC20.selector + : genericSwapFacetV3.swapTokensMultipleV3ERC20ToNative.selector + : swapCase == SwapCase.NativeToERC20 + ? genericSwapFacetV4.swapTokensMultipleV3NativeToERC20.selector + : genericSwapFacetV4.swapTokensMultipleV3ERC20ToAny.selector; uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 ? defaultMinAmountOutERC20ToERC20 From d9a98fdd9d56c485d590dc96b636da9197fe536a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Wed, 10 Jul 2024 10:16:38 +0700 Subject: [PATCH 06/11] added nativeAddress parameter --- config/global.json | 29 +++++++++++++++++++ deployments/_deployments_log_file.json | 12 ++++++++ deployments/bsc.diamond.staging.json | 7 ++++- deployments/bsc.staging.json | 3 +- .../facets/DeployGenericSwapFacetV3.s.sol | 28 +++++++++++++++++- src/Facets/GenericSwapFacetV3.sol | 26 ++++++++++------- test/solidity/Facets/GenericSwapFacetV3.t.sol | 7 +++-- .../Facets/GenericSwapFacetV3_POL.t.sol | 4 ++- 8 files changed, 99 insertions(+), 17 deletions(-) diff --git a/config/global.json b/config/global.json index c807d9f2c..40897e732 100644 --- a/config/global.json +++ b/config/global.json @@ -94,5 +94,34 @@ "scroll": "https://transaction.safe.scroll.xyz/api", "sei": "https://transaction.sei-safe.protofire.io/api", "zksync": "https://safe-transaction-zksync.safe.global/api" + }, + + "nativeAddress": { + "mainnet": "0x0000000000000000000000000000000000000000", + "arbitrum": "0x0000000000000000000000000000000000000000", + "aurora": "0x0000000000000000000000000000000000000000", + "avalanche": "0x0000000000000000000000000000000000000000", + "base": "0x0000000000000000000000000000000000000000", + "blast": "0x0000000000000000000000000000000000000000", + "boba": "0x0000000000000000000000000000000000000000", + "bsc": "0x0000000000000000000000000000000000000000", + "celo": "0x471EcE3750Da237f93B8E339c536989b8978a438and", + "fantom": "0x0000000000000000000000000000000000000000", + "fraxtal": "0x0000000000000000000000000000000000000000", + "fuse": "0x0000000000000000000000000000000000000000", + "gnosis": "0x0000000000000000000000000000000000000000", + "linea": "0x0000000000000000000000000000000000000000", + "mantle": "0x0000000000000000000000000000000000000000", + "metis": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", + "mode": "0x0000000000000000000000000000000000000000", + "moonbeam": "0x0000000000000000000000000000000000000000", + "moonriver": "0x0000000000000000000000000000000000000000", + "optimism": "0x0000000000000000000000000000000000000000", + "polygon": "0x0000000000000000000000000000000000000000", + "polygonzkevm": "0x0000000000000000000000000000000000000000", + "rootstock": "0x0000000000000000000000000000000000000000", + "scroll": "0x0000000000000000000000000000000000000000", + "sei": "0x0000000000000000000000000000000000000000", + "zksync": "0x0000000000000000000000000000000000000000" } } diff --git a/deployments/_deployments_log_file.json b/deployments/_deployments_log_file.json index 82e246e26..7e2c1a29b 100644 --- a/deployments/_deployments_log_file.json +++ b/deployments/_deployments_log_file.json @@ -19858,6 +19858,18 @@ "VERIFIED": "true" } ] + }, + "staging": { + "1.0.1": [ + { + "ADDRESS": "0xE871874D8AC30E8aCD0eC67529b4a5dDD73Bf0d6", + "OPTIMIZER_RUNS": "1000000", + "TIMESTAMP": "2024-07-10 10:13:56", + "CONSTRUCTOR_ARGS": "0x0000000000000000000000000000000000000000000000000000000000000000", + "SALT": "", + "VERIFIED": "true" + } + ] } }, "celo": { diff --git a/deployments/bsc.diamond.staging.json b/deployments/bsc.diamond.staging.json index ba6ab0314..a76834589 100644 --- a/deployments/bsc.diamond.staging.json +++ b/deployments/bsc.diamond.staging.json @@ -69,9 +69,13 @@ "Name": "GenericSwapFacet", "Version": "1.0.0" }, - "0xf92D157a857d55B5DA987E35488e746EA85f1ca3": { + "0xA269cb81E6bBB86683558e449cb1bAFFdb155Bfc": { "Name": "", "Version": "" + }, + "0xE871874D8AC30E8aCD0eC67529b4a5dDD73Bf0d6": { + "Name": "GenericSwapFacetV3", + "Version": "1.0.1" } }, "Periphery": { @@ -81,6 +85,7 @@ "GasRebateDistributor": "", "LiFuelFeeCollector": "0xc4f7A34b8d283f66925eF0f5CCdFC2AF3030DeaE", "Receiver": "0x76EE0F8fb09047284B6ea89881595Fc6F5B09E12", + "ReceiverStargateV2": "", "RelayerCelerIM": "", "ServiceFeeCollector": "0xdF4257A2f61E5D432Dedbc9c65917C268323421d", "TokenWrapper": "0x5215E9fd223BC909083fbdB2860213873046e45d" diff --git a/deployments/bsc.staging.json b/deployments/bsc.staging.json index 49c8877f1..554f49b63 100644 --- a/deployments/bsc.staging.json +++ b/deployments/bsc.staging.json @@ -26,5 +26,6 @@ "ThorSwapFacet": "0xa6aAe470E7B8E8916e692882A5db25bB40C398A7", "AmarokFacetPacked": "0x7ac3EB2D191EBAb9E925CAbFD4F8155be066b3aa", "MayanBridgeFacet": "0x5Ba4FeD1DAd2fD057A9f687B399B8e4cF2368214", - "MayanFacet": "0xd596C903d78870786c5DB0E448ce7F87A65A0daD" + "MayanFacet": "0xd596C903d78870786c5DB0E448ce7F87A65A0daD", + "GenericSwapFacetV3": "0xE871874D8AC30E8aCD0eC67529b4a5dDD73Bf0d6" } \ No newline at end of file diff --git a/script/deploy/facets/DeployGenericSwapFacetV3.s.sol b/script/deploy/facets/DeployGenericSwapFacetV3.s.sol index 4b138ec75..9e3b7486a 100644 --- a/script/deploy/facets/DeployGenericSwapFacetV3.s.sol +++ b/script/deploy/facets/DeployGenericSwapFacetV3.s.sol @@ -3,13 +3,39 @@ pragma solidity ^0.8.17; import { DeployScriptBase } from "./utils/DeployScriptBase.sol"; import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; +import { stdJson } from "forge-std/Script.sol"; contract DeployScript is DeployScriptBase { + using stdJson for string; + constructor() DeployScriptBase("GenericSwapFacetV3") {} - function run() public returns (GenericSwapFacetV3 deployed) { + function run() + public + returns (GenericSwapFacetV3 deployed, bytes memory constructorArgs) + { + constructorArgs = getConstructorArgs(); + deployed = GenericSwapFacetV3( deploy(type(GenericSwapFacetV3).creationCode) ); } + + function getConstructorArgs() internal override returns (bytes memory) { + // get path of global config file + string memory globalConfigPath = string.concat( + root, + "/config/global.json" + ); + + // read file into json variable + string memory globalConfigJson = vm.readFile(globalConfigPath); + + // extract network's native address + address nativeAddress = globalConfigJson.readAddress( + string.concat(".nativeAddress.", network) + ); + + return abi.encode(nativeAddress); + } } diff --git a/src/Facets/GenericSwapFacetV3.sol b/src/Facets/GenericSwapFacetV3.sol index a228021bf..ccddfab81 100644 --- a/src/Facets/GenericSwapFacetV3.sol +++ b/src/Facets/GenericSwapFacetV3.sol @@ -8,16 +8,24 @@ import { LibAllowList } from "../Libraries/LibAllowList.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "../Errors/GenericErrors.sol"; import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; -import { console2 } from "forge-std/console2.sol"; /// @title GenericSwapFacetV3 /// @author LI.FI (https://li.fi) /// @notice Provides gas-optimized functionality for fee collection and for swapping through any APPROVED DEX /// @dev Can only execute calldata for APPROVED function selectors -/// @custom:version 1.0.0 +/// @custom:version 1.0.1 contract GenericSwapFacetV3 is ILiFi { using SafeTransferLib for ERC20; + /// Storage + address public immutable NATIVE_ADDRESS; + + /// Constructor + /// @param _nativeAddress the address of the native token for this network + constructor(address _nativeAddress) { + NATIVE_ADDRESS = _nativeAddress; + } + /// External Methods /// // SINGLE SWAPS @@ -114,7 +122,7 @@ contract GenericSwapFacetV3 is ILiFi { _transactionId, _swapData.callTo, sendingAssetId, - address(0), + NATIVE_ADDRESS, fromAmount, amountReceived, block.timestamp @@ -126,7 +134,7 @@ contract GenericSwapFacetV3 is ILiFi { _referrer, _receiver, sendingAssetId, - address(0), + NATIVE_ADDRESS, fromAmount, amountReceived ); @@ -183,7 +191,7 @@ contract GenericSwapFacetV3 is ILiFi { emit LibSwap.AssetSwapped( _transactionId, callTo, - address(0), + NATIVE_ADDRESS, receivingAssetId, fromAmount, amountReceived, @@ -195,7 +203,7 @@ contract GenericSwapFacetV3 is ILiFi { _integrator, _referrer, _receiver, - address(0), + NATIVE_ADDRESS, receivingAssetId, fromAmount, amountReceived @@ -506,7 +514,6 @@ contract GenericSwapFacetV3 is ILiFi { uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData ) private { - console2.log("in _transferNativeTokensAndEmitEvent"); uint256 amountReceived = address(this).balance; // make sure minAmountOut was received @@ -517,7 +524,6 @@ contract GenericSwapFacetV3 is ILiFi { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = _receiver.call{ value: amountReceived }(""); if (!success) { - console2.log("HEYA"); revert NativeAssetTransferFailed(); } @@ -528,7 +534,7 @@ contract GenericSwapFacetV3 is ILiFi { _referrer, _receiver, _swapData[0].sendingAssetId, - address(0), + NATIVE_ADDRESS, _swapData[0].fromAmount, amountReceived ); @@ -540,7 +546,7 @@ contract GenericSwapFacetV3 is ILiFi { address receiver ) private { // if a balance exists in sendingAsset, it must be positive slippage - if (address(sendingAsset) != address(0)) { + if (address(sendingAsset) != NATIVE_ADDRESS) { uint256 sendingAssetBalance = sendingAsset.balanceOf( address(this) ); diff --git a/test/solidity/Facets/GenericSwapFacetV3.t.sol b/test/solidity/Facets/GenericSwapFacetV3.t.sol index 815ac05fe..29527e0ff 100644 --- a/test/solidity/Facets/GenericSwapFacetV3.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV3.t.sol @@ -14,12 +14,13 @@ import { ERC20 } from "solmate/tokens/ERC20.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "lifi/Errors/GenericErrors.sol"; import { UniswapV2Router02 } from "../utils/Interfaces.sol"; -// import { MockUniswapDEX } from "../utils/MockUniswapDEX.sol"; import { TestHelpers, MockUniswapDEX, NonETHReceiver } from "../utils/TestHelpers.sol"; import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; // Stub GenericSwapFacet Contract contract TestGenericSwapFacetV3 is GenericSwapFacetV3, GenericSwapFacet { + constructor(address _nativeAddress) GenericSwapFacetV3(_nativeAddress) {} + function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); } @@ -104,7 +105,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { diamond = createDiamond(); genericSwapFacet = new TestGenericSwapFacet(); - genericSwapFacetV3 = new TestGenericSwapFacetV3(); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); usdc = ERC20(USDC_ADDRESS); usdt = ERC20(USDT_ADDRESS); dai = ERC20(DAI_ADDRESS); @@ -1947,7 +1948,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // get swapData ( LibSwap.SwapData[] memory swapData, - uint256 amountIn, + , uint256 minAmountOut ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( address(genericSwapFacetV3) diff --git a/test/solidity/Facets/GenericSwapFacetV3_POL.t.sol b/test/solidity/Facets/GenericSwapFacetV3_POL.t.sol index 2f8febaba..1b930f9c6 100644 --- a/test/solidity/Facets/GenericSwapFacetV3_POL.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV3_POL.t.sol @@ -17,6 +17,8 @@ import { ERC20, SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; // Stub GenericSwapFacet Contract contract TestGenericSwapFacetV3 is GenericSwapFacetV3, GenericSwapFacet { + constructor(address _nativeAddress) GenericSwapFacetV3(_nativeAddress) {} + function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); } @@ -95,7 +97,7 @@ contract GenericSwapFacetV3POLTest is DSTest, DiamondTest, Test { diamond = createDiamond(); genericSwapFacet = new TestGenericSwapFacet(); - genericSwapFacetV3 = new TestGenericSwapFacetV3(); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); usdc = ERC20(USDC_ADDRESS); usdt = ERC20(USDT_ADDRESS); dai = ERC20(DAI_ADDRESS); From f6845059d632ef61a83734d172a9b7e7368fdf3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 11 Jul 2024 09:24:34 +0700 Subject: [PATCH 07/11] all tests fixed --- src/Facets/GenericSwapFacetV4.sol | 134 +++++++++++++----- test/solidity/Facets/GenericSwapFacetV3.t.sol | 5 - test/solidity/Facets/GenericSwapFacetV4.t.sol | 100 +++++++++++-- 3 files changed, 192 insertions(+), 47 deletions(-) diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Facets/GenericSwapFacetV4.sol index 3918d1ada..a95cd7a89 100644 --- a/src/Facets/GenericSwapFacetV4.sol +++ b/src/Facets/GenericSwapFacetV4.sol @@ -3,12 +3,10 @@ pragma solidity 0.8.17; import { ILiFi } from "../Interfaces/ILiFi.sol"; import { LibUtil } from "../Libraries/LibUtil.sol"; -import { LibSwap } from "../Libraries/LibSwap.sol"; +import { LibSwap, IERC20 } from "../Libraries/LibSwap.sol"; import { LibAllowList } from "../Libraries/LibAllowList.sol"; import { LibAsset } from "../Libraries/LibAsset.sol"; -import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData } from "../Errors/GenericErrors.sol"; - -//TODO: replace with solady +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData, UnAuthorized } from "../Errors/GenericErrors.sol"; import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; //TODO: remove @@ -22,16 +20,38 @@ import { console2 } from "forge-std/console2.sol"; contract GenericSwapFacetV4 is ILiFi { using SafeTransferLib for address; + struct TokenApproval { + address tokenAddress; + bool maxApprovalToFeeCollector; // if true then a max approval will be set between this contract and LI.FI FeeCollector + bool maxApprovalToDexAggregator; // if true then a max approval will be set between this contract and the LI.FI DEX Aggregator + } + + /// Modifier /// + modifier onlyAdmin() { + if (msg.sender != adminAddress) revert UnAuthorized(); + _; + } + /// Storage /// address public immutable dexAggregatorAddress; + address public immutable feeCollectorAddress; + address public immutable adminAddress; /// Constructor /// @notice Initialize the contract - /// @param _dexAggregatorAddress The address of the DEX aggregator - constructor(address _dexAggregatorAddress) { + /// @param _dexAggregatorAddress The address of the LI.FI DEX aggregator + /// @param _feeCollectorAddress The address of the LI.FI FeeCollector + /// @param _adminAddress The address of admin wallet (that can set token approvals) + constructor( + address _dexAggregatorAddress, + address _feeCollectorAddress, + address _adminAddress + ) { dexAggregatorAddress = _dexAggregatorAddress; + feeCollectorAddress = _feeCollectorAddress; + adminAddress = _adminAddress; } /// Modifier @@ -40,6 +60,22 @@ contract GenericSwapFacetV4 is ILiFi { _; } + modifier onlyCallsToLiFiContracts(LibSwap.SwapData[] memory swapData) { + for (uint256 i; i < swapData.length; ) { + if ( + swapData[i].callTo != dexAggregatorAddress && + swapData[i].callTo != feeCollectorAddress + ) revert InvalidCallData(); + + // gas-efficient way to increase loop counter + unchecked { + ++i; + } + } + + _; + } + /// External Methods /// // SINGLE SWAPS @@ -174,7 +210,7 @@ contract GenericSwapFacetV4 is ILiFi { address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData - ) external { + ) external onlyCallsToLiFiContracts(_swapData) { // deposit token of first swap LibSwap.SwapData calldata currentSwap = _swapData[0]; @@ -203,7 +239,7 @@ contract GenericSwapFacetV4 is ILiFi { address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData - ) external { + ) external onlyCallsToLiFiContracts(_swapData) { // deposit token of first swap LibSwap.SwapData calldata currentSwap = _swapData[0]; @@ -239,7 +275,7 @@ contract GenericSwapFacetV4 is ILiFi { address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData - ) external payable { + ) external payable onlyCallsToLiFiContracts(_swapData) { uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); // make sure that minAmount was received @@ -247,32 +283,66 @@ contract GenericSwapFacetV4 is ILiFi { revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); } - /// Private helper methods /// - function _depositMultipleERC20Tokens( - LibSwap.SwapData[] calldata _swapData - ) private {} - - function _depositAndSwapERC20Single( - LibSwap.SwapData calldata _swapData, - address _receiver - ) private onlyCallsToDexAggregator(_swapData.callTo) { - address sendingAssetId = _swapData.sendingAssetId; - uint256 fromAmount = _swapData.fromAmount; - // deposit funds - sendingAssetId.safeTransferFrom(msg.sender, address(this), fromAmount); - - // execute swap - // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = _swapData.callTo.call( - _swapData.callData - ); - if (!success) { - LibUtil.revertWith(res); + /// @notice (Re-)Sets max approvals from this contract to DEX Aggregator and FeeCollector + /// @param _approvals The information which approvals to set for which token + function setApprovalForTokens( + TokenApproval[] calldata _approvals + ) external onlyAdmin { + address tokenAddress; + uint256 currentAllowance; + for (uint256 i; i < _approvals.length; ) { + tokenAddress = _approvals[i].tokenAddress; + + // if maxApprovalToDexAggregator==true, set max approval, otherwise set approval to 0 + // same for 'maxApprovalToFeeCollector' flag + + // update approval for DEX aggregator + if (_approvals[i].maxApprovalToDexAggregator) { + // if an allowance exists, set it to 0 first + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + dexAggregatorAddress + ); + if ( + currentAllowance != 0 && + currentAllowance != type(uint256).max + ) tokenAddress.safeApprove(dexAggregatorAddress, 0); + + // set max approval + tokenAddress.safeApprove( + dexAggregatorAddress, + type(uint256).max + ); + } else tokenAddress.safeApprove(dexAggregatorAddress, 0); + + // update approval for FeeCollector + if (_approvals[i].maxApprovalToFeeCollector) { + // if an allowance exists, set it to 0 first + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + feeCollectorAddress + ); + if ( + currentAllowance != 0 && + currentAllowance != type(uint256).max + ) tokenAddress.safeApprove(feeCollectorAddress, 0); + + // set max approval + tokenAddress.safeApprove( + feeCollectorAddress, + type(uint256).max + ); + } else tokenAddress.safeApprove(feeCollectorAddress, 0); + + // gas-efficient way to increase counter + unchecked { + ++i; + } } - - _returnPositiveSlippageERC20(sendingAssetId, _receiver); } + /// Private helper methods /// + // @dev: this function will not work with swapData that has multiple swaps with the same sendingAssetId // as the _returnPositiveSlippage... functionality will refund all remaining tokens after the first swap // We accept this fact since the use case is not common yet. As an alternative you can always use the diff --git a/test/solidity/Facets/GenericSwapFacetV3.t.sol b/test/solidity/Facets/GenericSwapFacetV3.t.sol index 304248067..da4f8685a 100644 --- a/test/solidity/Facets/GenericSwapFacetV3.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV3.t.sol @@ -73,11 +73,6 @@ contract GenericSwapFacetV3Test is TestHelpers { diamond = createDiamond(); genericSwapFacet = new TestGenericSwapFacet(); genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); - usdc = ERC20(USDC_ADDRESS); - usdt = ERC20(USDT_ADDRESS); - dai = ERC20(DAI_ADDRESS); - weth = ERC20(WETH_ADDRESS); - uniswap = UniswapV2Router02(UNISWAP_V2_ROUTER); feeCollector = FeeCollector(FEE_COLLECTOR); // add genericSwapFacet (v1) to diamond (for gas usage comparison) diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Facets/GenericSwapFacetV4.t.sol index c3ffb8979..ac8376854 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Facets/GenericSwapFacetV4.t.sol @@ -4,17 +4,23 @@ pragma solidity 0.8.17; import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; import { GenericSwapFacetV4 } from "lifi/Facets/GenericSwapFacetV4.sol"; import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; -import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed } from "lifi/Errors/GenericErrors.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, UnAuthorized } from "lifi/Errors/GenericErrors.sol"; import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; -import { SafeTransferLib } from "solmate/utils/SafeTransferLib.sol"; // TODO: replace with SOLADY - // Stub GenericSwapFacet Contract contract TestGenericSwapFacetV4 is GenericSwapFacetV4 { constructor( - address _dexAggregatorAddress - ) GenericSwapFacetV4(_dexAggregatorAddress) {} + address _dexAggregatorAddress, + address _feeCollectorAddress, + address _adminAddress + ) + GenericSwapFacetV4( + _dexAggregatorAddress, + _feeCollectorAddress, + _adminAddress + ) + {} function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); @@ -30,6 +36,8 @@ contract TestGenericSwapFacetV4 is GenericSwapFacetV4 { } contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { + constructor(address _nativeAddress) GenericSwapFacetV3(_nativeAddress) {} + function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); } @@ -44,14 +52,12 @@ contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { } contract GenericSwapFacetV4Test is TestHelpers { - using SafeTransferLib for ERC20; - // These values are for Mainnet address internal constant USDC_HOLDER = 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; address internal constant DAI_HOLDER = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; - address internal constant SOME_WALLET = + address internal constant USER_ADMIN = 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; TestGenericSwapFacetV3 internal genericSwapFacetV3; @@ -68,9 +74,11 @@ contract GenericSwapFacetV4Test is TestHelpers { diamond = createDiamond(); routeProcessor = new RouteProcessor4(address(0), new address[](0)); - genericSwapFacetV3 = new TestGenericSwapFacetV3(); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); genericSwapFacetV4 = new TestGenericSwapFacetV4( - address(routeProcessor) + address(routeProcessor), + address(feeCollector), + USER_ADMIN ); // add genericSwapFacet (v3) to diamond (for gas usage comparison) @@ -466,8 +474,80 @@ contract GenericSwapFacetV4Test is TestHelpers { console.log("gas used: V4", gasUsed); } + function test_AdminCanUpdateTokenApprovals() public { + assertEq( + usdc.allowance( + address(genericSwapFacetV4), + address(routeProcessor) + ), + 0 + ); + assertEq( + usdt.allowance( + address(genericSwapFacetV4), + address(routeProcessor) + ), + 0 + ); + + GenericSwapFacetV4.TokenApproval[] + memory approvals = _getTokenApprovalsStruct(); + + vm.startPrank(USER_ADMIN); + genericSwapFacetV4.setApprovalForTokens(approvals); + + assertEq( + usdc.allowance( + address(genericSwapFacetV4), + address(routeProcessor) + ), + type(uint256).max + ); + assertEq( + usdc.allowance(address(genericSwapFacetV4), address(feeCollector)), + 0 + ); + assertEq( + usdt.allowance( + address(genericSwapFacetV4), + address(routeProcessor) + ), + 0 + ); + assertEq( + usdt.allowance(address(genericSwapFacetV4), address(feeCollector)), + type(uint256).max + ); + } + + function test_NonAdminCannotUpdateTokenApprovals() public { + GenericSwapFacetV4.TokenApproval[] + memory approvals = _getTokenApprovalsStruct(); + + vm.startPrank(USER_SENDER); + + vm.expectRevert(UnAuthorized.selector); + + genericSwapFacetV4.setApprovalForTokens(approvals); + } + // ------ HELPER FUNCTIONS + function _getTokenApprovalsStruct() + internal + view + returns (GenericSwapFacetV4.TokenApproval[] memory approvals) + { + approvals = new GenericSwapFacetV4.TokenApproval[](2); + approvals[0].tokenAddress = ADDRESS_USDC; + approvals[0].maxApprovalToDexAggregator = true; + approvals[0].maxApprovalToFeeCollector = false; + + approvals[1].tokenAddress = ADDRESS_USDT; + approvals[1].maxApprovalToDexAggregator = false; + approvals[1].maxApprovalToFeeCollector = true; + } + enum SwapCase { NativeToERC20, ERC20ToERC20, From 1099596a2f08ec5291fd01667df13ece60da0b53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 11 Jul 2024 10:04:41 +0700 Subject: [PATCH 08/11] refactoring --- .../GenericSwapper.sol} | 7 +- src/Periphery/GenericSwapperB.sol | 393 +++++++++ .../GenericSwapper.t.sol} | 98 +-- test/solidity/Periphery/GenericSwapperB.t.sol | 751 ++++++++++++++++++ 4 files changed, 1189 insertions(+), 60 deletions(-) rename src/{Facets/GenericSwapFacetV4.sol => Periphery/GenericSwapper.sol} (99%) create mode 100644 src/Periphery/GenericSwapperB.sol rename test/solidity/{Facets/GenericSwapFacetV4.t.sol => Periphery/GenericSwapper.t.sol} (89%) create mode 100644 test/solidity/Periphery/GenericSwapperB.t.sol diff --git a/src/Facets/GenericSwapFacetV4.sol b/src/Periphery/GenericSwapper.sol similarity index 99% rename from src/Facets/GenericSwapFacetV4.sol rename to src/Periphery/GenericSwapper.sol index a95cd7a89..a2cc8ccb6 100644 --- a/src/Facets/GenericSwapFacetV4.sol +++ b/src/Periphery/GenericSwapper.sol @@ -9,15 +9,12 @@ import { LibAsset } from "../Libraries/LibAsset.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData, UnAuthorized } from "../Errors/GenericErrors.sol"; import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; -//TODO: remove -import { console2 } from "forge-std/console2.sol"; - -/// @title GenericSwapFacetV4 +/// @title GenericSwapper /// @author LI.FI (https://li.fi) /// @notice Provides gas-optimized functionality for fee collection and for swapping through any APPROVED DEX /// @dev Can only execute calldata for APPROVED function selectors /// @custom:version 1.0.0 -contract GenericSwapFacetV4 is ILiFi { +contract GenericSwapper is ILiFi { using SafeTransferLib for address; struct TokenApproval { diff --git a/src/Periphery/GenericSwapperB.sol b/src/Periphery/GenericSwapperB.sol new file mode 100644 index 000000000..e44985193 --- /dev/null +++ b/src/Periphery/GenericSwapperB.sol @@ -0,0 +1,393 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.17; + +import { ILiFi } from "../Interfaces/ILiFi.sol"; +import { LibUtil } from "../Libraries/LibUtil.sol"; +import { LibSwap, IERC20 } from "../Libraries/LibSwap.sol"; +import { LibAllowList } from "../Libraries/LibAllowList.sol"; +import { LibAsset } from "../Libraries/LibAsset.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData, UnAuthorized } from "../Errors/GenericErrors.sol"; +import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; + +/// @title GenericSwapper +/// @author LI.FI (https://li.fi) +/// @notice Provides gas-optimized functionality for fee collection and for swapping through any APPROVED DEX +/// @dev Can only execute calldata for APPROVED function selectors +/// @custom:version 1.0.0 +contract GenericSwapperB is ILiFi { + using SafeTransferLib for address; + + struct TokenApproval { + address tokenAddress; + bool maxApprovalToFeeCollector; // if true then a max approval will be set between this contract and LI.FI FeeCollector + bool maxApprovalToDexAggregator; // if true then a max approval will be set between this contract and the LI.FI DEX Aggregator + } + + /// Modifier /// + modifier onlyAdmin() { + if (msg.sender != adminAddress) revert UnAuthorized(); + _; + } + + /// Storage /// + + address public immutable dexAggregatorAddress; + address public immutable feeCollectorAddress; + address public immutable adminAddress; + + /// Constructor + + /// @notice Initialize the contract + /// @param _dexAggregatorAddress The address of the LI.FI DEX aggregator + /// @param _feeCollectorAddress The address of the LI.FI FeeCollector + /// @param _adminAddress The address of admin wallet (that can set token approvals) + constructor( + address _dexAggregatorAddress, + address _feeCollectorAddress, + address _adminAddress + ) { + dexAggregatorAddress = _dexAggregatorAddress; + feeCollectorAddress = _feeCollectorAddress; + adminAddress = _adminAddress; + } + + /// Modifier + modifier onlyCallsToDexAggregator(address callTo) { + if (callTo != dexAggregatorAddress) revert InvalidCallData(); + _; + } + + modifier onlyCallsToLiFiContracts(LibSwap.SwapData[] memory swapData) { + for (uint256 i; i < swapData.length; ) { + if ( + swapData[i].callTo != dexAggregatorAddress && + swapData[i].callTo != feeCollectorAddress + ) revert InvalidCallData(); + + // gas-efficient way to increase loop counter + unchecked { + ++i; + } + } + + _; + } + + /// External Methods /// + + // SINGLE SWAPS + + /// @notice Performs a single swap from an ERC20 token to another ERC20 token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToERC20( + address _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external onlyCallsToDexAggregator(_swapData.callTo) { + address sendingAssetId = _swapData.sendingAssetId; + // deposit funds + sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + _swapData.fromAmount + ); + + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = _swapData.callTo.call( + _swapData.callData + ); + if (!success) { + LibUtil.revertWith(res); + } + + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + _returnPositiveSlippageERC20(sendingAssetId, _receiver); + } + + /// @notice Performs a single swap from an ERC20 token to the network's native token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToNative( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external onlyCallsToDexAggregator(_swapData.callTo) { + address sendingAssetId = _swapData.sendingAssetId; + + // deposit funds + sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + _swapData.fromAmount + ); + + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = _swapData.callTo.call( + _swapData.callData + ); + if (!success) { + LibUtil.revertWith(res); + } + + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + _returnPositiveSlippageNative(_receiver); + } + + /// @notice Performs a single swap from the network's native token to ERC20 token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3NativeToERC20( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) external payable onlyCallsToDexAggregator(_swapData.callTo) { + // execute swap + // solhint-disable-next-line avoid-low-level-calls + (bool success, bytes memory res) = _swapData.callTo.call{ + value: msg.value + }(_swapData.callData); + if (!success) { + LibUtil.revertWith(res); + } + + // make sure that minAmount was received + uint256 amountReceived = abi.decode(res, (uint256)); + if (amountReceived < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); + + // return any positive slippage (i.e. unused sendingAsset tokens) + _returnPositiveSlippageNative(_receiver); + } + + // MULTIPLE SWAPS + + /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3ERC20ToAny( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external onlyCallsToLiFiContracts(_swapData) { + // deposit token of first swap + LibSwap.SwapData calldata currentSwap = _swapData[0]; + + // check if a deposit is required + if (currentSwap.requiresDeposit) { + // we will not check msg.value as tx will fail anyway if not enough value available + // thus we only deposit ERC20 tokens here + currentSwap.sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + currentSwap.fromAmount + ); + } + + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); + } + + function swapTokensMultipleV3ERC20ToNative( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external onlyCallsToLiFiContracts(_swapData) { + // deposit token of first swap + LibSwap.SwapData calldata currentSwap = _swapData[0]; + + // check if a deposit is required + if (currentSwap.requiresDeposit) { + // we will not check msg.value as tx will fail anyway if not enough value available + // thus we only deposit ERC20 tokens here + currentSwap.sendingAssetId.safeTransferFrom( + msg.sender, + address(this), + currentSwap.fromAmount + ); + } + + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); + } + + /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3NativeToERC20( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) external payable onlyCallsToLiFiContracts(_swapData) { + uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); + + // make sure that minAmount was received + if (finalAmountOut < _minAmountOut) + revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); + } + + /// @notice (Re-)Sets max approvals from this contract to DEX Aggregator and FeeCollector + /// @param _approvals The information which approvals to set for which token + function setApprovalForTokens( + TokenApproval[] calldata _approvals + ) external onlyAdmin { + address tokenAddress; + uint256 currentAllowance; + for (uint256 i; i < _approvals.length; ) { + tokenAddress = _approvals[i].tokenAddress; + + // if maxApprovalToDexAggregator==true, set max approval, otherwise set approval to 0 + // same for 'maxApprovalToFeeCollector' flag + + // update approval for DEX aggregator + if (_approvals[i].maxApprovalToDexAggregator) { + // if an allowance exists, set it to 0 first + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + dexAggregatorAddress + ); + if ( + currentAllowance != 0 && + currentAllowance != type(uint256).max + ) tokenAddress.safeApprove(dexAggregatorAddress, 0); + + // set max approval + tokenAddress.safeApprove( + dexAggregatorAddress, + type(uint256).max + ); + } else tokenAddress.safeApprove(dexAggregatorAddress, 0); + + // update approval for FeeCollector + if (_approvals[i].maxApprovalToFeeCollector) { + // if an allowance exists, set it to 0 first + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + feeCollectorAddress + ); + if ( + currentAllowance != 0 && + currentAllowance != type(uint256).max + ) tokenAddress.safeApprove(feeCollectorAddress, 0); + + // set max approval + tokenAddress.safeApprove( + feeCollectorAddress, + type(uint256).max + ); + } else tokenAddress.safeApprove(feeCollectorAddress, 0); + + // gas-efficient way to increase counter + unchecked { + ++i; + } + } + } + + /// Private helper methods /// + + // @dev: this function will not work with swapData that has multiple swaps with the same sendingAssetId + // as the _returnPositiveSlippage... functionality will refund all remaining tokens after the first swap + // We accept this fact since the use case is not common yet. As an alternative you can always use the + // "swapTokensGeneric" function of the original GenericSwapFacet + function _executeSwaps( + LibSwap.SwapData[] calldata _swapData, + address _receiver + ) private returns (uint256 finalAmountOut) { + // initialize variables before loop to save gas + address sendingAssetId; + address receivingAssetId; + LibSwap.SwapData calldata currentSwap; + bool success; + bytes memory returnData; + + // go through all swaps + for (uint256 i = 0; i < _swapData.length; ) { + currentSwap = _swapData[i]; + sendingAssetId = currentSwap.sendingAssetId; + receivingAssetId = currentSwap.receivingAssetId; + + // execute the swap + (success, returnData) = currentSwap.callTo.call{ + value: LibAsset.isNativeAsset(sendingAssetId) + ? currentSwap.fromAmount + : 0 + }(currentSwap.callData); + if (!success) { + LibUtil.revertWith(returnData); + } + + // check if this is the final swap + if (i == _swapData.length - 1) { + finalAmountOut = abi.decode(returnData, (uint256)); + } + + // return any potential leftover sendingAsset tokens + // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) + if (sendingAssetId != receivingAssetId) + if (LibAsset.isNativeAsset(sendingAssetId)) { + // Native + _returnPositiveSlippageNative(_receiver); + } else { + // ERC20 + _returnPositiveSlippageERC20(sendingAssetId, _receiver); + } + + unchecked { + ++i; + } + } + } + + // returns any unused 'sendingAsset' tokens (=> positive slippage) to the receiver address + function _returnPositiveSlippageERC20( + address sendingAsset, + address receiver + ) private { + // if a balance exists in sendingAsset, it must be positive slippage + if (address(sendingAsset) != address(0)) { + uint256 sendingAssetBalance = sendingAsset.balanceOf( + address(this) + ); + + if (sendingAssetBalance > 0) { + sendingAsset.safeTransfer(receiver, sendingAssetBalance); + } + } + } + + // returns any unused native tokens (=> positive slippage) to the receiver address + function _returnPositiveSlippageNative(address receiver) private { + // if a native balance exists in sendingAsset, it must be positive slippage + uint256 nativeBalance = address(this).balance; + + if (nativeBalance > 0) { + // solhint-disable-next-line avoid-low-level-calls + (bool success, ) = receiver.call{ value: nativeBalance }(""); + if (!success) revert NativeAssetTransferFailed(); + } + } + + receive() external payable {} +} diff --git a/test/solidity/Facets/GenericSwapFacetV4.t.sol b/test/solidity/Periphery/GenericSwapper.t.sol similarity index 89% rename from test/solidity/Facets/GenericSwapFacetV4.t.sol rename to test/solidity/Periphery/GenericSwapper.t.sol index ac8376854..a9576199d 100644 --- a/test/solidity/Facets/GenericSwapFacetV4.t.sol +++ b/test/solidity/Periphery/GenericSwapper.t.sol @@ -2,20 +2,20 @@ pragma solidity 0.8.17; import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; -import { GenericSwapFacetV4 } from "lifi/Facets/GenericSwapFacetV4.sol"; +import { GenericSwapper } from "lifi/Periphery/GenericSwapper.sol"; import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, UnAuthorized } from "lifi/Errors/GenericErrors.sol"; import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; // Stub GenericSwapFacet Contract -contract TestGenericSwapFacetV4 is GenericSwapFacetV4 { +contract TestGenericSwapper is GenericSwapper { constructor( address _dexAggregatorAddress, address _feeCollectorAddress, address _adminAddress ) - GenericSwapFacetV4( + GenericSwapper( _dexAggregatorAddress, _feeCollectorAddress, _adminAddress @@ -51,7 +51,7 @@ contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { } } -contract GenericSwapFacetV4Test is TestHelpers { +contract GenericSwapperTest is TestHelpers { // These values are for Mainnet address internal constant USDC_HOLDER = 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; @@ -61,7 +61,7 @@ contract GenericSwapFacetV4Test is TestHelpers { 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; TestGenericSwapFacetV3 internal genericSwapFacetV3; - TestGenericSwapFacetV4 internal genericSwapFacetV4; + TestGenericSwapper internal genericSwapper; RouteProcessor4 internal routeProcessor; uint256 defaultMinAmountOutNativeToERC20 = 2991350294; @@ -75,7 +75,7 @@ contract GenericSwapFacetV4Test is TestHelpers { diamond = createDiamond(); routeProcessor = new RouteProcessor4(address(0), new address[](0)); genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); - genericSwapFacetV4 = new TestGenericSwapFacetV4( + genericSwapper = new TestGenericSwapper( address(routeProcessor), address(feeCollector), USER_ADMIN @@ -120,8 +120,8 @@ contract GenericSwapFacetV4Test is TestHelpers { ); // v4 - genericSwapFacetV4.addDex(address(routeProcessor)); - genericSwapFacetV4.setFunctionApprovalBySignature( + genericSwapper.addDex(address(routeProcessor)); + genericSwapper.setFunctionApprovalBySignature( routeProcessor.processRoute.selector ); @@ -135,16 +135,16 @@ contract GenericSwapFacetV4Test is TestHelpers { feeCollector.collectNativeFees.selector ); // v4 - genericSwapFacetV4.addDex(address(feeCollector)); - genericSwapFacetV4.setFunctionApprovalBySignature( + genericSwapper.addDex(address(feeCollector)); + genericSwapper.setFunctionApprovalBySignature( feeCollector.collectTokenFees.selector ); - genericSwapFacetV4.setFunctionApprovalBySignature( + genericSwapper.setFunctionApprovalBySignature( feeCollector.collectNativeFees.selector ); vm.label(address(genericSwapFacetV3), "GenericSwapV3 via Diamond"); - vm.label(address(genericSwapFacetV4), "GenericSwapV4"); + vm.label(address(genericSwapper), "GenericSwapV4"); vm.label(address(routeProcessor), "RouteProcessor"); vm.label(ADDRESS_WETH, "WETH_TOKEN"); vm.label(ADDRESS_DAI, "DAI_TOKEN"); @@ -184,7 +184,7 @@ contract GenericSwapFacetV4Test is TestHelpers { { uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call{ + (bool success, ) = address(genericSwapper).call{ value: defaultNativeAmount }(_getGenericSwapCallDataSingle(false, SwapCase.NativeToERC20)); if (!success) revert(); @@ -226,16 +226,16 @@ contract GenericSwapFacetV4Test is TestHelpers { ) { // ensure that max approval exists from GenericSwapFacet to DEX aggregator - vm.startPrank(address(genericSwapFacetV4)); + vm.startPrank(address(genericSwapper)); usdc.approve(address(routeProcessor), type(uint256).max); vm.stopPrank(); vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapFacetV4), defaultUSDCAmount); + usdc.approve(address(genericSwapper), defaultUSDCAmount); uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call( + (bool success, ) = address(genericSwapper).call( _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToNative) ); if (!success) revert(); @@ -277,16 +277,16 @@ contract GenericSwapFacetV4Test is TestHelpers { ) { // ensure that max approval exists from GenericSwapFacet to DEX aggregator - vm.startPrank(address(genericSwapFacetV4)); + vm.startPrank(address(genericSwapper)); usdc.approve(address(routeProcessor), type(uint256).max); vm.stopPrank(); vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapFacetV4), defaultUSDCAmount); + usdc.approve(address(genericSwapper), defaultUSDCAmount); uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call( + (bool success, ) = address(genericSwapper).call( _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToERC20) ); if (!success) revert(); @@ -332,7 +332,7 @@ contract GenericSwapFacetV4Test is TestHelpers { { uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call{ + (bool success, ) = address(genericSwapper).call{ value: defaultNativeAmount + defaultNativeFeeCollectionAmount }( _getGenericSwapCallDataFeeCollectionPlusSwap( @@ -385,20 +385,20 @@ contract GenericSwapFacetV4Test is TestHelpers { ) { // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector - vm.startPrank(address(genericSwapFacetV4)); + vm.startPrank(address(genericSwapper)); usdc.approve(address(routeProcessor), type(uint256).max); usdc.approve(address(feeCollector), type(uint256).max); vm.stopPrank(); vm.startPrank(USER_SENDER); usdc.approve( - address(genericSwapFacetV4), + address(genericSwapper), defaultUSDCAmount + defaultUSDCFeeCollectionAmount ); uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call( + (bool success, ) = address(genericSwapper).call( _getGenericSwapCallDataFeeCollectionPlusSwap( false, SwapCase.ERC20ToNative @@ -449,20 +449,20 @@ contract GenericSwapFacetV4Test is TestHelpers { ) { // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector - vm.startPrank(address(genericSwapFacetV4)); + vm.startPrank(address(genericSwapper)); usdc.approve(address(routeProcessor), type(uint256).max); usdc.approve(address(feeCollector), type(uint256).max); vm.stopPrank(); vm.startPrank(USER_SENDER); usdc.approve( - address(genericSwapFacetV4), + address(genericSwapper), defaultUSDCAmount + defaultUSDCFeeCollectionAmount ); uint256 gasLeftBef = gasleft(); - (bool success, ) = address(genericSwapFacetV4).call( + (bool success, ) = address(genericSwapper).call( _getGenericSwapCallDataFeeCollectionPlusSwap( false, SwapCase.ERC20ToERC20 @@ -476,59 +476,47 @@ contract GenericSwapFacetV4Test is TestHelpers { function test_AdminCanUpdateTokenApprovals() public { assertEq( - usdc.allowance( - address(genericSwapFacetV4), - address(routeProcessor) - ), + usdc.allowance(address(genericSwapper), address(routeProcessor)), 0 ); assertEq( - usdt.allowance( - address(genericSwapFacetV4), - address(routeProcessor) - ), + usdt.allowance(address(genericSwapper), address(routeProcessor)), 0 ); - GenericSwapFacetV4.TokenApproval[] + GenericSwapper.TokenApproval[] memory approvals = _getTokenApprovalsStruct(); vm.startPrank(USER_ADMIN); - genericSwapFacetV4.setApprovalForTokens(approvals); + genericSwapper.setApprovalForTokens(approvals); assertEq( - usdc.allowance( - address(genericSwapFacetV4), - address(routeProcessor) - ), + usdc.allowance(address(genericSwapper), address(routeProcessor)), type(uint256).max ); assertEq( - usdc.allowance(address(genericSwapFacetV4), address(feeCollector)), + usdc.allowance(address(genericSwapper), address(feeCollector)), 0 ); assertEq( - usdt.allowance( - address(genericSwapFacetV4), - address(routeProcessor) - ), + usdt.allowance(address(genericSwapper), address(routeProcessor)), 0 ); assertEq( - usdt.allowance(address(genericSwapFacetV4), address(feeCollector)), + usdt.allowance(address(genericSwapper), address(feeCollector)), type(uint256).max ); } function test_NonAdminCannotUpdateTokenApprovals() public { - GenericSwapFacetV4.TokenApproval[] + GenericSwapper.TokenApproval[] memory approvals = _getTokenApprovalsStruct(); vm.startPrank(USER_SENDER); vm.expectRevert(UnAuthorized.selector); - genericSwapFacetV4.setApprovalForTokens(approvals); + genericSwapper.setApprovalForTokens(approvals); } // ------ HELPER FUNCTIONS @@ -536,9 +524,9 @@ contract GenericSwapFacetV4Test is TestHelpers { function _getTokenApprovalsStruct() internal view - returns (GenericSwapFacetV4.TokenApproval[] memory approvals) + returns (GenericSwapper.TokenApproval[] memory approvals) { - approvals = new GenericSwapFacetV4.TokenApproval[](2); + approvals = new GenericSwapper.TokenApproval[](2); approvals[0].tokenAddress = ADDRESS_USDC; approvals[0].maxApprovalToDexAggregator = true; approvals[0].maxApprovalToFeeCollector = false; @@ -673,10 +661,10 @@ contract GenericSwapFacetV4Test is TestHelpers { SwapCase swapCase ) internal view returns (bytes memory callData) { bytes4 selector = swapCase == SwapCase.ERC20ToERC20 - ? genericSwapFacetV4.swapTokensSingleV3ERC20ToERC20.selector + ? genericSwapper.swapTokensSingleV3ERC20ToERC20.selector : swapCase == SwapCase.ERC20ToNative - ? genericSwapFacetV4.swapTokensSingleV3ERC20ToNative.selector - : genericSwapFacetV4.swapTokensSingleV3NativeToERC20.selector; + ? genericSwapper.swapTokensSingleV3ERC20ToNative.selector + : genericSwapper.swapTokensSingleV3NativeToERC20.selector; uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 ? defaultMinAmountOutERC20ToERC20 @@ -708,8 +696,8 @@ contract GenericSwapFacetV4Test is TestHelpers { ? genericSwapFacetV3.swapTokensMultipleV3ERC20ToERC20.selector : genericSwapFacetV3.swapTokensMultipleV3ERC20ToNative.selector : swapCase == SwapCase.NativeToERC20 - ? genericSwapFacetV4.swapTokensMultipleV3NativeToERC20.selector - : genericSwapFacetV4.swapTokensMultipleV3ERC20ToAny.selector; + ? genericSwapper.swapTokensMultipleV3NativeToERC20.selector + : genericSwapper.swapTokensMultipleV3ERC20ToAny.selector; uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 ? defaultMinAmountOutERC20ToERC20 diff --git a/test/solidity/Periphery/GenericSwapperB.t.sol b/test/solidity/Periphery/GenericSwapperB.t.sol new file mode 100644 index 000000000..10eedcc9b --- /dev/null +++ b/test/solidity/Periphery/GenericSwapperB.t.sol @@ -0,0 +1,751 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity 0.8.17; + +import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; +import { GenericSwapperB } from "lifi/Periphery/GenericSwapperB.sol"; +import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; +import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, UnAuthorized } from "lifi/Errors/GenericErrors.sol"; + +import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; + +// Stub GenericSwapFacet Contract +contract TestGenericSwapperB is GenericSwapperB { + constructor( + address _dexAggregatorAddress, + address _feeCollectorAddress, + address _adminAddress + ) + GenericSwapperB( + _dexAggregatorAddress, + _feeCollectorAddress, + _adminAddress + ) + {} + + function addDex(address _dex) external { + LibAllowList.addAllowedContract(_dex); + } + + function removeDex(address _dex) external { + LibAllowList.removeAllowedContract(_dex); + } + + function setFunctionApprovalBySignature(bytes4 _signature) external { + LibAllowList.addAllowedSelector(_signature); + } +} + +contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { + constructor(address _nativeAddress) GenericSwapFacetV3(_nativeAddress) {} + + function addDex(address _dex) external { + LibAllowList.addAllowedContract(_dex); + } + + function removeDex(address _dex) external { + LibAllowList.removeAllowedContract(_dex); + } + + function setFunctionApprovalBySignature(bytes4 _signature) external { + LibAllowList.addAllowedSelector(_signature); + } +} + +contract GenericSwapperBTest is TestHelpers { + // These values are for Mainnet + address internal constant USDC_HOLDER = + 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; + address internal constant DAI_HOLDER = + 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; + address internal constant USER_ADMIN = + 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; + + TestGenericSwapFacetV3 internal genericSwapFacetV3; + TestGenericSwapperB internal genericSwapper; + RouteProcessor4 internal routeProcessor; + + uint256 defaultMinAmountOutNativeToERC20 = 2991350294; + uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; + uint256 defaultMinAmountOutERC20ToERC20 = 99868787; + + function setUp() public { + customBlockNumberForForking = 20266387; + initTestBase(); + + diamond = createDiamond(); + routeProcessor = new RouteProcessor4(address(0), new address[](0)); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); + genericSwapper = new TestGenericSwapperB( + address(routeProcessor), + address(feeCollector), + USER_ADMIN + ); + + // add genericSwapFacet (v3) to diamond (for gas usage comparison) + bytes4[] memory functionSelectors = new bytes4[](9); + functionSelectors[0] = genericSwapFacetV3 + .swapTokensSingleV3ERC20ToERC20 + .selector; + functionSelectors[1] = genericSwapFacetV3 + .swapTokensSingleV3ERC20ToNative + .selector; + functionSelectors[2] = genericSwapFacetV3 + .swapTokensSingleV3NativeToERC20 + .selector; + functionSelectors[3] = genericSwapFacetV3 + .swapTokensMultipleV3ERC20ToERC20 + .selector; + functionSelectors[4] = genericSwapFacetV3 + .swapTokensMultipleV3ERC20ToNative + .selector; + functionSelectors[5] = genericSwapFacetV3 + .swapTokensMultipleV3NativeToERC20 + .selector; + functionSelectors[6] = genericSwapFacetV3.addDex.selector; + functionSelectors[7] = genericSwapFacetV3.removeDex.selector; + functionSelectors[8] = genericSwapFacetV3 + .setFunctionApprovalBySignature + .selector; + + // add v3 to diamond + // v4 will be standalone, so we dont add it here + addFacet(diamond, address(genericSwapFacetV3), functionSelectors); + genericSwapFacetV3 = TestGenericSwapFacetV3(address(diamond)); + + // whitelist dexAggregator dex with function selectors + // v3 + genericSwapFacetV3.addDex(address(routeProcessor)); + genericSwapFacetV3.setFunctionApprovalBySignature( + routeProcessor.processRoute.selector + ); + + // v4 + genericSwapper.addDex(address(routeProcessor)); + genericSwapper.setFunctionApprovalBySignature( + routeProcessor.processRoute.selector + ); + + // whitelist feeCollector with function selectors + // v3 + genericSwapFacetV3.addDex(address(feeCollector)); + genericSwapFacetV3.setFunctionApprovalBySignature( + feeCollector.collectTokenFees.selector + ); + genericSwapFacetV3.setFunctionApprovalBySignature( + feeCollector.collectNativeFees.selector + ); + // v4 + genericSwapper.addDex(address(feeCollector)); + genericSwapper.setFunctionApprovalBySignature( + feeCollector.collectTokenFees.selector + ); + genericSwapper.setFunctionApprovalBySignature( + feeCollector.collectNativeFees.selector + ); + + vm.label(address(genericSwapFacetV3), "GenericSwapV3 via Diamond"); + vm.label(address(genericSwapper), "GenericSwapV4"); + vm.label(address(routeProcessor), "RouteProcessor"); + vm.label(ADDRESS_WETH, "WETH_TOKEN"); + vm.label(ADDRESS_DAI, "DAI_TOKEN"); + vm.label(ADDRESS_USDC, "USDC_TOKEN"); + vm.label(ADDRESS_USDT, "USDT_TOKEN"); + vm.label(ADDRESS_UNISWAP, "ADDRESS_UNISWAP"); + } + + // SINGLE NATIVE TO ERC20 (ETH > USDC) + + function test_CanExecuteSingleSwapNativeToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call{ + value: defaultNativeAmount + }(_getGenericSwapCallDataSingle(true, SwapCase.NativeToERC20)); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteSingleSwapNativeToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call{ + value: defaultNativeAmount + }(_getGenericSwapCallDataSingle(false, SwapCase.NativeToERC20)); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // SINGLE ERC20 TO Native (USDC > ETH) + + function test_CanExecuteSingleSwapERC20ToNative_V3() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(32610177968847511) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToNative) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteSingleSwapERC20ToNative_V4() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToNative) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator + vm.startPrank(address(genericSwapper)); + usdc.approve(address(routeProcessor), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapper), defaultUSDCAmount); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call( + _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToNative) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // SINGLE ERC20 TO ERC20 (USDC > USDT) + + function test_CanExecuteSingleSwapERC20ToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToERC20) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteSingleSwapERC20ToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator + vm.startPrank(address(genericSwapper)); + usdc.approve(address(routeProcessor), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapper), defaultUSDCAmount); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call( + _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToERC20) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // FEE COLLECTION + SWAP NATIVE TO ERC20 (ETH > USDC) + + function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + vm.startPrank(USER_SENDER); + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call{ + value: defaultNativeAmount + defaultNativeFeeCollectionAmount + }( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.NativeToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDC, + USER_RECEIVER, + int256(defaultMinAmountOutNativeToERC20) + ) + { + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call{ + value: defaultNativeAmount + defaultNativeFeeCollectionAmount + }( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.NativeToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // FEE COLLECTION + SWAP ERC20 TO Native (USDC > ETH) + + function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V3() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(32610177968847511) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV3), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.ERC20ToNative + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V4() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToNative) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector + vm.startPrank(address(genericSwapper)); + usdc.approve(address(routeProcessor), type(uint256).max); + usdc.approve(address(feeCollector), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapper), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.ERC20ToNative + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + // FEE COLLECTION + SWAP ERC20 TO ERC20 (USDC > USDT) + + function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V3() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapFacetV3), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapFacetV3).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + true, + SwapCase.ERC20ToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V3", gasUsed); + } + + function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector + vm.startPrank(address(genericSwapper)); + usdc.approve(address(routeProcessor), type(uint256).max); + usdc.approve(address(feeCollector), type(uint256).max); + vm.stopPrank(); + + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapper), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + uint256 gasLeftBef = gasleft(); + + (bool success, ) = address(genericSwapper).call( + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.ERC20ToERC20 + ) + ); + if (!success) revert(); + + uint256 gasUsed = gasLeftBef - gasleft(); + console.log("gas used: V4", gasUsed); + } + + function test_AdminCanUpdateTokenApprovals() public { + assertEq( + usdc.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); + assertEq( + usdt.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); + + GenericSwapperB.TokenApproval[] + memory approvals = _getTokenApprovalsStruct(); + + vm.startPrank(USER_ADMIN); + genericSwapper.setApprovalForTokens(approvals); + + assertEq( + usdc.allowance(address(genericSwapper), address(routeProcessor)), + type(uint256).max + ); + assertEq( + usdc.allowance(address(genericSwapper), address(feeCollector)), + 0 + ); + assertEq( + usdt.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); + assertEq( + usdt.allowance(address(genericSwapper), address(feeCollector)), + type(uint256).max + ); + } + + function test_NonAdminCannotUpdateTokenApprovals() public { + GenericSwapperB.TokenApproval[] + memory approvals = _getTokenApprovalsStruct(); + + vm.startPrank(USER_SENDER); + + vm.expectRevert(UnAuthorized.selector); + + genericSwapper.setApprovalForTokens(approvals); + } + + // ------ HELPER FUNCTIONS + + function _getTokenApprovalsStruct() + internal + view + returns (GenericSwapperB.TokenApproval[] memory approvals) + { + approvals = new GenericSwapperB.TokenApproval[](2); + approvals[0].tokenAddress = ADDRESS_USDC; + approvals[0].maxApprovalToDexAggregator = true; + approvals[0].maxApprovalToFeeCollector = false; + + approvals[1].tokenAddress = ADDRESS_USDT; + approvals[1].maxApprovalToDexAggregator = false; + approvals[1].maxApprovalToFeeCollector = true; + } + + enum SwapCase { + NativeToERC20, + ERC20ToERC20, + ERC20ToNative + } + + function _getValidDexAggregatorCalldata( + bool isV3, + SwapCase swapCase + ) internal pure returns (bytes memory callData) { + if (swapCase == SwapCase.NativeToERC20) { + if (isV3) + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d8000000000000000000000000020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db041422600020C24B58c803c6e487a41D3Fd87788ef0bBdB2a0009c400000000000000000000000000000000"; + else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d80000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db0414226000000000000000000000000000000000abC6543210009c400000000000000000000000000000000"; + } + } + if (swapCase == SwapCase.ERC20ToERC20) { + if (isV3) + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005ec3e74000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f01020C24B58c803c6e487a41D3Fd87788ef0bBdB2a000bb8000000000000000000000000000000000000000000000000000000"; + else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005edbbbb0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f010000000000000000000000000000000abC654321000bb8000000000000000000000000000000000000000000000000000000"; + } + } + if (swapCase == SwapCase.ERC20ToNative) { + if (isV3) { + // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000000000000000000000000000000073467d7b86a48a000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff006E1fbeeABA87BAe1100d95f8340dc27aD7C8427b01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff0200020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000"; + } else { + // swapped tokens will be sent directly to USER_RECEIVER + return + hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000007378cf172f087a0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff00B4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff02000000000000000000000000000000000abC65432100000000000000000000000000"; + } + } + + // should not reach this code + revert(hex"dead"); + } + + function _getValidSingleSwapDataViaDexAggregator( + bool isV3, + SwapCase swapCase + ) internal view returns (LibSwap.SwapData memory swapData) { + ( + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount + ) = _getSwapDataParameters(swapCase); + + swapData = LibSwap.SwapData( + address(routeProcessor), + address(routeProcessor), + sendingAssetId, + receivingAssetId, + inputAmount, + _getValidDexAggregatorCalldata(isV3, swapCase), + swapCase == SwapCase.NativeToERC20 ? false : true + ); + } + + function _getValidMultiSwapData( + bool isV3, + SwapCase swapCase + ) internal view returns (LibSwap.SwapData[] memory swapData) { + ( + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount + ) = _getSwapDataParameters(swapCase); + + swapData = new LibSwap.SwapData[](2); + swapData[0] = _getFeeCollectorSwapData( + swapCase == SwapCase.NativeToERC20 ? true : false + ); + + swapData[1] = LibSwap.SwapData( + address(routeProcessor), + address(routeProcessor), + sendingAssetId, + receivingAssetId, + inputAmount, + _getValidDexAggregatorCalldata(isV3, swapCase), + false + ); + } + + function _getSwapDataParameters( + SwapCase swapCase + ) + internal + view + returns ( + address sendingAssetId, + address receivingAssetId, + uint256 inputAmount + ) + { + sendingAssetId = swapCase == SwapCase.NativeToERC20 + ? address(0) + : ADDRESS_USDC; + receivingAssetId = swapCase == SwapCase.ERC20ToNative + ? address(0) + : swapCase == SwapCase.ERC20ToERC20 + ? ADDRESS_USDT + : ADDRESS_USDC; + + inputAmount = swapCase == SwapCase.NativeToERC20 + ? defaultNativeAmount + : defaultUSDCAmount; + } + + function _getGenericSwapCallDataSingle( + bool isV3, + SwapCase swapCase + ) internal view returns (bytes memory callData) { + bytes4 selector = isV3 + ? swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV3.swapTokensSingleV3ERC20ToERC20.selector + : swapCase == SwapCase.ERC20ToNative + ? genericSwapFacetV3.swapTokensSingleV3ERC20ToNative.selector + : genericSwapFacetV3.swapTokensSingleV3NativeToERC20.selector + : swapCase == SwapCase.ERC20ToERC20 + ? genericSwapper.swapTokensSingleV3ERC20ToERC20.selector + : swapCase == SwapCase.ERC20ToNative + ? genericSwapper.swapTokensSingleV3ERC20ToNative.selector + : genericSwapper.swapTokensSingleV3NativeToERC20.selector; + + uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 + ? defaultMinAmountOutERC20ToERC20 + : swapCase == SwapCase.ERC20ToNative + ? defaultMinAmountOutERC20ToNative + : defaultMinAmountOutNativeToERC20; + + callData = _attachTransactionIdToCallData( + isV3 + ? abi.encodeWithSelector( + selector, + "", + "", + "", + payable(USER_RECEIVER), + minAmountOut, + _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) + ) + : abi.encodeWithSelector( + selector, + payable(USER_RECEIVER), + minAmountOut, + _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) + ) + ); + } + + function _getGenericSwapCallDataFeeCollectionPlusSwap( + bool isV3, + SwapCase swapCase + ) internal view returns (bytes memory callData) { + bytes4 selector = isV3 + ? swapCase == SwapCase.NativeToERC20 + ? genericSwapFacetV3.swapTokensMultipleV3NativeToERC20.selector + : swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV3.swapTokensMultipleV3ERC20ToERC20.selector + : genericSwapFacetV3.swapTokensMultipleV3ERC20ToNative.selector + : swapCase == SwapCase.NativeToERC20 + ? genericSwapper.swapTokensMultipleV3NativeToERC20.selector + : genericSwapper.swapTokensMultipleV3ERC20ToAny.selector; + + uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 + ? defaultMinAmountOutERC20ToERC20 + : swapCase == SwapCase.ERC20ToNative + ? defaultMinAmountOutERC20ToNative + : defaultMinAmountOutNativeToERC20; + + callData = _attachTransactionIdToCallData( + isV3 + ? abi.encodeWithSelector( + selector, + "", + "", + "", + payable(USER_RECEIVER), + minAmountOut, + _getValidMultiSwapData(isV3, swapCase) + ) + : abi.encodeWithSelector( + selector, + payable(USER_RECEIVER), + minAmountOut, + _getValidMultiSwapData(isV3, swapCase) + ) + ); + } + + function _attachTransactionIdToCallData( + bytes memory callData + ) internal pure returns (bytes memory adjustedCallData) { + bytes memory delimiter = hex"deadbeef"; + bytes memory transactionID = hex"513ae98e50764707a4a573b35df47051"; + + bytes memory mergedAppendix = mergeBytes(delimiter, transactionID); + + adjustedCallData = mergeBytes(callData, mergedAppendix); + } +} From 4764d00123556d1799d4cd238dca93d5e58d40b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 11 Jul 2024 10:23:40 +0700 Subject: [PATCH 09/11] docs added --- docs/GenericSwapper.md | 97 +++ src/Periphery/GenericSwapper.sol | 59 -- src/Periphery/GenericSwapperB.sol | 393 --------- test/solidity/Periphery/GenericSwapper.t.sol | 65 +- test/solidity/Periphery/GenericSwapperB.t.sol | 751 ------------------ 5 files changed, 141 insertions(+), 1224 deletions(-) create mode 100644 docs/GenericSwapper.md delete mode 100644 src/Periphery/GenericSwapperB.sol delete mode 100644 test/solidity/Periphery/GenericSwapperB.t.sol diff --git a/docs/GenericSwapper.md b/docs/GenericSwapper.md new file mode 100644 index 000000000..2a8e4a0cb --- /dev/null +++ b/docs/GenericSwapper.md @@ -0,0 +1,97 @@ +# GenericSwapper + +## Description + +Gas-optimized periphery contract used for executing same-chain swaps (incl. an optional fee collection step) + +## How To Use + +This contract was designed to provide a heavily gas-optimized way to execute same-chain swaps. It will not emit any events and it can only use the LI.FI DEX Aggregator to execute these swaps. Other DEXs are not supported. +It will also not check if token approvals from the GenericSwapper to the LI.FI DEX Aggregator and to the FeeCollector exist. If such approvals are missing, they would have to be set first (see function below). + +In order to still be able to trace transactions a `transactionId` will be appended to the calldata, separated from the actual calldata with a delimiter ('`0xdeadbeef`'). + +The contract has a number of specialized methods for various use cases: + +This method is used to execute a single swap from ERC20 to ERC20 + +```solidity + /// @notice Performs a single swap from an ERC20 token to another ERC20 token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToERC20( + address _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) +``` + +This method is used to execute a single swap from ERC20 to native + +```solidity + /// @notice Performs a single swap from an ERC20 token to the network's native token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3ERC20ToNative( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) +``` + +This method is used to execute a single swap from native to ERC20 + +```solidity + /// @notice Performs a single swap from the network's native token to ERC20 token + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensSingleV3NativeToERC20( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData calldata _swapData + ) +``` + +This method is used to execute a swap from ERC20 any other token (ERC20 or native) incl. a previous fee collection step + +```solidity + /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3ERC20ToAny( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) + +``` + +This method is used to execute a swap from native to ERC20 incl. a previous fee collection step + +```solidity + /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 + /// @param _receiver the address to receive the swapped tokens into (also excess tokens) + /// @param _minAmountOut the minimum amount of the final asset to receive + /// @param _swapData an object containing swap related data to perform swaps before bridging + function swapTokensMultipleV3NativeToERC20( + address payable _receiver, + uint256 _minAmountOut, + LibSwap.SwapData[] calldata _swapData + ) +``` + +This method is used to set max approvals between the GenericSwapper and the DEXAggregator as well as the FeeCollector +(it can only be called by the registered admin address) + +```solidity + /// @notice (Re-)Sets max approvals from this contract to DEX Aggregator and FeeCollector + /// @param _approvals The information which approvals to set for which token + function setApprovalForTokens( + TokenApproval[] calldata _approvals + ) + +``` diff --git a/src/Periphery/GenericSwapper.sol b/src/Periphery/GenericSwapper.sol index a2cc8ccb6..7dbe4f6b5 100644 --- a/src/Periphery/GenericSwapper.sol +++ b/src/Periphery/GenericSwapper.sol @@ -78,16 +78,10 @@ contract GenericSwapper is ILiFi { // SINGLE SWAPS /// @notice Performs a single swap from an ERC20 token to another ERC20 token - /// @param (unused)_transactionId the transaction id associated with the operation - /// @param (unused) _integrator the name of the integrator - /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3ERC20ToERC20( - bytes32, - string calldata, - string calldata, address _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData @@ -118,16 +112,10 @@ contract GenericSwapper is ILiFi { } /// @notice Performs a single swap from an ERC20 token to the network's native token - /// @param (unused)_transactionId the transaction id associated with the operation - /// @param (unused) _integrator the name of the integrator - /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3ERC20ToNative( - bytes32, - string calldata, - string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData @@ -159,16 +147,10 @@ contract GenericSwapper is ILiFi { } /// @notice Performs a single swap from the network's native token to ERC20 token - /// @param (unused)_transactionId the transaction id associated with the operation - /// @param (unused) _integrator the name of the integrator - /// @param (unused) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensSingleV3NativeToERC20( - bytes32, - string calldata, - string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData calldata _swapData @@ -194,45 +176,10 @@ contract GenericSwapper is ILiFi { // MULTIPLE SWAPS /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native - /// @param (*) _transactionId the transaction id associated with the operation - /// @param (*) _integrator the name of the integrator - /// @param (*) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensMultipleV3ERC20ToAny( - bytes32, - string calldata, - string calldata, - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) external onlyCallsToLiFiContracts(_swapData) { - // deposit token of first swap - LibSwap.SwapData calldata currentSwap = _swapData[0]; - - // check if a deposit is required - if (currentSwap.requiresDeposit) { - // we will not check msg.value as tx will fail anyway if not enough value available - // thus we only deposit ERC20 tokens here - currentSwap.sendingAssetId.safeTransferFrom( - msg.sender, - address(this), - currentSwap.fromAmount - ); - } - - uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); - - // make sure that minAmount was received - if (finalAmountOut < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); - } - - function swapTokensMultipleV3ERC20ToNative( - bytes32, - string calldata, - string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData @@ -259,16 +206,10 @@ contract GenericSwapper is ILiFi { } /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 - /// @param (*) _transactionId the transaction id associated with the operation - /// @param (*) _integrator the name of the integrator - /// @param (*) _referrer the address of the referrer /// @param _receiver the address to receive the swapped tokens into (also excess tokens) /// @param _minAmountOut the minimum amount of the final asset to receive /// @param _swapData an object containing swap related data to perform swaps before bridging function swapTokensMultipleV3NativeToERC20( - bytes32, - string calldata, - string calldata, address payable _receiver, uint256 _minAmountOut, LibSwap.SwapData[] calldata _swapData diff --git a/src/Periphery/GenericSwapperB.sol b/src/Periphery/GenericSwapperB.sol deleted file mode 100644 index e44985193..000000000 --- a/src/Periphery/GenericSwapperB.sol +++ /dev/null @@ -1,393 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.17; - -import { ILiFi } from "../Interfaces/ILiFi.sol"; -import { LibUtil } from "../Libraries/LibUtil.sol"; -import { LibSwap, IERC20 } from "../Libraries/LibSwap.sol"; -import { LibAllowList } from "../Libraries/LibAllowList.sol"; -import { LibAsset } from "../Libraries/LibAsset.sol"; -import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, InvalidCallData, UnAuthorized } from "../Errors/GenericErrors.sol"; -import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; - -/// @title GenericSwapper -/// @author LI.FI (https://li.fi) -/// @notice Provides gas-optimized functionality for fee collection and for swapping through any APPROVED DEX -/// @dev Can only execute calldata for APPROVED function selectors -/// @custom:version 1.0.0 -contract GenericSwapperB is ILiFi { - using SafeTransferLib for address; - - struct TokenApproval { - address tokenAddress; - bool maxApprovalToFeeCollector; // if true then a max approval will be set between this contract and LI.FI FeeCollector - bool maxApprovalToDexAggregator; // if true then a max approval will be set between this contract and the LI.FI DEX Aggregator - } - - /// Modifier /// - modifier onlyAdmin() { - if (msg.sender != adminAddress) revert UnAuthorized(); - _; - } - - /// Storage /// - - address public immutable dexAggregatorAddress; - address public immutable feeCollectorAddress; - address public immutable adminAddress; - - /// Constructor - - /// @notice Initialize the contract - /// @param _dexAggregatorAddress The address of the LI.FI DEX aggregator - /// @param _feeCollectorAddress The address of the LI.FI FeeCollector - /// @param _adminAddress The address of admin wallet (that can set token approvals) - constructor( - address _dexAggregatorAddress, - address _feeCollectorAddress, - address _adminAddress - ) { - dexAggregatorAddress = _dexAggregatorAddress; - feeCollectorAddress = _feeCollectorAddress; - adminAddress = _adminAddress; - } - - /// Modifier - modifier onlyCallsToDexAggregator(address callTo) { - if (callTo != dexAggregatorAddress) revert InvalidCallData(); - _; - } - - modifier onlyCallsToLiFiContracts(LibSwap.SwapData[] memory swapData) { - for (uint256 i; i < swapData.length; ) { - if ( - swapData[i].callTo != dexAggregatorAddress && - swapData[i].callTo != feeCollectorAddress - ) revert InvalidCallData(); - - // gas-efficient way to increase loop counter - unchecked { - ++i; - } - } - - _; - } - - /// External Methods /// - - // SINGLE SWAPS - - /// @notice Performs a single swap from an ERC20 token to another ERC20 token - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensSingleV3ERC20ToERC20( - address _receiver, - uint256 _minAmountOut, - LibSwap.SwapData calldata _swapData - ) external onlyCallsToDexAggregator(_swapData.callTo) { - address sendingAssetId = _swapData.sendingAssetId; - // deposit funds - sendingAssetId.safeTransferFrom( - msg.sender, - address(this), - _swapData.fromAmount - ); - - // execute swap - // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = _swapData.callTo.call( - _swapData.callData - ); - if (!success) { - LibUtil.revertWith(res); - } - - // make sure that minAmount was received - uint256 amountReceived = abi.decode(res, (uint256)); - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - - _returnPositiveSlippageERC20(sendingAssetId, _receiver); - } - - /// @notice Performs a single swap from an ERC20 token to the network's native token - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensSingleV3ERC20ToNative( - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData calldata _swapData - ) external onlyCallsToDexAggregator(_swapData.callTo) { - address sendingAssetId = _swapData.sendingAssetId; - - // deposit funds - sendingAssetId.safeTransferFrom( - msg.sender, - address(this), - _swapData.fromAmount - ); - - // execute swap - // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = _swapData.callTo.call( - _swapData.callData - ); - if (!success) { - LibUtil.revertWith(res); - } - - // make sure that minAmount was received - uint256 amountReceived = abi.decode(res, (uint256)); - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - - _returnPositiveSlippageNative(_receiver); - } - - /// @notice Performs a single swap from the network's native token to ERC20 token - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensSingleV3NativeToERC20( - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData calldata _swapData - ) external payable onlyCallsToDexAggregator(_swapData.callTo) { - // execute swap - // solhint-disable-next-line avoid-low-level-calls - (bool success, bytes memory res) = _swapData.callTo.call{ - value: msg.value - }(_swapData.callData); - if (!success) { - LibUtil.revertWith(res); - } - - // make sure that minAmount was received - uint256 amountReceived = abi.decode(res, (uint256)); - if (amountReceived < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, amountReceived); - - // return any positive slippage (i.e. unused sendingAsset tokens) - _returnPositiveSlippageNative(_receiver); - } - - // MULTIPLE SWAPS - - /// @notice Performs multiple swaps in one transaction, starting with ERC20 and ending with native - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensMultipleV3ERC20ToAny( - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) external onlyCallsToLiFiContracts(_swapData) { - // deposit token of first swap - LibSwap.SwapData calldata currentSwap = _swapData[0]; - - // check if a deposit is required - if (currentSwap.requiresDeposit) { - // we will not check msg.value as tx will fail anyway if not enough value available - // thus we only deposit ERC20 tokens here - currentSwap.sendingAssetId.safeTransferFrom( - msg.sender, - address(this), - currentSwap.fromAmount - ); - } - - uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); - - // make sure that minAmount was received - if (finalAmountOut < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); - } - - function swapTokensMultipleV3ERC20ToNative( - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) external onlyCallsToLiFiContracts(_swapData) { - // deposit token of first swap - LibSwap.SwapData calldata currentSwap = _swapData[0]; - - // check if a deposit is required - if (currentSwap.requiresDeposit) { - // we will not check msg.value as tx will fail anyway if not enough value available - // thus we only deposit ERC20 tokens here - currentSwap.sendingAssetId.safeTransferFrom( - msg.sender, - address(this), - currentSwap.fromAmount - ); - } - - uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); - - // make sure that minAmount was received - if (finalAmountOut < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); - } - - /// @notice Performs multiple swaps in one transaction, starting with native and ending with ERC20 - /// @param _receiver the address to receive the swapped tokens into (also excess tokens) - /// @param _minAmountOut the minimum amount of the final asset to receive - /// @param _swapData an object containing swap related data to perform swaps before bridging - function swapTokensMultipleV3NativeToERC20( - address payable _receiver, - uint256 _minAmountOut, - LibSwap.SwapData[] calldata _swapData - ) external payable onlyCallsToLiFiContracts(_swapData) { - uint256 finalAmountOut = _executeSwaps(_swapData, _receiver); - - // make sure that minAmount was received - if (finalAmountOut < _minAmountOut) - revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); - } - - /// @notice (Re-)Sets max approvals from this contract to DEX Aggregator and FeeCollector - /// @param _approvals The information which approvals to set for which token - function setApprovalForTokens( - TokenApproval[] calldata _approvals - ) external onlyAdmin { - address tokenAddress; - uint256 currentAllowance; - for (uint256 i; i < _approvals.length; ) { - tokenAddress = _approvals[i].tokenAddress; - - // if maxApprovalToDexAggregator==true, set max approval, otherwise set approval to 0 - // same for 'maxApprovalToFeeCollector' flag - - // update approval for DEX aggregator - if (_approvals[i].maxApprovalToDexAggregator) { - // if an allowance exists, set it to 0 first - currentAllowance = IERC20(tokenAddress).allowance( - address(this), - dexAggregatorAddress - ); - if ( - currentAllowance != 0 && - currentAllowance != type(uint256).max - ) tokenAddress.safeApprove(dexAggregatorAddress, 0); - - // set max approval - tokenAddress.safeApprove( - dexAggregatorAddress, - type(uint256).max - ); - } else tokenAddress.safeApprove(dexAggregatorAddress, 0); - - // update approval for FeeCollector - if (_approvals[i].maxApprovalToFeeCollector) { - // if an allowance exists, set it to 0 first - currentAllowance = IERC20(tokenAddress).allowance( - address(this), - feeCollectorAddress - ); - if ( - currentAllowance != 0 && - currentAllowance != type(uint256).max - ) tokenAddress.safeApprove(feeCollectorAddress, 0); - - // set max approval - tokenAddress.safeApprove( - feeCollectorAddress, - type(uint256).max - ); - } else tokenAddress.safeApprove(feeCollectorAddress, 0); - - // gas-efficient way to increase counter - unchecked { - ++i; - } - } - } - - /// Private helper methods /// - - // @dev: this function will not work with swapData that has multiple swaps with the same sendingAssetId - // as the _returnPositiveSlippage... functionality will refund all remaining tokens after the first swap - // We accept this fact since the use case is not common yet. As an alternative you can always use the - // "swapTokensGeneric" function of the original GenericSwapFacet - function _executeSwaps( - LibSwap.SwapData[] calldata _swapData, - address _receiver - ) private returns (uint256 finalAmountOut) { - // initialize variables before loop to save gas - address sendingAssetId; - address receivingAssetId; - LibSwap.SwapData calldata currentSwap; - bool success; - bytes memory returnData; - - // go through all swaps - for (uint256 i = 0; i < _swapData.length; ) { - currentSwap = _swapData[i]; - sendingAssetId = currentSwap.sendingAssetId; - receivingAssetId = currentSwap.receivingAssetId; - - // execute the swap - (success, returnData) = currentSwap.callTo.call{ - value: LibAsset.isNativeAsset(sendingAssetId) - ? currentSwap.fromAmount - : 0 - }(currentSwap.callData); - if (!success) { - LibUtil.revertWith(returnData); - } - - // check if this is the final swap - if (i == _swapData.length - 1) { - finalAmountOut = abi.decode(returnData, (uint256)); - } - - // return any potential leftover sendingAsset tokens - // but only for swaps, not for fee collections (otherwise the whole amount would be returned before the actual swap) - if (sendingAssetId != receivingAssetId) - if (LibAsset.isNativeAsset(sendingAssetId)) { - // Native - _returnPositiveSlippageNative(_receiver); - } else { - // ERC20 - _returnPositiveSlippageERC20(sendingAssetId, _receiver); - } - - unchecked { - ++i; - } - } - } - - // returns any unused 'sendingAsset' tokens (=> positive slippage) to the receiver address - function _returnPositiveSlippageERC20( - address sendingAsset, - address receiver - ) private { - // if a balance exists in sendingAsset, it must be positive slippage - if (address(sendingAsset) != address(0)) { - uint256 sendingAssetBalance = sendingAsset.balanceOf( - address(this) - ); - - if (sendingAssetBalance > 0) { - sendingAsset.safeTransfer(receiver, sendingAssetBalance); - } - } - } - - // returns any unused native tokens (=> positive slippage) to the receiver address - function _returnPositiveSlippageNative(address receiver) private { - // if a native balance exists in sendingAsset, it must be positive slippage - uint256 nativeBalance = address(this).balance; - - if (nativeBalance > 0) { - // solhint-disable-next-line avoid-low-level-calls - (bool success, ) = receiver.call{ value: nativeBalance }(""); - if (!success) revert NativeAssetTransferFailed(); - } - } - - receive() external payable {} -} diff --git a/test/solidity/Periphery/GenericSwapper.t.sol b/test/solidity/Periphery/GenericSwapper.t.sol index a9576199d..7c5bd6795 100644 --- a/test/solidity/Periphery/GenericSwapper.t.sol +++ b/test/solidity/Periphery/GenericSwapper.t.sol @@ -59,6 +59,7 @@ contract GenericSwapperTest is TestHelpers { 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; address internal constant USER_ADMIN = 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; + bytes constant CALLDATA_DELIMITER = hex"deadbeef"; TestGenericSwapFacetV3 internal genericSwapFacetV3; TestGenericSwapper internal genericSwapper; @@ -660,7 +661,13 @@ contract GenericSwapperTest is TestHelpers { bool isV3, SwapCase swapCase ) internal view returns (bytes memory callData) { - bytes4 selector = swapCase == SwapCase.ERC20ToERC20 + bytes4 selector = isV3 + ? swapCase == SwapCase.ERC20ToERC20 + ? genericSwapFacetV3.swapTokensSingleV3ERC20ToERC20.selector + : swapCase == SwapCase.ERC20ToNative + ? genericSwapFacetV3.swapTokensSingleV3ERC20ToNative.selector + : genericSwapFacetV3.swapTokensSingleV3NativeToERC20.selector + : swapCase == SwapCase.ERC20ToERC20 ? genericSwapper.swapTokensSingleV3ERC20ToERC20.selector : swapCase == SwapCase.ERC20ToNative ? genericSwapper.swapTokensSingleV3ERC20ToNative.selector @@ -673,15 +680,22 @@ contract GenericSwapperTest is TestHelpers { : defaultMinAmountOutNativeToERC20; callData = _attachTransactionIdToCallData( - abi.encodeWithSelector( - selector, - "", - "", - "", - payable(USER_RECEIVER), - minAmountOut, - _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) - ) + isV3 + ? abi.encodeWithSelector( + selector, + "", + "", + "", + payable(USER_RECEIVER), + minAmountOut, + _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) + ) + : abi.encodeWithSelector( + selector, + payable(USER_RECEIVER), + minAmountOut, + _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) + ) ); } @@ -706,25 +720,34 @@ contract GenericSwapperTest is TestHelpers { : defaultMinAmountOutNativeToERC20; callData = _attachTransactionIdToCallData( - abi.encodeWithSelector( - selector, - "", - "", - "", - payable(USER_RECEIVER), - minAmountOut, - _getValidMultiSwapData(isV3, swapCase) - ) + isV3 + ? abi.encodeWithSelector( + selector, + "", + "", + "", + payable(USER_RECEIVER), + minAmountOut, + _getValidMultiSwapData(isV3, swapCase) + ) + : abi.encodeWithSelector( + selector, + payable(USER_RECEIVER), + minAmountOut, + _getValidMultiSwapData(isV3, swapCase) + ) ); } function _attachTransactionIdToCallData( bytes memory callData ) internal pure returns (bytes memory adjustedCallData) { - bytes memory delimiter = hex"deadbeef"; bytes memory transactionID = hex"513ae98e50764707a4a573b35df47051"; - bytes memory mergedAppendix = mergeBytes(delimiter, transactionID); + bytes memory mergedAppendix = mergeBytes( + CALLDATA_DELIMITER, + transactionID + ); adjustedCallData = mergeBytes(callData, mergedAppendix); } diff --git a/test/solidity/Periphery/GenericSwapperB.t.sol b/test/solidity/Periphery/GenericSwapperB.t.sol deleted file mode 100644 index 10eedcc9b..000000000 --- a/test/solidity/Periphery/GenericSwapperB.t.sol +++ /dev/null @@ -1,751 +0,0 @@ -// SPDX-License-Identifier: Unlicense -pragma solidity 0.8.17; - -import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; -import { GenericSwapperB } from "lifi/Periphery/GenericSwapperB.sol"; -import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; -import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, UnAuthorized } from "lifi/Errors/GenericErrors.sol"; - -import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; - -// Stub GenericSwapFacet Contract -contract TestGenericSwapperB is GenericSwapperB { - constructor( - address _dexAggregatorAddress, - address _feeCollectorAddress, - address _adminAddress - ) - GenericSwapperB( - _dexAggregatorAddress, - _feeCollectorAddress, - _adminAddress - ) - {} - - function addDex(address _dex) external { - LibAllowList.addAllowedContract(_dex); - } - - function removeDex(address _dex) external { - LibAllowList.removeAllowedContract(_dex); - } - - function setFunctionApprovalBySignature(bytes4 _signature) external { - LibAllowList.addAllowedSelector(_signature); - } -} - -contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { - constructor(address _nativeAddress) GenericSwapFacetV3(_nativeAddress) {} - - function addDex(address _dex) external { - LibAllowList.addAllowedContract(_dex); - } - - function removeDex(address _dex) external { - LibAllowList.removeAllowedContract(_dex); - } - - function setFunctionApprovalBySignature(bytes4 _signature) external { - LibAllowList.addAllowedSelector(_signature); - } -} - -contract GenericSwapperBTest is TestHelpers { - // These values are for Mainnet - address internal constant USDC_HOLDER = - 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; - address internal constant DAI_HOLDER = - 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; - address internal constant USER_ADMIN = - 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; - - TestGenericSwapFacetV3 internal genericSwapFacetV3; - TestGenericSwapperB internal genericSwapper; - RouteProcessor4 internal routeProcessor; - - uint256 defaultMinAmountOutNativeToERC20 = 2991350294; - uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; - uint256 defaultMinAmountOutERC20ToERC20 = 99868787; - - function setUp() public { - customBlockNumberForForking = 20266387; - initTestBase(); - - diamond = createDiamond(); - routeProcessor = new RouteProcessor4(address(0), new address[](0)); - genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); - genericSwapper = new TestGenericSwapperB( - address(routeProcessor), - address(feeCollector), - USER_ADMIN - ); - - // add genericSwapFacet (v3) to diamond (for gas usage comparison) - bytes4[] memory functionSelectors = new bytes4[](9); - functionSelectors[0] = genericSwapFacetV3 - .swapTokensSingleV3ERC20ToERC20 - .selector; - functionSelectors[1] = genericSwapFacetV3 - .swapTokensSingleV3ERC20ToNative - .selector; - functionSelectors[2] = genericSwapFacetV3 - .swapTokensSingleV3NativeToERC20 - .selector; - functionSelectors[3] = genericSwapFacetV3 - .swapTokensMultipleV3ERC20ToERC20 - .selector; - functionSelectors[4] = genericSwapFacetV3 - .swapTokensMultipleV3ERC20ToNative - .selector; - functionSelectors[5] = genericSwapFacetV3 - .swapTokensMultipleV3NativeToERC20 - .selector; - functionSelectors[6] = genericSwapFacetV3.addDex.selector; - functionSelectors[7] = genericSwapFacetV3.removeDex.selector; - functionSelectors[8] = genericSwapFacetV3 - .setFunctionApprovalBySignature - .selector; - - // add v3 to diamond - // v4 will be standalone, so we dont add it here - addFacet(diamond, address(genericSwapFacetV3), functionSelectors); - genericSwapFacetV3 = TestGenericSwapFacetV3(address(diamond)); - - // whitelist dexAggregator dex with function selectors - // v3 - genericSwapFacetV3.addDex(address(routeProcessor)); - genericSwapFacetV3.setFunctionApprovalBySignature( - routeProcessor.processRoute.selector - ); - - // v4 - genericSwapper.addDex(address(routeProcessor)); - genericSwapper.setFunctionApprovalBySignature( - routeProcessor.processRoute.selector - ); - - // whitelist feeCollector with function selectors - // v3 - genericSwapFacetV3.addDex(address(feeCollector)); - genericSwapFacetV3.setFunctionApprovalBySignature( - feeCollector.collectTokenFees.selector - ); - genericSwapFacetV3.setFunctionApprovalBySignature( - feeCollector.collectNativeFees.selector - ); - // v4 - genericSwapper.addDex(address(feeCollector)); - genericSwapper.setFunctionApprovalBySignature( - feeCollector.collectTokenFees.selector - ); - genericSwapper.setFunctionApprovalBySignature( - feeCollector.collectNativeFees.selector - ); - - vm.label(address(genericSwapFacetV3), "GenericSwapV3 via Diamond"); - vm.label(address(genericSwapper), "GenericSwapV4"); - vm.label(address(routeProcessor), "RouteProcessor"); - vm.label(ADDRESS_WETH, "WETH_TOKEN"); - vm.label(ADDRESS_DAI, "DAI_TOKEN"); - vm.label(ADDRESS_USDC, "USDC_TOKEN"); - vm.label(ADDRESS_USDT, "USDT_TOKEN"); - vm.label(ADDRESS_UNISWAP, "ADDRESS_UNISWAP"); - } - - // SINGLE NATIVE TO ERC20 (ETH > USDC) - - function test_CanExecuteSingleSwapNativeToERC20_V3() - public - assertBalanceChange( - ADDRESS_USDC, - USER_RECEIVER, - int256(defaultMinAmountOutNativeToERC20) - ) - { - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call{ - value: defaultNativeAmount - }(_getGenericSwapCallDataSingle(true, SwapCase.NativeToERC20)); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteSingleSwapNativeToERC20_V4() - public - assertBalanceChange( - ADDRESS_USDC, - USER_RECEIVER, - int256(defaultMinAmountOutNativeToERC20) - ) - { - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call{ - value: defaultNativeAmount - }(_getGenericSwapCallDataSingle(false, SwapCase.NativeToERC20)); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - // SINGLE ERC20 TO Native (USDC > ETH) - - function test_CanExecuteSingleSwapERC20ToNative_V3() - public - assertBalanceChange( - address(0), - USER_RECEIVER, - int256(32610177968847511) - ) - { - vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call( - _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToNative) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteSingleSwapERC20ToNative_V4() - public - assertBalanceChange( - address(0), - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToNative) - ) - { - // ensure that max approval exists from GenericSwapFacet to DEX aggregator - vm.startPrank(address(genericSwapper)); - usdc.approve(address(routeProcessor), type(uint256).max); - vm.stopPrank(); - - vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapper), defaultUSDCAmount); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call( - _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToNative) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - // SINGLE ERC20 TO ERC20 (USDC > USDT) - - function test_CanExecuteSingleSwapERC20ToERC20_V3() - public - assertBalanceChange( - ADDRESS_USDT, - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToERC20) - ) - { - vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapFacetV3), defaultUSDCAmount); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call( - _getGenericSwapCallDataSingle(true, SwapCase.ERC20ToERC20) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteSingleSwapERC20ToERC20_V4() - public - assertBalanceChange( - ADDRESS_USDT, - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToERC20) - ) - { - // ensure that max approval exists from GenericSwapFacet to DEX aggregator - vm.startPrank(address(genericSwapper)); - usdc.approve(address(routeProcessor), type(uint256).max); - vm.stopPrank(); - - vm.startPrank(USER_SENDER); - usdc.approve(address(genericSwapper), defaultUSDCAmount); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call( - _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToERC20) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - // FEE COLLECTION + SWAP NATIVE TO ERC20 (ETH > USDC) - - function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V3() - public - assertBalanceChange( - ADDRESS_USDC, - USER_RECEIVER, - int256(defaultMinAmountOutNativeToERC20) - ) - { - vm.startPrank(USER_SENDER); - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call{ - value: defaultNativeAmount + defaultNativeFeeCollectionAmount - }( - _getGenericSwapCallDataFeeCollectionPlusSwap( - true, - SwapCase.NativeToERC20 - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteFeeCollectionPlusSwapNativeToERC20_V4() - public - assertBalanceChange( - ADDRESS_USDC, - USER_RECEIVER, - int256(defaultMinAmountOutNativeToERC20) - ) - { - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call{ - value: defaultNativeAmount + defaultNativeFeeCollectionAmount - }( - _getGenericSwapCallDataFeeCollectionPlusSwap( - false, - SwapCase.NativeToERC20 - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - // FEE COLLECTION + SWAP ERC20 TO Native (USDC > ETH) - - function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V3() - public - assertBalanceChange( - address(0), - USER_RECEIVER, - int256(32610177968847511) - ) - { - vm.startPrank(USER_SENDER); - usdc.approve( - address(genericSwapFacetV3), - defaultUSDCAmount + defaultUSDCFeeCollectionAmount - ); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call( - _getGenericSwapCallDataFeeCollectionPlusSwap( - true, - SwapCase.ERC20ToNative - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteFeeCollectionPlusSwapERC20ToNative_V4() - public - assertBalanceChange( - address(0), - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToNative) - ) - { - // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector - vm.startPrank(address(genericSwapper)); - usdc.approve(address(routeProcessor), type(uint256).max); - usdc.approve(address(feeCollector), type(uint256).max); - vm.stopPrank(); - - vm.startPrank(USER_SENDER); - usdc.approve( - address(genericSwapper), - defaultUSDCAmount + defaultUSDCFeeCollectionAmount - ); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call( - _getGenericSwapCallDataFeeCollectionPlusSwap( - false, - SwapCase.ERC20ToNative - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - // FEE COLLECTION + SWAP ERC20 TO ERC20 (USDC > USDT) - - function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V3() - public - assertBalanceChange( - ADDRESS_USDT, - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToERC20) - ) - { - vm.startPrank(USER_SENDER); - usdc.approve( - address(genericSwapFacetV3), - defaultUSDCAmount + defaultUSDCFeeCollectionAmount - ); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapFacetV3).call( - _getGenericSwapCallDataFeeCollectionPlusSwap( - true, - SwapCase.ERC20ToERC20 - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V3", gasUsed); - } - - function test_CanExecuteFeeCollectionPlusSwapERC20ToERC20_V4() - public - assertBalanceChange( - ADDRESS_USDT, - USER_RECEIVER, - int256(defaultMinAmountOutERC20ToERC20) - ) - { - // ensure that max approval exists from GenericSwapFacet to DEX aggregator and FeeCollector - vm.startPrank(address(genericSwapper)); - usdc.approve(address(routeProcessor), type(uint256).max); - usdc.approve(address(feeCollector), type(uint256).max); - vm.stopPrank(); - - vm.startPrank(USER_SENDER); - usdc.approve( - address(genericSwapper), - defaultUSDCAmount + defaultUSDCFeeCollectionAmount - ); - - uint256 gasLeftBef = gasleft(); - - (bool success, ) = address(genericSwapper).call( - _getGenericSwapCallDataFeeCollectionPlusSwap( - false, - SwapCase.ERC20ToERC20 - ) - ); - if (!success) revert(); - - uint256 gasUsed = gasLeftBef - gasleft(); - console.log("gas used: V4", gasUsed); - } - - function test_AdminCanUpdateTokenApprovals() public { - assertEq( - usdc.allowance(address(genericSwapper), address(routeProcessor)), - 0 - ); - assertEq( - usdt.allowance(address(genericSwapper), address(routeProcessor)), - 0 - ); - - GenericSwapperB.TokenApproval[] - memory approvals = _getTokenApprovalsStruct(); - - vm.startPrank(USER_ADMIN); - genericSwapper.setApprovalForTokens(approvals); - - assertEq( - usdc.allowance(address(genericSwapper), address(routeProcessor)), - type(uint256).max - ); - assertEq( - usdc.allowance(address(genericSwapper), address(feeCollector)), - 0 - ); - assertEq( - usdt.allowance(address(genericSwapper), address(routeProcessor)), - 0 - ); - assertEq( - usdt.allowance(address(genericSwapper), address(feeCollector)), - type(uint256).max - ); - } - - function test_NonAdminCannotUpdateTokenApprovals() public { - GenericSwapperB.TokenApproval[] - memory approvals = _getTokenApprovalsStruct(); - - vm.startPrank(USER_SENDER); - - vm.expectRevert(UnAuthorized.selector); - - genericSwapper.setApprovalForTokens(approvals); - } - - // ------ HELPER FUNCTIONS - - function _getTokenApprovalsStruct() - internal - view - returns (GenericSwapperB.TokenApproval[] memory approvals) - { - approvals = new GenericSwapperB.TokenApproval[](2); - approvals[0].tokenAddress = ADDRESS_USDC; - approvals[0].maxApprovalToDexAggregator = true; - approvals[0].maxApprovalToFeeCollector = false; - - approvals[1].tokenAddress = ADDRESS_USDT; - approvals[1].maxApprovalToDexAggregator = false; - approvals[1].maxApprovalToFeeCollector = true; - } - - enum SwapCase { - NativeToERC20, - ERC20ToERC20, - ERC20ToNative - } - - function _getValidDexAggregatorCalldata( - bool isV3, - SwapCase swapCase - ) internal pure returns (bytes memory callData) { - if (swapCase == SwapCase.NativeToERC20) { - if (isV3) - // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) - return - hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d8000000000000000000000000020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db041422600020C24B58c803c6e487a41D3Fd87788ef0bBdB2a0009c400000000000000000000000000000000"; - else { - // swapped tokens will be sent directly to USER_RECEIVER - return - hex"2646478b000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000002386f26fc10000000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000001ea36d80000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000700301ffff02012E8135bE71230c6B1B4045696d41C09Db0414226C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc204C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2002E8135bE71230c6B1B4045696d41C09Db0414226000000000000000000000000000000000abC6543210009c400000000000000000000000000000000"; - } - } - if (swapCase == SwapCase.ERC20ToERC20) { - if (isV3) - // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) - return - hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005ec3e74000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f01020C24B58c803c6e487a41D3Fd87788ef0bBdB2a000bb8000000000000000000000000000000000000000000000000000000"; - else { - // swapped tokens will be sent directly to USER_RECEIVER - return - hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000dac17f958d2ee523a2206206994597c13d831ec70000000000000000000000000000000000000000000000000000000005edbbbb0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000004502A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff003041CbD36888bECc7bbCBc0045E3B1f144466f5f010000000000000000000000000000000abC654321000bb8000000000000000000000000000000000000000000000000000000"; - } - } - if (swapCase == SwapCase.ERC20ToNative) { - if (isV3) { - // swapped tokens will be sent to diamond (and then forwarded to USER_RECEIVER by the facet) - return - hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000000000000000000000000000000073467d7b86a48a000000000000000000000000020c24b58c803c6e487a41d3fd87788ef0bbdb2a00000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff006E1fbeeABA87BAe1100d95f8340dc27aD7C8427b01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff0200020C24B58c803c6e487a41D3Fd87788ef0bBdB2a00000000000000000000000000"; - } else { - // swapped tokens will be sent directly to USER_RECEIVER - return - hex"2646478b000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000007378cf172f087a0000000000000000000000000000000000000000000000000000000abc65432100000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000007302A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB4801ffff00B4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc01F88d7F6357910E01e6e3A4f890B7Ca86471Eb6Ac000bb801C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc201ffff02000000000000000000000000000000000abC65432100000000000000000000000000"; - } - } - - // should not reach this code - revert(hex"dead"); - } - - function _getValidSingleSwapDataViaDexAggregator( - bool isV3, - SwapCase swapCase - ) internal view returns (LibSwap.SwapData memory swapData) { - ( - address sendingAssetId, - address receivingAssetId, - uint256 inputAmount - ) = _getSwapDataParameters(swapCase); - - swapData = LibSwap.SwapData( - address(routeProcessor), - address(routeProcessor), - sendingAssetId, - receivingAssetId, - inputAmount, - _getValidDexAggregatorCalldata(isV3, swapCase), - swapCase == SwapCase.NativeToERC20 ? false : true - ); - } - - function _getValidMultiSwapData( - bool isV3, - SwapCase swapCase - ) internal view returns (LibSwap.SwapData[] memory swapData) { - ( - address sendingAssetId, - address receivingAssetId, - uint256 inputAmount - ) = _getSwapDataParameters(swapCase); - - swapData = new LibSwap.SwapData[](2); - swapData[0] = _getFeeCollectorSwapData( - swapCase == SwapCase.NativeToERC20 ? true : false - ); - - swapData[1] = LibSwap.SwapData( - address(routeProcessor), - address(routeProcessor), - sendingAssetId, - receivingAssetId, - inputAmount, - _getValidDexAggregatorCalldata(isV3, swapCase), - false - ); - } - - function _getSwapDataParameters( - SwapCase swapCase - ) - internal - view - returns ( - address sendingAssetId, - address receivingAssetId, - uint256 inputAmount - ) - { - sendingAssetId = swapCase == SwapCase.NativeToERC20 - ? address(0) - : ADDRESS_USDC; - receivingAssetId = swapCase == SwapCase.ERC20ToNative - ? address(0) - : swapCase == SwapCase.ERC20ToERC20 - ? ADDRESS_USDT - : ADDRESS_USDC; - - inputAmount = swapCase == SwapCase.NativeToERC20 - ? defaultNativeAmount - : defaultUSDCAmount; - } - - function _getGenericSwapCallDataSingle( - bool isV3, - SwapCase swapCase - ) internal view returns (bytes memory callData) { - bytes4 selector = isV3 - ? swapCase == SwapCase.ERC20ToERC20 - ? genericSwapFacetV3.swapTokensSingleV3ERC20ToERC20.selector - : swapCase == SwapCase.ERC20ToNative - ? genericSwapFacetV3.swapTokensSingleV3ERC20ToNative.selector - : genericSwapFacetV3.swapTokensSingleV3NativeToERC20.selector - : swapCase == SwapCase.ERC20ToERC20 - ? genericSwapper.swapTokensSingleV3ERC20ToERC20.selector - : swapCase == SwapCase.ERC20ToNative - ? genericSwapper.swapTokensSingleV3ERC20ToNative.selector - : genericSwapper.swapTokensSingleV3NativeToERC20.selector; - - uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 - ? defaultMinAmountOutERC20ToERC20 - : swapCase == SwapCase.ERC20ToNative - ? defaultMinAmountOutERC20ToNative - : defaultMinAmountOutNativeToERC20; - - callData = _attachTransactionIdToCallData( - isV3 - ? abi.encodeWithSelector( - selector, - "", - "", - "", - payable(USER_RECEIVER), - minAmountOut, - _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) - ) - : abi.encodeWithSelector( - selector, - payable(USER_RECEIVER), - minAmountOut, - _getValidSingleSwapDataViaDexAggregator(isV3, swapCase) - ) - ); - } - - function _getGenericSwapCallDataFeeCollectionPlusSwap( - bool isV3, - SwapCase swapCase - ) internal view returns (bytes memory callData) { - bytes4 selector = isV3 - ? swapCase == SwapCase.NativeToERC20 - ? genericSwapFacetV3.swapTokensMultipleV3NativeToERC20.selector - : swapCase == SwapCase.ERC20ToERC20 - ? genericSwapFacetV3.swapTokensMultipleV3ERC20ToERC20.selector - : genericSwapFacetV3.swapTokensMultipleV3ERC20ToNative.selector - : swapCase == SwapCase.NativeToERC20 - ? genericSwapper.swapTokensMultipleV3NativeToERC20.selector - : genericSwapper.swapTokensMultipleV3ERC20ToAny.selector; - - uint256 minAmountOut = swapCase == SwapCase.ERC20ToERC20 - ? defaultMinAmountOutERC20ToERC20 - : swapCase == SwapCase.ERC20ToNative - ? defaultMinAmountOutERC20ToNative - : defaultMinAmountOutNativeToERC20; - - callData = _attachTransactionIdToCallData( - isV3 - ? abi.encodeWithSelector( - selector, - "", - "", - "", - payable(USER_RECEIVER), - minAmountOut, - _getValidMultiSwapData(isV3, swapCase) - ) - : abi.encodeWithSelector( - selector, - payable(USER_RECEIVER), - minAmountOut, - _getValidMultiSwapData(isV3, swapCase) - ) - ); - } - - function _attachTransactionIdToCallData( - bytes memory callData - ) internal pure returns (bytes memory adjustedCallData) { - bytes memory delimiter = hex"deadbeef"; - bytes memory transactionID = hex"513ae98e50764707a4a573b35df47051"; - - bytes memory mergedAppendix = mergeBytes(delimiter, transactionID); - - adjustedCallData = mergeBytes(callData, mergedAppendix); - } -} From e1cbcddcfa401d9a6bfd581f4b1dde25080217e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 11 Jul 2024 11:54:57 +0700 Subject: [PATCH 10/11] simplifies token approvals --- src/Periphery/GenericSwapper.sol | 124 +++++++++-------- test/solidity/Periphery/GenericSwapper.t.sol | 137 +++++++++++++------ 2 files changed, 161 insertions(+), 100 deletions(-) diff --git a/src/Periphery/GenericSwapper.sol b/src/Periphery/GenericSwapper.sol index 7dbe4f6b5..f47a8a39d 100644 --- a/src/Periphery/GenericSwapper.sol +++ b/src/Periphery/GenericSwapper.sol @@ -17,38 +17,19 @@ import { SafeTransferLib } from "solady/utils/SafeTransferLib.sol"; contract GenericSwapper is ILiFi { using SafeTransferLib for address; - struct TokenApproval { - address tokenAddress; - bool maxApprovalToFeeCollector; // if true then a max approval will be set between this contract and LI.FI FeeCollector - bool maxApprovalToDexAggregator; // if true then a max approval will be set between this contract and the LI.FI DEX Aggregator - } - - /// Modifier /// - modifier onlyAdmin() { - if (msg.sender != adminAddress) revert UnAuthorized(); - _; - } - /// Storage /// address public immutable dexAggregatorAddress; address public immutable feeCollectorAddress; - address public immutable adminAddress; /// Constructor /// @notice Initialize the contract /// @param _dexAggregatorAddress The address of the LI.FI DEX aggregator /// @param _feeCollectorAddress The address of the LI.FI FeeCollector - /// @param _adminAddress The address of admin wallet (that can set token approvals) - constructor( - address _dexAggregatorAddress, - address _feeCollectorAddress, - address _adminAddress - ) { + constructor(address _dexAggregatorAddress, address _feeCollectorAddress) { dexAggregatorAddress = _dexAggregatorAddress; feeCollectorAddress = _feeCollectorAddress; - adminAddress = _adminAddress; } /// Modifier @@ -221,56 +202,89 @@ contract GenericSwapper is ILiFi { revert CumulativeSlippageTooHigh(_minAmountOut, finalAmountOut); } - /// @notice (Re-)Sets max approvals from this contract to DEX Aggregator and FeeCollector - /// @param _approvals The information which approvals to set for which token + /// @notice Sets max approvals from this contract to DEX Aggregator and FeeCollector + /// @param _tokensToBeApproved The addresses of the tokens to be approved + /// @param _swapCallData The full calldata for the swap via this contract (e.g. swapTokensMultipleV3NativeToERC20(...)) + function setApprovalForTokensAndSwap( + address[] calldata _tokensToBeApproved, + bytes memory _swapCallData + ) external { + // set token approvals + setApprovalForTokens(_tokensToBeApproved); + + // execute swap on this contract using assembly for gas optimization purposes + assembly { + // Load the length of the callData + let callDataLength := mload(_swapCallData) + // Load the pointer to the callData + let callDataPointer := add(_swapCallData, 0x20) + + // Perform the delegatecall to itself + let result := delegatecall( + gas(), // Forward all available gas + address(), // Address of this contract + callDataPointer, // Pointer to the callData + callDataLength, // Length of the callData + 0, // Output location (none) + 0 // Output size (none) + ) + + // Check if the call was successful + if eq(result, 0) { + // Revert if the call failed + revert(0, 0) + } + } + } + + /// @notice Sets max approvals from this contract to DEX Aggregator and FeeCollector + /// @param _tokensToBeApproved The addresses of the tokens to be approved function setApprovalForTokens( - TokenApproval[] calldata _approvals - ) external onlyAdmin { - address tokenAddress; + address[] calldata _tokensToBeApproved + ) public { uint256 currentAllowance; - for (uint256 i; i < _approvals.length; ) { - tokenAddress = _approvals[i].tokenAddress; - - // if maxApprovalToDexAggregator==true, set max approval, otherwise set approval to 0 - // same for 'maxApprovalToFeeCollector' flag - + address tokenAddress; + for (uint256 i; i < _tokensToBeApproved.length; ) { + tokenAddress = _tokensToBeApproved[i]; // update approval for DEX aggregator - if (_approvals[i].maxApprovalToDexAggregator) { - // if an allowance exists, set it to 0 first - currentAllowance = IERC20(tokenAddress).allowance( - address(this), - dexAggregatorAddress - ); - if ( - currentAllowance != 0 && - currentAllowance != type(uint256).max - ) tokenAddress.safeApprove(dexAggregatorAddress, 0); + // check current allowance + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + dexAggregatorAddress + ); + + // check if existing allowance is max + if (currentAllowance != type(uint256).max) { + if (currentAllowance != 0) + // if a non-max allowance exists, reset to 0 first + tokenAddress.safeApprove(dexAggregatorAddress, 0); - // set max approval + // set to max tokenAddress.safeApprove( dexAggregatorAddress, type(uint256).max ); - } else tokenAddress.safeApprove(dexAggregatorAddress, 0); + } // update approval for FeeCollector - if (_approvals[i].maxApprovalToFeeCollector) { - // if an allowance exists, set it to 0 first - currentAllowance = IERC20(tokenAddress).allowance( - address(this), - feeCollectorAddress - ); - if ( - currentAllowance != 0 && - currentAllowance != type(uint256).max - ) tokenAddress.safeApprove(feeCollectorAddress, 0); + // check current allowance + currentAllowance = IERC20(tokenAddress).allowance( + address(this), + feeCollectorAddress + ); + + // check if existing allowance is max + if (currentAllowance != type(uint256).max) { + if (currentAllowance != 0) + // if a non-max allowance exists, reset to 0 first + tokenAddress.safeApprove(feeCollectorAddress, 0); - // set max approval + // set to max tokenAddress.safeApprove( feeCollectorAddress, type(uint256).max ); - } else tokenAddress.safeApprove(feeCollectorAddress, 0); + } // gas-efficient way to increase counter unchecked { diff --git a/test/solidity/Periphery/GenericSwapper.t.sol b/test/solidity/Periphery/GenericSwapper.t.sol index 7c5bd6795..77c5bc773 100644 --- a/test/solidity/Periphery/GenericSwapper.t.sol +++ b/test/solidity/Periphery/GenericSwapper.t.sol @@ -12,15 +12,8 @@ import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibA contract TestGenericSwapper is GenericSwapper { constructor( address _dexAggregatorAddress, - address _feeCollectorAddress, - address _adminAddress - ) - GenericSwapper( - _dexAggregatorAddress, - _feeCollectorAddress, - _adminAddress - ) - {} + address _feeCollectorAddress + ) GenericSwapper(_dexAggregatorAddress, _feeCollectorAddress) {} function addDex(address _dex) external { LibAllowList.addAllowedContract(_dex); @@ -52,11 +45,20 @@ contract TestGenericSwapFacetV3 is GenericSwapFacetV3 { } contract GenericSwapperTest is TestHelpers { + event Route( + address indexed from, + address to, + address indexed tokenIn, + address indexed tokenOut, + uint256 amountIn, + uint256 amountOutMin, + uint256 amountOut + ); + // These values are for Mainnet - address internal constant USDC_HOLDER = - 0x4B16c5dE96EB2117bBE5fd171E4d203624B014aa; - address internal constant DAI_HOLDER = - 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf; + + address internal constant ROUTE_PROCESSOR_NATIVE_ADDRESS = + 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant USER_ADMIN = 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; bytes constant CALLDATA_DELIMITER = hex"deadbeef"; @@ -68,6 +70,7 @@ contract GenericSwapperTest is TestHelpers { uint256 defaultMinAmountOutNativeToERC20 = 2991350294; uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; uint256 defaultMinAmountOutERC20ToERC20 = 99868787; + uint256 actualAmpountOutERC20ToERC20 = 99868787; function setUp() public { customBlockNumberForForking = 20266387; @@ -78,8 +81,7 @@ contract GenericSwapperTest is TestHelpers { genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); genericSwapper = new TestGenericSwapper( address(routeProcessor), - address(feeCollector), - USER_ADMIN + address(feeCollector) ); // add genericSwapFacet (v3) to diamond (for gas usage comparison) @@ -245,6 +247,34 @@ contract GenericSwapperTest is TestHelpers { console.log("gas used: V4", gasUsed); } + function test_CanSetApprovalsAndExecuteSingleSwapERC20ToNative_V4() + public + assertBalanceChange( + address(0), + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToNative) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve(address(genericSwapper), defaultUSDCAmount); + + vm.expectEmit(true, true, true, true, address(routeProcessor)); + emit Route( + address(genericSwapper), + USER_RECEIVER, + ADDRESS_USDC, + ROUTE_PROCESSOR_NATIVE_ADDRESS, + defaultUSDCAmount, + 32502453164247162, // AmountOut determined by processRoute calldata + defaultMinAmountOutERC20ToNative + ); + + genericSwapper.setApprovalForTokensAndSwap( + _getTokenApprovals(), + _getGenericSwapCallDataSingle(false, SwapCase.ERC20ToNative) + ); + } + // SINGLE ERC20 TO ERC20 (USDC > USDT) function test_CanExecuteSingleSwapERC20ToERC20_V3() @@ -475,6 +505,40 @@ contract GenericSwapperTest is TestHelpers { console.log("gas used: V4", gasUsed); } + function test_CanSetApprovalsAndExecuteFeeCollectionPlusSwapERC20ToERC20_V4() + public + assertBalanceChange( + ADDRESS_USDT, + USER_RECEIVER, + int256(defaultMinAmountOutERC20ToERC20) + ) + { + vm.startPrank(USER_SENDER); + usdc.approve( + address(genericSwapper), + defaultUSDCAmount + defaultUSDCFeeCollectionAmount + ); + + vm.expectEmit(true, true, true, true, address(routeProcessor)); + emit Route( + address(genericSwapper), + USER_RECEIVER, + ADDRESS_USDC, + ADDRESS_USDT, + defaultUSDCAmount, + 99466171, // AmountOut determined by processRoute calldata + defaultMinAmountOutERC20ToERC20 + ); + + genericSwapper.setApprovalForTokensAndSwap( + _getTokenApprovals(), + _getGenericSwapCallDataFeeCollectionPlusSwap( + false, + SwapCase.ERC20ToERC20 + ) + ); + } + function test_AdminCanUpdateTokenApprovals() public { assertEq( usdc.allowance(address(genericSwapper), address(routeProcessor)), @@ -484,9 +548,12 @@ contract GenericSwapperTest is TestHelpers { usdt.allowance(address(genericSwapper), address(routeProcessor)), 0 ); + assertEq( + dai.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); - GenericSwapper.TokenApproval[] - memory approvals = _getTokenApprovalsStruct(); + address[] memory approvals = _getTokenApprovals(); vm.startPrank(USER_ADMIN); genericSwapper.setApprovalForTokens(approvals); @@ -496,45 +563,25 @@ contract GenericSwapperTest is TestHelpers { type(uint256).max ); assertEq( - usdc.allowance(address(genericSwapper), address(feeCollector)), - 0 + usdt.allowance(address(genericSwapper), address(feeCollector)), + type(uint256).max ); assertEq( - usdt.allowance(address(genericSwapper), address(routeProcessor)), + dai.allowance(address(genericSwapper), address(feeCollector)), 0 ); - assertEq( - usdt.allowance(address(genericSwapper), address(feeCollector)), - type(uint256).max - ); - } - - function test_NonAdminCannotUpdateTokenApprovals() public { - GenericSwapper.TokenApproval[] - memory approvals = _getTokenApprovalsStruct(); - - vm.startPrank(USER_SENDER); - - vm.expectRevert(UnAuthorized.selector); - - genericSwapper.setApprovalForTokens(approvals); } // ------ HELPER FUNCTIONS - function _getTokenApprovalsStruct() + function _getTokenApprovals() internal view - returns (GenericSwapper.TokenApproval[] memory approvals) + returns (address[] memory approvals) { - approvals = new GenericSwapper.TokenApproval[](2); - approvals[0].tokenAddress = ADDRESS_USDC; - approvals[0].maxApprovalToDexAggregator = true; - approvals[0].maxApprovalToFeeCollector = false; - - approvals[1].tokenAddress = ADDRESS_USDT; - approvals[1].maxApprovalToDexAggregator = false; - approvals[1].maxApprovalToFeeCollector = true; + approvals = new address[](2); + approvals[0] = ADDRESS_USDC; + approvals[1] = ADDRESS_USDT; } enum SwapCase { From 6337197b51d680c14291b2b9ea68b4f9facc167e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Bl=C3=A4cker?= Date: Thu, 11 Jul 2024 12:02:11 +0700 Subject: [PATCH 11/11] renames RouteProcessor4 to LiFiDEXAggregator --- .../deploy/facets/DeployGenericSwapper.s.sol | 37 +++++++++++++++++++ .../deploy/resources/deployRequirements.json | 11 ++++++ ...teProcessor4.sol => LiFiDEXAggregator.sol} | 3 +- test/solidity/Periphery/GenericSwapper.t.sol | 6 +-- 4 files changed, 52 insertions(+), 5 deletions(-) create mode 100644 script/deploy/facets/DeployGenericSwapper.s.sol rename src/Periphery/{RouteProcessor4.sol => LiFiDEXAggregator.sol} (99%) diff --git a/script/deploy/facets/DeployGenericSwapper.s.sol b/script/deploy/facets/DeployGenericSwapper.s.sol new file mode 100644 index 000000000..53c9e0462 --- /dev/null +++ b/script/deploy/facets/DeployGenericSwapper.s.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.17; + +import { DeployScriptBase } from "./utils/DeployScriptBase.sol"; +import { stdJson } from "forge-std/Script.sol"; +import { GenericSwapper } from "lifi/Periphery/GenericSwapper.sol"; + +contract DeployScript is DeployScriptBase { + using stdJson for string; + + constructor() DeployScriptBase("GenericSwapper") {} + + function run() + public + returns (GenericSwapper deployed, bytes memory constructorArgs) + { + constructorArgs = getConstructorArgs(); + + deployed = GenericSwapper(deploy(type(GenericSwapper).creationCode)); + } + + function getConstructorArgs() internal override returns (bytes memory) { + string memory path = string.concat( + root, + "/deployments/", + network, + ".", + fileSuffix, + "json" + ); + string memory json = vm.readFile(path); + address dexAggregatorAddress = json.readAddress(".LiFiDEXAggregator"); + address feeCollectorAddress = json.readAddress(".FeeCollector"); + + return abi.encode(dexAggregatorAddress, feeCollectorAddress); + } +} diff --git a/script/deploy/resources/deployRequirements.json b/script/deploy/resources/deployRequirements.json index 49cff1354..c49310c32 100644 --- a/script/deploy/resources/deployRequirements.json +++ b/script/deploy/resources/deployRequirements.json @@ -413,6 +413,17 @@ } } }, + "GenericSwapper": { + "configData": { + "contractAddresses": { + "FeeCollector": { + "allowToDeployWithZeroAddress": "false" + }, + "LiFiDEXAggregator": { + "allowToDeployWithZeroAddress": "false" + } + } + }, "FeeCollector": { "configData": { "_owner": { diff --git a/src/Periphery/RouteProcessor4.sol b/src/Periphery/LiFiDEXAggregator.sol similarity index 99% rename from src/Periphery/RouteProcessor4.sol rename to src/Periphery/LiFiDEXAggregator.sol index dad801826..bb40898e5 100644 --- a/src/Periphery/RouteProcessor4.sol +++ b/src/Periphery/LiFiDEXAggregator.sol @@ -4,7 +4,6 @@ pragma solidity ^0.8.17; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; -import { console2 } from "forge-std/console2.sol"; address constant NATIVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address constant IMPOSSIBLE_POOL_ADDRESS = 0x0000000000000000000000000000000000000001; @@ -22,7 +21,7 @@ uint160 constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970 /// @title A route processor for the Sushi Aggregator /// @author Ilya Lyalin -contract RouteProcessor4 is Ownable { +contract LiFiDEXAggregator is Ownable { using SafeERC20 for IERC20; using Approve for IERC20; using SafeERC20 for IERC20Permit; diff --git a/test/solidity/Periphery/GenericSwapper.t.sol b/test/solidity/Periphery/GenericSwapper.t.sol index 77c5bc773..03b12468a 100644 --- a/test/solidity/Periphery/GenericSwapper.t.sol +++ b/test/solidity/Periphery/GenericSwapper.t.sol @@ -3,7 +3,7 @@ pragma solidity 0.8.17; import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; import { GenericSwapper } from "lifi/Periphery/GenericSwapper.sol"; -import { RouteProcessor4 } from "lifi/Periphery/RouteProcessor4.sol"; +import { LiFiDEXAggregator } from "lifi/Periphery/LiFiDEXAggregator.sol"; import { ContractCallNotAllowed, CumulativeSlippageTooHigh, NativeAssetTransferFailed, UnAuthorized } from "lifi/Errors/GenericErrors.sol"; import { TestHelpers, MockUniswapDEX, NonETHReceiver, LiFiDiamond, LibSwap, LibAllowList, ERC20, console } from "../utils/TestHelpers.sol"; @@ -65,7 +65,7 @@ contract GenericSwapperTest is TestHelpers { TestGenericSwapFacetV3 internal genericSwapFacetV3; TestGenericSwapper internal genericSwapper; - RouteProcessor4 internal routeProcessor; + LiFiDEXAggregator internal routeProcessor; uint256 defaultMinAmountOutNativeToERC20 = 2991350294; uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; @@ -77,7 +77,7 @@ contract GenericSwapperTest is TestHelpers { initTestBase(); diamond = createDiamond(); - routeProcessor = new RouteProcessor4(address(0), new address[](0)); + routeProcessor = new LiFiDEXAggregator(address(0), new address[](0)); genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); genericSwapper = new TestGenericSwapper( address(routeProcessor),