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/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/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/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/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/src/Periphery/GenericSwapper.sol b/src/Periphery/GenericSwapper.sol new file mode 100644 index 000000000..f47a8a39d --- /dev/null +++ b/src/Periphery/GenericSwapper.sol @@ -0,0 +1,381 @@ +// 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 GenericSwapper is ILiFi { + using SafeTransferLib for address; + + /// Storage /// + + address public immutable dexAggregatorAddress; + address public immutable feeCollectorAddress; + + /// Constructor + + /// @notice Initialize the contract + /// @param _dexAggregatorAddress The address of the LI.FI DEX aggregator + /// @param _feeCollectorAddress The address of the LI.FI FeeCollector + constructor(address _dexAggregatorAddress, address _feeCollectorAddress) { + dexAggregatorAddress = _dexAggregatorAddress; + feeCollectorAddress = _feeCollectorAddress; + } + + /// 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); + } + + /// @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 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( + address[] calldata _tokensToBeApproved + ) public { + uint256 currentAllowance; + address tokenAddress; + for (uint256 i; i < _tokensToBeApproved.length; ) { + tokenAddress = _tokensToBeApproved[i]; + // update approval for DEX aggregator + // 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 to max + tokenAddress.safeApprove( + dexAggregatorAddress, + type(uint256).max + ); + } + + // update approval for FeeCollector + // 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 to max + tokenAddress.safeApprove( + feeCollectorAddress, + type(uint256).max + ); + } + + // 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/src/Periphery/LiFiDEXAggregator.sol b/src/Periphery/LiFiDEXAggregator.sol new file mode 100644 index 000000000..bb40898e5 --- /dev/null +++ b/src/Periphery/LiFiDEXAggregator.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 LiFiDEXAggregator 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/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..da4f8685a 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); } @@ -47,69 +48,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); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); feeCollector = FeeCollector(FEE_COLLECTOR); // add genericSwapFacet (v1) to diamond (for gas usage comparison) @@ -197,10 +160,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 +175,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 +189,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 +226,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 +285,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 +329,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 +406,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 +447,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 +474,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 +488,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 +523,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 +566,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 +677,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 +727,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 +742,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 +771,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 +805,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 +833,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 +895,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 +935,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 +949,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 +965,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 +975,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 +1011,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 +1055,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 +1141,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 +1193,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 +1234,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 +1249,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 +1263,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 +1273,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 +1305,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 +1340,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 +1449,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 +1466,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 +1479,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 +1513,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 +1558,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 +1618,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 +1632,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 +1662,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 +1697,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 +1741,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 +1758,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 +1771,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 +1807,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 +1844,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 +1910,7 @@ contract GenericSwapFacetV3Test is DSTest, DiamondTest, TestHelpers { // get swapData ( LibSwap.SwapData[] memory swapData, - uint256 amountIn, + , uint256 minAmountOut ) = _produceSwapDataMultiswapERC20FeeAndSwapToNative( address(genericSwapFacetV3) @@ -1982,14 +1945,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 +2013,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 +2032,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 +2095,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 +2153,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/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); 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/GenericSwapper.t.sol b/test/solidity/Periphery/GenericSwapper.t.sol new file mode 100644 index 000000000..03b12468a --- /dev/null +++ b/test/solidity/Periphery/GenericSwapper.t.sol @@ -0,0 +1,801 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity 0.8.17; + +import { GenericSwapFacetV3 } from "lifi/Facets/GenericSwapFacetV3.sol"; +import { GenericSwapper } from "lifi/Periphery/GenericSwapper.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"; + +// Stub GenericSwapFacet Contract +contract TestGenericSwapper is GenericSwapper { + constructor( + address _dexAggregatorAddress, + address _feeCollectorAddress + ) GenericSwapper(_dexAggregatorAddress, _feeCollectorAddress) {} + + 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 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 ROUTE_PROCESSOR_NATIVE_ADDRESS = + 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; + address internal constant USER_ADMIN = + 0x552008c0f6870c2f77e5cC1d2eb9bdff03e30Ea0; + bytes constant CALLDATA_DELIMITER = hex"deadbeef"; + + TestGenericSwapFacetV3 internal genericSwapFacetV3; + TestGenericSwapper internal genericSwapper; + LiFiDEXAggregator internal routeProcessor; + + uint256 defaultMinAmountOutNativeToERC20 = 2991350294; + uint256 defaultMinAmountOutERC20ToNative = 32539678644151061; + uint256 defaultMinAmountOutERC20ToERC20 = 99868787; + uint256 actualAmpountOutERC20ToERC20 = 99868787; + + function setUp() public { + customBlockNumberForForking = 20266387; + initTestBase(); + + diamond = createDiamond(); + routeProcessor = new LiFiDEXAggregator(address(0), new address[](0)); + genericSwapFacetV3 = new TestGenericSwapFacetV3(address(0)); + genericSwapper = new TestGenericSwapper( + address(routeProcessor), + address(feeCollector) + ); + + // 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); + } + + 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() + 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_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)), + 0 + ); + assertEq( + usdt.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); + assertEq( + dai.allowance(address(genericSwapper), address(routeProcessor)), + 0 + ); + + address[] memory approvals = _getTokenApprovals(); + + vm.startPrank(USER_ADMIN); + genericSwapper.setApprovalForTokens(approvals); + + assertEq( + usdc.allowance(address(genericSwapper), address(routeProcessor)), + type(uint256).max + ); + assertEq( + usdt.allowance(address(genericSwapper), address(feeCollector)), + type(uint256).max + ); + assertEq( + dai.allowance(address(genericSwapper), address(feeCollector)), + 0 + ); + } + + // ------ HELPER FUNCTIONS + + function _getTokenApprovals() + internal + view + returns (address[] memory approvals) + { + approvals = new address[](2); + approvals[0] = ADDRESS_USDC; + approvals[1] = ADDRESS_USDT; + } + + 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 transactionID = hex"513ae98e50764707a4a573b35df47051"; + + bytes memory mergedAppendix = mergeBytes( + CALLDATA_DELIMITER, + transactionID + ); + + adjustedCallData = mergeBytes(callData, mergedAppendix); + } +} 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..597604ca2 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,84 @@ 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 + defaultNativeFeeCollectionAmount + : defaultUSDCAmount + defaultUSDCFeeCollectionAmount, + 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 { diff --git a/tmpfile b/tmpfile new file mode 100644 index 000000000..e69de29bb