File size: 21,892 Bytes
f998fcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
  "language": "Solidity",
  "sources": {
    "contracts/swapHandlers/SwapHandlerUniAutoRouter.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\nimport \"./SwapHandlerCombinedBase.sol\";\n\n/// @notice Swap handler executing trades on Uniswap with a payload generated by auto-router\ncontract SwapHandlerUniAutoRouter is SwapHandlerCombinedBase {\n    address immutable public uniSwapRouter02;\n\n    constructor(address uniSwapRouter02_, address uniSwapRouterV2, address uniSwapRouterV3) SwapHandlerCombinedBase(uniSwapRouterV2, uniSwapRouterV3) {\n        uniSwapRouter02 = uniSwapRouter02_;\n    }\n\n    function swapPrimary(SwapParams memory params) override internal returns (uint amountOut) {\n        setMaxAllowance(params.underlyingIn, params.amountIn, uniSwapRouter02);\n\n        if (params.mode == 0) {\n            // for exact input return value is ignored\n            swapInternal(params);\n        } else {\n            // exact output on SwapRouter02 routed through uniV2 is not exact, balance check is needed\n            uint preBalance = IERC20(params.underlyingOut).balanceOf(msg.sender);\n\n            swapInternal(params);\n\n            uint postBalance = IERC20(params.underlyingOut).balanceOf(msg.sender);\n\n            require(postBalance >= preBalance, \"SwapHandlerUniAutoRouter: negative amount out\");\n\n            unchecked { amountOut = postBalance - preBalance; }\n        }\n    }\n\n    function swapInternal(SwapParams memory params) private {\n        (bool success, bytes memory result) = uniSwapRouter02.call(params.payload);\n        if (!success) revertBytes(result);\n    }\n}\n"
    },
    "contracts/swapHandlers/SwapHandlerCombinedBase.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\nimport \"./SwapHandlerBase.sol\";\nimport \"../vendor/ISwapRouterV3.sol\";\nimport \"../vendor/ISwapRouterV2.sol\";\n\n/// @notice Base contract for swap handlers which execute a secondary swap on Uniswap V2 or V3 for exact output\nabstract contract SwapHandlerCombinedBase is SwapHandlerBase {\n    address immutable public uniSwapRouterV2;\n    address immutable public uniSwapRouterV3;\n\n    constructor(address uniSwapRouterV2_, address uniSwapRouterV3_) {\n        uniSwapRouterV2 = uniSwapRouterV2_;\n        uniSwapRouterV3 = uniSwapRouterV3_;\n    }\n\n    function executeSwap(SwapParams memory params) external override {\n        require(params.mode <= 1, \"SwapHandlerCombinedBase: invalid mode\");\n\n        if (params.mode == 0) {\n            swapPrimary(params);\n        } else {\n            // For exact output expect a payload for the primary swap provider and a path to swap the remainder on Uni2 or Uni3\n            bytes memory path;\n            (params.payload, path) = abi.decode(params.payload, (bytes, bytes));\n\n            uint primaryAmountOut = swapPrimary(params);\n\n            if (primaryAmountOut < params.amountOut) {\n                // The path param is reused for UniV2 and UniV3 swaps. The protocol to use is determined by the path length.\n                // The length of valid UniV2 paths is given as n * 20, for n > 1, and the shortes path is 40 bytes.\n                // The length of valid UniV3 paths is given as 20 + n * 23 for n > 0, because of an additional 3 bytes for the pool fee.\n                // The max path length must be lower than the first path length which is valid for both protocols (and is therefore ambiguous)\n                // This value is at 20 UniV3 hops, which corresponds to 24 UniV2 hops.\n                require(path.length >= 40 && path.length < 20 + (20 * 23), \"SwapHandlerPayloadBase: secondary path format\");\n\n                uint remainder;\n                unchecked { remainder = params.amountOut - primaryAmountOut; }\n\n                swapExactOutDirect(params, remainder, path);\n            }\n        }\n\n        transferBack(params.underlyingIn);\n    }\n\n    function swapPrimary(SwapParams memory params) internal virtual returns (uint amountOut);\n\n    function swapExactOutDirect(SwapParams memory params, uint amountOut, bytes memory path) private {\n        (bool isUniV2, address[] memory uniV2Path) = detectAndDecodeUniV2Path(path);\n\n        if (isUniV2) {\n            setMaxAllowance(params.underlyingIn, params.amountIn, uniSwapRouterV2);\n\n            ISwapRouterV2(uniSwapRouterV2).swapTokensForExactTokens(amountOut, type(uint).max, uniV2Path, msg.sender, block.timestamp);\n        } else {\n            setMaxAllowance(params.underlyingIn, params.amountIn, uniSwapRouterV3);\n\n            ISwapRouterV3(uniSwapRouterV3).exactOutput(\n                ISwapRouterV3.ExactOutputParams({\n                    path: path,\n                    recipient: msg.sender,\n                    amountOut: amountOut,\n                    amountInMaximum: type(uint).max,\n                    deadline: block.timestamp\n                })\n            );\n        }\n    }\n\n    function detectAndDecodeUniV2Path(bytes memory path) private pure returns (bool, address[] memory) {\n        bool isUniV2 = path.length % 20 == 0;\n        address[] memory addressPath;\n\n        if (isUniV2) {\n            uint addressPathSize = path.length / 20;\n            addressPath = new address[](addressPathSize);\n\n            unchecked {\n                for(uint i = 0; i < addressPathSize; ++i) {\n                    addressPath[i] = toAddress(path, i * 20);\n                }\n            }\n        }\n\n        return (isUniV2, addressPath);\n    }\n\n    function toAddress(bytes memory data, uint start) private pure returns (address result) {\n        // assuming data length is already validated\n        assembly {\n            // borrowed from BytesLib https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol\n            result := div(mload(add(add(data, 0x20), start)), 0x1000000000000000000000000)\n        }\n    }\n}\n"
    },
    "contracts/swapHandlers/SwapHandlerBase.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\nimport \"./ISwapHandler.sol\";\nimport \"../Interfaces.sol\";\nimport \"../Utils.sol\";\n\n/// @notice Base contract for swap handlers\nabstract contract SwapHandlerBase is ISwapHandler {\n    function trySafeApprove(address token, address to, uint value) internal returns (bool, bytes memory) {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));\n        return (success && (data.length == 0 || abi.decode(data, (bool))), data);\n    }\n\n    function safeApproveWithRetry(address token, address to, uint value) internal {\n        (bool success, bytes memory data) = trySafeApprove(token, to, value);\n\n        // some tokens, like USDT, require the allowance to be set to 0 first\n        if (!success) {\n            (success,) = trySafeApprove(token, to, 0);\n            if (success) {\n                (success,) = trySafeApprove(token, to, value);\n            }\n        }\n\n        if (!success) revertBytes(data);\n    }\n\n    function transferBack(address token) internal {\n        uint balance = IERC20(token).balanceOf(address(this));\n        if (balance > 0) Utils.safeTransfer(token, msg.sender, balance);\n    }\n\n    function setMaxAllowance(address token, uint minAllowance, address spender) internal {\n        uint allowance = IERC20(token).allowance(address(this), spender);\n        if (allowance < minAllowance) safeApproveWithRetry(token, spender, type(uint).max);\n    }\n\n    function revertBytes(bytes memory errMsg) internal pure {\n        if (errMsg.length > 0) {\n            assembly {\n                revert(add(32, errMsg), mload(errMsg))\n            }\n        }\n\n        revert(\"SwapHandlerBase: empty error\");\n    }\n}\n"
    },
    "contracts/vendor/ISwapRouterV3.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouterV3 is IUniswapV3SwapCallback {\n    struct ExactInputSingleParams {\n        address tokenIn;\n        address tokenOut;\n        uint24 fee;\n        address recipient;\n        uint256 deadline;\n        uint256 amountIn;\n        uint256 amountOutMinimum;\n        uint160 sqrtPriceLimitX96;\n    }\n\n    /// @notice Swaps `amountIn` of one token for as much as possible of another token\n    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n    /// @return amountOut The amount of the received token\n    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n    struct ExactInputParams {\n        bytes path;\n        address recipient;\n        uint256 deadline;\n        uint256 amountIn;\n        uint256 amountOutMinimum;\n    }\n\n    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n    /// @return amountOut The amount of the received token\n    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n    struct ExactOutputSingleParams {\n        address tokenIn;\n        address tokenOut;\n        uint24 fee;\n        address recipient;\n        uint256 deadline;\n        uint256 amountOut;\n        uint256 amountInMaximum;\n        uint160 sqrtPriceLimitX96;\n    }\n\n    /// @notice Swaps as little as possible of one token for `amountOut` of another token\n    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n    /// @return amountIn The amount of the input token\n    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n    struct ExactOutputParams {\n        bytes path;\n        address recipient;\n        uint256 deadline;\n        uint256 amountOut;\n        uint256 amountInMaximum;\n    }\n\n    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n    /// @return amountIn The amount of the input token\n    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n"
    },
    "contracts/vendor/ISwapRouterV2.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n    function factory() external pure returns (address);\n    function WETH() external pure returns (address);\n\n    function addLiquidity(\n        address tokenA,\n        address tokenB,\n        uint amountADesired,\n        uint amountBDesired,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB, uint liquidity);\n    function addLiquidityETH(\n        address token,\n        uint amountTokenDesired,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n    function removeLiquidity(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETH(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountToken, uint amountETH);\n    function removeLiquidityWithPermit(\n        address tokenA,\n        address tokenB,\n        uint liquidity,\n        uint amountAMin,\n        uint amountBMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountA, uint amountB);\n    function removeLiquidityETHWithPermit(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountToken, uint amountETH);\n    function swapExactTokensForTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapTokensForExactTokens(\n        uint amountOut,\n        uint amountInMax,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external returns (uint[] memory amounts);\n    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n        external\n        returns (uint[] memory amounts);\n    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n        external\n        payable\n        returns (uint[] memory amounts);\n\n    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}\n\n\ninterface ISwapRouterV2 is IUniswapV2Router01 {\n    function removeLiquidityETHSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline\n    ) external returns (uint amountETH);\n    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n        address token,\n        uint liquidity,\n        uint amountTokenMin,\n        uint amountETHMin,\n        address to,\n        uint deadline,\n        bool approveMax, uint8 v, bytes32 r, bytes32 s\n    ) external returns (uint amountETH);\n\n    function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n    function swapExactETHForTokensSupportingFeeOnTransferTokens(\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external payable;\n    function swapExactTokensForETHSupportingFeeOnTransferTokens(\n        uint amountIn,\n        uint amountOutMin,\n        address[] calldata path,\n        address to,\n        uint deadline\n    ) external;\n}\n"
    },
    "contracts/swapHandlers/ISwapHandler.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\ninterface ISwapHandler {\n    /// @notice Params for swaps using SwapHub contract and swap handlers\n    /// @param underlyingIn sold token address\n    /// @param underlyingOut bought token address\n    /// @param mode type of the swap: 0 for exact input, 1 for exact output\n    /// @param amountIn amount of token to sell. Exact value for exact input, maximum for exact output\n    /// @param amountOut amount of token to buy. Exact value for exact output, minimum for exact input\n    /// @param exactOutTolerance Maximum difference between requested amountOut and received tokens in exact output swap. Ignored for exact input\n    /// @param payload multi-purpose byte param. The usage depends on the swap handler implementation\n    struct SwapParams {\n        address underlyingIn;\n        address underlyingOut;\n        uint mode;                  // 0=exactIn  1=exactOut\n        uint amountIn;              // mode 0: exact,    mode 1: maximum\n        uint amountOut;             // mode 0: minimum,  mode 1: exact\n        uint exactOutTolerance;     // mode 0: ignored,  mode 1: downward tolerance on amountOut (fee-on-transfer etc.)\n        bytes payload;\n    }\n\n    /// @notice Execute a trade on the swap handler\n    /// @param params struct defining the requested trade\n    function executeSwap(SwapParams calldata params) external;\n}\n"
    },
    "contracts/Interfaces.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\n\ninterface IERC20 {\n    event Approval(address indexed owner, address indexed spender, uint value);\n    event Transfer(address indexed from, address indexed to, uint value);\n\n    function name() external view returns (string memory);\n    function symbol() external view returns (string memory);\n    function decimals() external view returns (uint8);\n    function totalSupply() external view returns (uint);\n    function balanceOf(address owner) external view returns (uint);\n    function allowance(address owner, address spender) external view returns (uint);\n\n    function approve(address spender, uint value) external returns (bool);\n    function transfer(address to, uint value) external returns (bool);\n    function transferFrom(address from, address to, uint value) external returns (bool);\n}\n\ninterface IERC20Permit {\n    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n    function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;\n    function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external;\n}\n\ninterface IERC3156FlashBorrower {\n    function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32);\n}\n\ninterface IERC3156FlashLender {\n    function maxFlashLoan(address token) external view returns (uint256);\n    function flashFee(address token, uint256 amount) external view returns (uint256);\n    function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n}\n"
    },
    "contracts/Utils.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\npragma solidity ^0.8.0;\n\nimport \"./Interfaces.sol\";\n\nlibrary Utils {\n    function safeTransferFrom(address token, address from, address to, uint value) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));\n        require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));\n    }\n\n    function safeTransfer(address token, address to, uint value) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));\n        require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));\n    }\n\n    function safeApprove(address token, address to, uint value) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));\n        require(success && (data.length == 0 || abi.decode(data, (bool))), string(data));\n    }\n}\n"
    },
    "contracts/vendor/IUniswapV3SwapCallback.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n    /// @dev In the implementation you must pay the pool tokens owed for the swap.\n    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n    function uniswapV3SwapCallback(\n        int256 amount0Delta,\n        int256 amount1Delta,\n        bytes calldata data\n    ) external;\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 1000000
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    }
  }
}