File size: 112,204 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{
  "language": "Solidity",
  "sources": {
    "@gearbox-protocol/integrations-v2/contracts/adapters/curve/CurveV1_DepositZap.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n// LIBRARIES\nimport { CurveV1AdapterBase } from \"./CurveV1_Base.sol\";\n\n// INTERFACES\nimport { IAdapter, AdapterType } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\n\n/// @title CurveV1AdapterDeposit adapter\n/// @dev Implements logic for interacting with a Curve zap wrapper (to remove_liquidity_one_coin from older pools)\ncontract CurveV1AdapterDeposit is CurveV1AdapterBase {\n    AdapterType public constant override _gearboxAdapterType =\n        AdapterType.CURVE_V1_WRAPPER;\n\n    /// @dev Sets allowance for the pool LP token before and after operation\n    modifier withLPTokenApproval() {\n        _approveToken(lp_token, type(uint256).max);\n        _;\n        _approveToken(lp_token, type(uint256).max);\n    }\n\n    /// @dev Constructor\n    /// @param _creditManager Address of the Credit manager\n    /// @param _curveDeposit Address of the target Curve deposit contract\n    /// @param _lp_token Address of the pool's LP token\n    /// @param _nCoins Number of coins supported by the wrapper\n    constructor(\n        address _creditManager,\n        address _curveDeposit,\n        address _lp_token,\n        uint256 _nCoins\n    )\n        CurveV1AdapterBase(\n            _creditManager,\n            _curveDeposit,\n            _lp_token,\n            address(0),\n            _nCoins\n        )\n    {}\n\n    /// @dev Sends an order to remove liquidity from the pool in a single asset,\n    /// using a deposit zap contract\n    /// @param i Index of the token to withdraw from the pool\n    /// - Unlike other adapters, approves the LP token to the target\n    /// @notice See more implementation details in CurveV1AdapterBase\n    function remove_liquidity_one_coin(\n        uint256, // _token_amount,\n        int128 i,\n        uint256 // min_amount\n    ) external virtual override nonReentrant withLPTokenApproval {\n        address tokenOut = _get_token(i);\n        _remove_liquidity_one_coin(tokenOut);\n    }\n\n    /// @dev Sends an order to remove all liquidity from the pool in a single asset\n    /// using a deposit zap contract\n    /// @param i Index of the token to withdraw from the pool\n    /// @param minRateRAY The minimum exchange rate of the LP token to the received asset\n    /// - Unlike other adapters, approves the LP token to the target\n    /// @notice See more implementation details in CurveV1AdapterBase\n    function remove_all_liquidity_one_coin(int128 i, uint256 minRateRAY)\n        external\n        virtual\n        override\n        nonReentrant\n        withLPTokenApproval\n    {\n        address tokenOut = _get_token(i); // F:[ACV1-4]\n        _remove_all_liquidity_one_coin(i, tokenOut, minRateRAY); // F:[ACV1-10]\n    }\n}\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/adapters/curve/CurveV1_Base.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { AbstractAdapter } from \"@gearbox-protocol/core-v2/contracts/adapters/AbstractAdapter.sol\";\nimport { ICurvePool2Assets } from \"../../integrations/curve/ICurvePool_2.sol\";\nimport { ICurvePool3Assets } from \"../../integrations/curve/ICurvePool_3.sol\";\nimport { ICurvePool4Assets } from \"../../integrations/curve/ICurvePool_4.sol\";\nimport { ICurveV1Adapter } from \"../../interfaces/curve/ICurveV1Adapter.sol\";\nimport { IAdapter, AdapterType } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\nimport { ICurvePool } from \"../../integrations/curve/ICurvePool.sol\";\nimport { RAY } from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\n// EXCEPTIONS\nimport { ZeroAddressException, NotImplementedException } from \"@gearbox-protocol/core-v2/contracts/interfaces/IErrors.sol\";\n\nuint256 constant ZERO = 0;\n\n/// @title CurveV1Base adapter\n/// @dev Implements common logic for interacting with all Curve pools, regardless of N_COINS\ncontract CurveV1AdapterBase is\n    AbstractAdapter,\n    ICurveV1Adapter,\n    ReentrancyGuard\n{\n    using SafeCast for uint256;\n    using SafeCast for int256;\n    // LP token, it could be named differently in some Curve Pools,\n    // so we set the same value to cover all possible cases\n\n    // coins\n    /// @dev Token in the pool under index 0\n    address public immutable token0;\n\n    /// @dev Token in the pool under index 1\n    address public immutable token1;\n\n    /// @dev Token in the pool under index 2\n    address public immutable token2;\n\n    /// @dev Token in the pool under index 3\n    address public immutable token3;\n\n    // underlying coins\n    /// @dev Underlying in the pool under index 0\n    address public immutable underlying0;\n\n    /// @dev Underlying in the pool under index 1\n    address public immutable underlying1;\n\n    /// @dev Underlying in the pool under index 2\n    address public immutable underlying2;\n\n    /// @dev Underlying in the pool under index 3\n    address public immutable underlying3;\n\n    /// @dev The pool LP token\n    address public immutable override token;\n\n    /// @dev The pool LP token\n    /// @notice The LP token can be named differently in different Curve pools,\n    /// so 2 getters are needed for backward compatibility\n    address public immutable override lp_token;\n\n    /// @dev Address of the base pool (for metapools only)\n    address public immutable override metapoolBase;\n\n    /// @dev Number of coins in the pool\n    uint256 public immutable nCoins;\n\n    uint16 public constant _gearboxAdapterVersion = 2;\n\n    function _gearboxAdapterType()\n        external\n        pure\n        virtual\n        override\n        returns (AdapterType)\n    {\n        return AdapterType.CURVE_V1_EXCHANGE_ONLY;\n    }\n\n    /// @dev Constructor\n    /// @param _creditManager Address of the Credit manager\n    /// @param _curvePool Address of the target contract Curve pool\n    /// @param _lp_token Address of the pool's LP token\n    /// @param _metapoolBase The base pool if this pool is a metapool, otherwise 0x0\n    constructor(\n        address _creditManager,\n        address _curvePool,\n        address _lp_token,\n        address _metapoolBase,\n        uint256 _nCoins\n    ) AbstractAdapter(_creditManager, _curvePool) {\n        if (_lp_token == address(0)) revert ZeroAddressException(); // F:[ACV1-1]\n\n        if (creditManager.tokenMasksMap(_lp_token) == 0)\n            revert TokenIsNotInAllowedList(_lp_token); // F:[ACV1-1]\n\n        token = _lp_token; // F:[ACV1-2]\n        lp_token = _lp_token; // F:[ACV1-2]\n        metapoolBase = _metapoolBase; // F:[ACV1-2]\n        nCoins = _nCoins; // F:[ACV1-2]\n\n        address[4] memory tokens;\n\n        for (uint256 i = 0; i < nCoins; ) {\n            address currentCoin;\n\n            try ICurvePool(targetContract).coins(i) returns (\n                address tokenAddress\n            ) {\n                currentCoin = tokenAddress;\n            } catch {\n                try\n                    ICurvePool(targetContract).coins(i.toInt256().toInt128())\n                returns (address tokenAddress) {\n                    currentCoin = tokenAddress;\n                } catch {}\n            }\n\n            if (currentCoin == address(0)) revert ZeroAddressException();\n            if (creditManager.tokenMasksMap(currentCoin) == 0)\n                revert TokenIsNotInAllowedList(currentCoin);\n\n            tokens[i] = currentCoin;\n\n            unchecked {\n                ++i;\n            }\n        }\n\n        token0 = tokens[0]; // F:[ACV1-2]\n        token1 = tokens[1]; // F:[ACV1-2]\n        token2 = tokens[2]; // F:[ACV1-2]\n        token3 = tokens[3]; // F:[ACV1-2]\n\n        tokens = [address(0), address(0), address(0), address(0)];\n\n        for (uint256 i = 0; i < 4; ) {\n            address currentCoin;\n\n            if (metapoolBase != address(0)) {\n                if (i == 0) {\n                    currentCoin = token0;\n                } else {\n                    try ICurvePool(metapoolBase).coins(i - 1) returns (\n                        address tokenAddress\n                    ) {\n                        currentCoin = tokenAddress;\n                    } catch {}\n                }\n            } else {\n                try ICurvePool(targetContract).underlying_coins(i) returns (\n                    address tokenAddress\n                ) {\n                    currentCoin = tokenAddress;\n                } catch {\n                    try\n                        ICurvePool(targetContract).underlying_coins(\n                            i.toInt256().toInt128()\n                        )\n                    returns (address tokenAddress) {\n                        currentCoin = tokenAddress;\n                    } catch {}\n                }\n            }\n\n            if (\n                currentCoin != address(0) &&\n                creditManager.tokenMasksMap(currentCoin) == 0\n            ) {\n                revert TokenIsNotInAllowedList(currentCoin); // F:[ACV1-1]\n            }\n\n            tokens[i] = currentCoin;\n\n            unchecked {\n                ++i;\n            }\n        }\n\n        underlying0 = tokens[0]; // F:[ACV1-2]\n        underlying1 = tokens[1]; // F:[ACV1-2]\n        underlying2 = tokens[2]; // F:[ACV1-2]\n        underlying3 = tokens[3]; // F:[ACV1-2]\n    }\n\n    /// @dev Sends an order to exchange one asset to another\n    /// @param i Index for the coin sent\n    /// @param j Index for the coin received\n    /// @notice Fast check parameters:\n    /// Input token: Coin under index i\n    /// Output token: Coin under index j\n    /// Input token is allowed, since the target does a transferFrom for coin i\n    /// The input token does not need to be disabled, because this does not spend the entire\n    /// balance, generally\n    function exchange(\n        int128 i,\n        int128 j,\n        uint256,\n        uint256\n    ) external override nonReentrant {\n        address tokenIn = _get_token(i); // F:[ACV1-4,ACV1S-3]\n        address tokenOut = _get_token(j); // F:[ACV1-4,ACV1S-3]\n        _executeMaxAllowanceFastCheck(tokenIn, tokenOut, msg.data, true, false); // F:[ACV1-4,ACV1S-3]\n    }\n\n    /// @dev Sends an order to exchange the entire balance of one asset to another\n    /// @param i Index for the coin sent\n    /// @param j Index for the coin received\n    /// @param rateMinRAY Minimum exchange rate between coins i and j\n    /// @notice Fast check parameters:\n    /// Input token: Coin under index i\n    /// Output token: Coin under index j\n    /// Input token is allowed, since the target does a transferFrom for coin i\n    /// The input token does need to be disabled, because this spends the entire balance\n    /// @notice Calls `exchange` under the hood, passing current balance - 1 as the amount\n    function exchange_all(\n        int128 i,\n        int128 j,\n        uint256 rateMinRAY\n    ) external override nonReentrant {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); //F:[ACV1-3]\n\n        address tokenIn = _get_token(i); //F:[ACV1-5]\n        address tokenOut = _get_token(j); // F:[ACV1-5]\n\n        uint256 dx = IERC20(tokenIn).balanceOf(creditAccount); //F:[ACV1-5]\n\n        if (dx > 1) {\n            unchecked {\n                dx--;\n            }\n            uint256 min_dy = (dx * rateMinRAY) / RAY; //F:[ACV1-5]\n\n            _executeMaxAllowanceFastCheck(\n                creditAccount,\n                tokenIn,\n                tokenOut,\n                abi.encodeWithSelector(\n                    ICurvePool.exchange.selector,\n                    i,\n                    j,\n                    dx,\n                    min_dy\n                ),\n                true,\n                true\n            ); //F:[ACV1-5]\n        }\n    }\n\n    /// @dev Sends an order to exchange one underlying asset to another\n    /// @param i Index for the underlying coin sent\n    /// @param j Index for the underlying coin received\n    /// @notice Fast check parameters:\n    /// Input token: Underlying coin under index i\n    /// Output token: Underlying coin under index j\n    /// Input token is allowed, since the target does a transferFrom for underlying i\n    /// The input token does not need to be disabled, because this does not spend the entire\n    /// balance, generally\n    function exchange_underlying(\n        int128 i,\n        int128 j,\n        uint256,\n        uint256\n    ) external override nonReentrant {\n        address tokenIn = _get_underlying(i); // F:[ACV1-6]\n        address tokenOut = _get_underlying(j); // F:[ACV1-6]\n        _executeMaxAllowanceFastCheck(tokenIn, tokenOut, msg.data, true, false); // F:[ACV1-6]\n    }\n\n    /// @dev Sends an order to exchange the entire balance of one underlying asset to another\n    /// @param i Index for the underlying coin sent\n    /// @param j Index for the underlying coin received\n    /// @param rateMinRAY Minimum exchange rate between underlyings i and j\n    /// @notice Fast check parameters:\n    /// Input token: Underlying coin under index i\n    /// Output token: Underlying coin under index j\n    /// Input token is allowed, since the target does a transferFrom for underlying i\n    /// The input token does need to be disabled, because this spends the entire balance\n    /// @notice Calls `exchange_underlying` under the hood, passing current balance - 1 as the amount\n    function exchange_all_underlying(\n        int128 i,\n        int128 j,\n        uint256 rateMinRAY\n    ) external nonReentrant {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); //F:[ACV1-3]\n\n        address tokenIn = _get_underlying(i); //F:[ACV1-7]\n        address tokenOut = _get_underlying(j); // F:[ACV1-7]\n\n        uint256 dx = IERC20(tokenIn).balanceOf(creditAccount); //F:[ACV1-7]\n\n        if (dx > 1) {\n            unchecked {\n                dx--;\n            }\n            uint256 min_dy = (dx * rateMinRAY) / RAY; //F:[ACV1-7]\n\n            _executeMaxAllowanceFastCheck(\n                creditAccount,\n                tokenIn,\n                tokenOut,\n                abi.encodeWithSelector(\n                    ICurvePool.exchange_underlying.selector,\n                    i,\n                    j,\n                    dx,\n                    min_dy\n                ),\n                true,\n                true\n            ); //F:[ACV1-7]\n        }\n    }\n\n    /// @dev Internal implementation for `add_liquidity`\n    /// - Sets allowances for tokens that are added\n    /// - Enables the pool LP token on the CA\n    /// - Executes the order with a full check (this is required since >2 tokens are involved)\n    /// - Resets allowance for tokens that are added\n\n    function _add_liquidity(\n        bool t0Approve,\n        bool t1Approve,\n        bool t2Approve,\n        bool t3Approve\n    ) internal {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1_2-3, ACV1_3-3, ACV1_3-4]\n\n        _approve_coins(t0Approve, t1Approve, t2Approve, t3Approve); // F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n\n        _enableToken(creditAccount, address(lp_token)); // F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n        _execute(msg.data); // F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n\n        _approve_coins(t0Approve, t1Approve, t2Approve, t3Approve); /// F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n\n        _fullCheck(creditAccount);\n    }\n\n    /// @dev Sends an order to add liquidity with only 1 input asset\n    /// - Picks a selector based on the number of coins\n    /// - Makes a fast check call to target\n    /// @param amount Amount of asset to deposit\n    /// @param i Index of the asset to deposit\n    /// @param minAmount Minimal number of LP tokens to receive\n    /// @notice Fast check parameters:\n    /// Input token: Pool asset under index i\n    /// Output token: Pool LP token\n    /// Input token is allowed, since the target does a transferFrom for the deposited asset\n    /// The input token does not need to be disabled, because this does not spend the entire\n    /// balance, generally\n    /// @notice Calls `add_liquidity` under the hood with only one amount being non-zero\n    function add_liquidity_one_coin(\n        uint256 amount,\n        int128 i,\n        uint256 minAmount\n    ) external override nonReentrant {\n        address tokenIn = _get_token(i);\n\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1-8A]\n\n        _executeMaxAllowanceFastCheck(\n            creditAccount,\n            tokenIn,\n            lp_token,\n            _getAddLiquidityCallData(i, amount, minAmount),\n            true,\n            false\n        ); // F:[ACV1-8A]\n    }\n\n    /// @dev Sends an order to add liquidity with only 1 input asset, using the entire balance\n    /// - Computes the amount of asset to deposit (balance - 1)\n    /// - Picks a selector based on the number of coins\n    /// - Makes a fast check call to target\n    /// @param i Index of the asset to deposit\n    /// @param rateMinRAY Minimal exchange rate between the deposited asset and the LP token\n    /// @notice Fast check parameters:\n    /// Input token: Pool asset under index i\n    /// Output token: Pool LP token\n    /// Input token is allowed, since the target does a transferFrom for the deposited asset\n    /// The input token does need to be disabled, because this spends the entire balance\n    /// @notice Calls `add_liquidity` under the hood with only one amount being non-zero\n    function add_all_liquidity_one_coin(int128 i, uint256 rateMinRAY)\n        external\n        override\n        nonReentrant\n    {\n        address tokenIn = _get_token(i);\n\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1-8]\n\n        uint256 amount = IERC20(tokenIn).balanceOf(creditAccount); /// F:[ACV1-8]\n\n        if (amount > 1) {\n            unchecked {\n                amount--; // F:[ACV1-8]\n            }\n\n            uint256 minAmount = (amount * rateMinRAY) / RAY; // F:[ACV1-8]\n\n            _executeMaxAllowanceFastCheck(\n                creditAccount,\n                tokenIn,\n                lp_token,\n                _getAddLiquidityCallData(i, amount, minAmount),\n                true,\n                true\n            ); // F:[ACV1-8]\n        }\n    }\n\n    function _getAddLiquidityCallData(\n        int128 i,\n        uint256 amount,\n        uint256 minAmount\n    ) internal view returns (bytes memory) {\n        if (nCoins == 2) {\n            return\n                i == 0\n                    ? abi.encodeWithSelector(\n                        ICurvePool2Assets.add_liquidity.selector,\n                        amount,\n                        ZERO,\n                        minAmount\n                    )\n                    : abi.encodeWithSelector(\n                        ICurvePool2Assets.add_liquidity.selector,\n                        ZERO,\n                        amount,\n                        minAmount\n                    ); // F:[ACV1-8]\n        }\n        if (nCoins == 3) {\n            return\n                i == 0\n                    ? abi.encodeWithSelector(\n                        ICurvePool3Assets.add_liquidity.selector,\n                        amount,\n                        ZERO,\n                        ZERO,\n                        minAmount\n                    )\n                    : i == 1\n                    ? abi.encodeWithSelector(\n                        ICurvePool3Assets.add_liquidity.selector,\n                        ZERO,\n                        amount,\n                        ZERO,\n                        minAmount\n                    )\n                    : abi.encodeWithSelector(\n                        ICurvePool3Assets.add_liquidity.selector,\n                        ZERO,\n                        ZERO,\n                        amount,\n                        minAmount\n                    ); // F:[ACV1-8]\n        }\n        if (nCoins == 4) {\n            return\n                i == 0\n                    ? abi.encodeWithSelector(\n                        ICurvePool4Assets.add_liquidity.selector,\n                        amount,\n                        ZERO,\n                        ZERO,\n                        ZERO,\n                        minAmount\n                    )\n                    : i == 1\n                    ? abi.encodeWithSelector(\n                        ICurvePool4Assets.add_liquidity.selector,\n                        ZERO,\n                        amount,\n                        ZERO,\n                        ZERO,\n                        minAmount\n                    )\n                    : i == 2\n                    ? abi.encodeWithSelector(\n                        ICurvePool4Assets.add_liquidity.selector,\n                        ZERO,\n                        ZERO,\n                        amount,\n                        ZERO,\n                        minAmount\n                    )\n                    : abi.encodeWithSelector(\n                        ICurvePool4Assets.add_liquidity.selector,\n                        ZERO,\n                        ZERO,\n                        ZERO,\n                        amount,\n                        minAmount\n                    ); // F:[ACV1-8]\n        }\n\n        revert(\"Incorrect nCoins\");\n    }\n\n    /// @dev Returns the amount of lp token received when adding a single coin to the pool\n    /// @param amount Amount of coin to be deposited\n    /// @param i Index of a coin to be deposited\n    function calc_add_one_coin(uint256 amount, int128 i)\n        external\n        view\n        returns (uint256)\n    {\n        if (nCoins == 2) {\n            return\n                i == 0\n                    ? ICurvePool2Assets(targetContract).calc_token_amount(\n                        [amount, 0],\n                        true\n                    )\n                    : ICurvePool2Assets(targetContract).calc_token_amount(\n                        [0, amount],\n                        true\n                    );\n        } else if (nCoins == 3) {\n            return\n                i == 0\n                    ? ICurvePool3Assets(targetContract).calc_token_amount(\n                        [amount, 0, 0],\n                        true\n                    )\n                    : i == 1\n                    ? ICurvePool3Assets(targetContract).calc_token_amount(\n                        [0, amount, 0],\n                        true\n                    )\n                    : ICurvePool3Assets(targetContract).calc_token_amount(\n                        [0, 0, amount],\n                        true\n                    );\n        } else if (nCoins == 4) {\n            return\n                i == 0\n                    ? ICurvePool4Assets(targetContract).calc_token_amount(\n                        [amount, 0, 0, 0],\n                        true\n                    )\n                    : i == 1\n                    ? ICurvePool4Assets(targetContract).calc_token_amount(\n                        [0, amount, 0, 0],\n                        true\n                    )\n                    : i == 2\n                    ? ICurvePool4Assets(targetContract).calc_token_amount(\n                        [0, 0, amount, 0],\n                        true\n                    )\n                    : ICurvePool4Assets(targetContract).calc_token_amount(\n                        [0, 0, 0, amount],\n                        true\n                    );\n        } else {\n            revert(\"Incorrect nCoins\");\n        }\n    }\n\n    /// @dev Internal implementation for `remove_liquidity`\n    /// - Enables all of the pool tokens (since remove_liquidity will always\n    /// return non-zero amounts for all tokens)\n    /// - Executes the order with a full check (this is required since >2 tokens are involved)\n    /// @notice The LP token does not need to be approved since the pool burns it\n    function _remove_liquidity() internal {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1_2-3, ACV1_3-3, ACV1_3-4]\n\n        _enableToken(creditAccount, token0); // F:[ACV1_2-5, ACV1_3-5, ACV1_4-5]\n        _enableToken(creditAccount, token1); // F:[ACV1_2-5, ACV1_3-5, ACV1_4-5]\n\n        if (token2 != address(0)) {\n            _enableToken(creditAccount, token2); // F:[ACV1_3-5, ACV1_4-5]\n\n            if (token3 != address(0)) {\n                _enableToken(creditAccount, token3); // F:[ACV1_4-5]\n            }\n        }\n        _execute(msg.data);\n        _fullCheck(creditAccount); //F:[ACV1_2-5, ACV1_3-5, ACV1_4-5]\n    }\n\n    /// @dev Sends an order to remove liquidity from a pool in a single asset\n    /// - Makes a fast check call to target, with passed calldata\n    /// @param i Index of the asset to withdraw\n    /// @notice `_token_amount` and `min_amount` are ignored since the calldata is routed directly to the target\n    /// @notice Fast check parameters:\n    /// Input token: Pool LP token\n    /// Output token: Coin under index i\n    /// Input token is not approved, since the pool directly burns the LP token\n    /// The input token does not need to be disabled, because this does not spend the entire\n    /// balance, generally\n    function remove_liquidity_one_coin(\n        uint256, // _token_amount,\n        int128 i,\n        uint256 // min_amount\n    ) external virtual override nonReentrant {\n        address tokenOut = _get_token(i); // F:[ACV1-9]\n        _remove_liquidity_one_coin(tokenOut); // F:[ACV1-9]\n    }\n\n    /// @dev Internal implementation for `remove_liquidity_one_coin` operations\n    /// - Makes a fast check call to target, with passed calldata\n    /// @param tokenOut The coin received from the pool\n    /// @notice Fast check parameters:\n    /// Input token: Pool LP token\n    /// Output token: Coin under index i\n    /// Input token is not approved, since the pool directly burns the LP token\n    /// The input token does not need to be disabled, because this does not spend the entire\n    /// balance, generally\n    function _remove_liquidity_one_coin(address tokenOut) internal {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1-9]\n\n        _executeMaxAllowanceFastCheck(\n            creditAccount,\n            lp_token,\n            tokenOut,\n            msg.data,\n            false,\n            false\n        ); // F:[ACV1-9]\n    }\n\n    /// @dev Sends an order to remove all liquidity from the pool in a single asset\n    /// @param i Index of the asset to withdraw\n    /// @param minRateRAY Minimal exchange rate between the LP token and the received token\n    function remove_all_liquidity_one_coin(int128 i, uint256 minRateRAY)\n        external\n        virtual\n        override\n        nonReentrant\n    {\n        address tokenOut = _get_token(i); // F:[ACV1-4]\n        _remove_all_liquidity_one_coin(i, tokenOut, minRateRAY); // F:[ACV1-10]\n    }\n\n    /// @dev Internal implementation for `remove_all_liquidity_one_coin` operations\n    /// - Computes the amount of LP token to burn (balance - 1)\n    /// - Makes a max allowance fast check call to target\n    /// @param i Index of the coin received from the pool\n    /// @param tokenOut The coin received from the pool\n    /// @param rateMinRAY The minimal exchange rate between the LP token and received token\n    /// @notice Fast check parameters:\n    /// Input token: Pool LP token\n    /// Output token: Coin under index i\n    /// Input token is not approved, since the pool directly burns the LP token\n    /// The input token does need to be disabled, because this spends the entire balance\n    function _remove_all_liquidity_one_coin(\n        int128 i,\n        address tokenOut,\n        uint256 rateMinRAY\n    ) internal {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); //F:[ACV1-3]\n\n        uint256 amount = IERC20(lp_token).balanceOf(creditAccount); // F:[ACV1-10]\n\n        if (amount > 1) {\n            unchecked {\n                amount--; // F:[ACV1-10]\n            }\n\n            _executeMaxAllowanceFastCheck(\n                creditAccount,\n                lp_token,\n                tokenOut,\n                abi.encodeWithSelector(\n                    ICurvePool.remove_liquidity_one_coin.selector,\n                    amount,\n                    i,\n                    (amount * rateMinRAY) / RAY\n                ),\n                false,\n                true\n            ); // F:[ACV1-10]\n        }\n    }\n\n    /// @dev Internal implementation for `remove_liquidity_imbalance`\n    /// - Enables tokens with a non-zero amount withdrawn\n    /// - Executes the order with a full check (this is required since >2 tokens are involved)\n    /// @notice The LP token does not need to be approved since the pool burns it\n    function _remove_liquidity_imbalance(\n        bool t0Enable,\n        bool t1Enable,\n        bool t2Enable,\n        bool t3Enable\n    ) internal {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[ACV1_2-3, ACV1_3-3, ACV1_3-4]\n\n        if (t0Enable) {\n            _enableToken(creditAccount, token0); // F:[ACV1_2-6, ACV1_3-6, ACV1_4-6]\n        }\n\n        if (t1Enable) {\n            _enableToken(creditAccount, token1); // F:[ACV1_2-6, ACV1_3-6, ACV1_4-6]\n        }\n\n        if (t2Enable) {\n            _enableToken(creditAccount, token2); // F:[ACV1_3-6, ACV1_4-6]\n        }\n\n        if (t3Enable) {\n            _enableToken(creditAccount, token3); // F:[ACV1_4-6]\n        }\n\n        _execute(msg.data);\n        _fullCheck(creditAccount); // F:[ACV1_2-6, ACV1_3-6, ACV1_4-6]\n    }\n\n    /// @dev Returns the amount of coin j received by swapping dx of coin i\n    /// @param i Index of the input coin\n    /// @param j Index of the output coin\n    /// @param dx Amount of coin i to be swapped in\n    function get_dy(\n        int128 i,\n        int128 j,\n        uint256 dx\n    ) external view override returns (uint256) {\n        return ICurvePool(targetContract).get_dy(i, j, dx); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the amount of underlying j received by swapping dx of underlying i\n    /// @param i Index of the input underlying\n    /// @param j Index of the output underlying\n    /// @param dx Amount of underlying i to be swapped in\n    function get_dy_underlying(\n        int128 i,\n        int128 j,\n        uint256 dx\n    ) external view override returns (uint256) {\n        return ICurvePool(targetContract).get_dy_underlying(i, j, dx); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the price of the pool's LP token\n    function get_virtual_price() external view override returns (uint256) {\n        return ICurvePool(targetContract).get_virtual_price(); // F:[ACV1-13]\n    }\n\n    /// @dev Returns the address of the coin with index i\n    /// @param i The index of a coin to retrieve the address for\n    function coins(uint256 i) external view override returns (address) {\n        return _get_token(i.toInt256().toInt128()); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the address of the coin with index i\n    /// @param i The index of a coin to retrieve the address for (type int128)\n    /// @notice Since `i` is int128 in some older Curve pools,\n    /// the function is provided for compatibility\n    function coins(int128 i) external view override returns (address) {\n        return _get_token(i); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the address of the underlying with index i\n    /// @param i The index of a coin to retrieve the address for\n    function underlying_coins(uint256 i)\n        public\n        view\n        override\n        returns (address)\n    {\n        return _get_underlying(i.toInt256().toInt128()); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the address of the underlying with index i\n    /// @param i The index of a coin to retrieve the address for (type int128)\n    /// @notice Since `i` is int128 in some older Curve pools,\n    /// the function is provided for compatibility\n    function underlying_coins(int128 i)\n        external\n        view\n        override\n        returns (address)\n    {\n        return _get_underlying(i); // F:[ACV1-11]\n    }\n\n    /// @dev Returns the pool's balance of the coin with index i\n    /// @param i The index of the coin to retrieve the balance for\n    /// @notice Since `i` is int128 in some older Curve pools,\n    /// the function first tries to call a uin256 variant,\n    /// and then then int128 variant if that fails\n    function balances(uint256 i) public view override returns (uint256) {\n        try ICurvePool(targetContract).balances(i) returns (uint256 balance) {\n            return balance; // F:[ACV1-11]\n        } catch {\n            return ICurvePool(targetContract).balances(i.toInt256().toInt128()); // F:[ACV1-11]\n        }\n    }\n\n    /// @dev Returns the pool's balance of the coin with index i\n    /// @param i The index of the coin to retrieve the balance for\n    /// @notice Since `i` is int128 in some older Curve pools,\n    /// the function first tries to call a int128 variant,\n    /// and then then uint256 variant if that fails\n    function balances(int128 i) public view override returns (uint256) {\n        return balances(uint256(uint128(i)));\n    }\n\n    /// @dev Return the token i's address gas-efficiently\n    function _get_token(int128 i) internal view returns (address addr) {\n        if (i == 0)\n            addr = token0; // F:[ACV1-14]\n        else if (i == 1)\n            addr = token1; // F:[ACV1-14]\n        else if (i == 2)\n            addr = token2; // F:[ACV1-14]\n        else if (i == 3) addr = token3; // F:[ACV1-14]\n\n        if (addr == address(0)) revert IncorrectIndexException(); // F:[ACV1-13]\n    }\n\n    /// @dev Return the underlying i's address gas-efficiently\n    function _get_underlying(int128 i) internal view returns (address addr) {\n        if (i == 0)\n            addr = underlying0; // F:[ACV1-14]\n        else if (i == 1)\n            addr = underlying1; // F:[ACV1-14]\n        else if (i == 2)\n            addr = underlying2; // F:[ACV1-14]\n        else if (i == 3) addr = underlying3; // F:[ACV1-14]\n\n        if (addr == address(0)) revert IncorrectIndexException(); // F:[ACV1-13]\n    }\n\n    /// @dev Gives max approval for a coin to target contract\n    function _approve_coins(\n        bool t0Enable,\n        bool t1Enable,\n        bool t2Enable,\n        bool t3Enable\n    ) internal {\n        if (t0Enable) {\n            _approveToken(token0, type(uint256).max); // F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n        }\n        if (t1Enable) {\n            _approveToken(token1, type(uint256).max); // F:[ACV1_2-4, ACV1_3-4, ACV1_4-4]\n        }\n        if (t2Enable) {\n            _approveToken(token2, type(uint256).max); // F:[ACV1_3-4, ACV1_4-4]\n        }\n        if (t3Enable) {\n            _approveToken(token3, type(uint256).max); // F:[ACV1_4-4]\n        }\n    }\n\n    function _enableToken(address creditAccount, address tokenToEnable)\n        internal\n    {\n        creditManager.checkAndEnableToken(creditAccount, tokenToEnable);\n    }\n\n    /// @dev Returns the current amplification parameter\n    function A() external view returns (uint256) {\n        return ICurvePool(targetContract).A();\n    }\n\n    /// @dev Returns the current amplification parameter scaled\n    function A_precise() external view returns (uint256) {\n        return ICurvePool(targetContract).A_precise();\n    }\n\n    /// @dev Returns the amount of coin withdrawn when using remove_liquidity_one_coin\n    /// @param _burn_amount Amount of LP token to be burnt\n    /// @param i Index of a coin to receive\n    function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)\n        external\n        view\n        returns (uint256)\n    {\n        return\n            ICurvePool(targetContract).calc_withdraw_one_coin(_burn_amount, i);\n    }\n\n    /// @dev Returns the amount of coin that belongs to the admin\n    /// @param i Index of a coin\n    function admin_balances(uint256 i) external view returns (uint256) {\n        return ICurvePool(targetContract).admin_balances(i);\n    }\n\n    /// @dev Returns the admin of a pool\n    function admin() external view returns (address) {\n        return ICurvePool(targetContract).admin();\n    }\n\n    /// @dev Returns the fee amount\n    function fee() external view returns (uint256) {\n        return ICurvePool(targetContract).fee();\n    }\n\n    /// @dev Returns the percentage of the fee claimed by the admin\n    function admin_fee() external view returns (uint256) {\n        return ICurvePool(targetContract).admin_fee();\n    }\n\n    /// @dev Returns the block in which the pool was last interacted with\n    function block_timestamp_last() external view returns (uint256) {\n        return ICurvePool(targetContract).block_timestamp_last();\n    }\n\n    /// @dev Returns the initial A during ramping\n    function initial_A() external view returns (uint256) {\n        return ICurvePool(targetContract).initial_A();\n    }\n\n    /// @dev Returns the final A during ramping\n    function future_A() external view returns (uint256) {\n        return ICurvePool(targetContract).future_A();\n    }\n\n    /// @dev Returns the ramping start time\n    function initial_A_time() external view returns (uint256) {\n        return ICurvePool(targetContract).initial_A_time();\n    }\n\n    /// @dev Returns the ramping end time\n    function future_A_time() external view returns (uint256) {\n        return ICurvePool(targetContract).future_A_time();\n    }\n\n    /// @dev Returns the name of the LP token\n    /// @notice Only for pools that implement ERC20\n    function name() external view returns (string memory) {\n        return ICurvePool(targetContract).name();\n    }\n\n    /// @dev Returns the symbol of the LP token\n    /// @notice Only for pools that implement ERC20\n    function symbol() external view returns (string memory) {\n        return ICurvePool(targetContract).symbol();\n    }\n\n    /// @dev Returns the decimals of the LP token\n    /// @notice Only for pools that implement ERC20\n    function decimals() external view returns (uint256) {\n        return ICurvePool(targetContract).decimals();\n    }\n\n    /// @dev Returns the LP token balance of address\n    /// @param account Address to compute the balance for\n    /// @notice Only for pools that implement ERC20\n    function balanceOf(address account) external view returns (uint256) {\n        return ICurvePool(targetContract).balanceOf(account);\n    }\n\n    /// @dev Returns the LP token allowance of address\n    /// @param owner Address from which the token is allowed\n    /// @param spender Address to which the token is allowed\n    /// @notice Only for pools that implement ERC20\n    function allowance(address owner, address spender)\n        external\n        view\n        returns (uint256)\n    {\n        return ICurvePool(targetContract).allowance(owner, spender);\n    }\n\n    /// @dev Returns the total supply of the LP token\n    /// @notice Only for pools that implement ERC20\n    function totalSupply() external view returns (uint256) {\n        return ICurvePool(targetContract).totalSupply();\n    }\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\nimport { ICreditManagerV2 } from \"../ICreditManagerV2.sol\";\n\nenum AdapterType {\n    ABSTRACT,\n    UNISWAP_V2_ROUTER,\n    UNISWAP_V3_ROUTER,\n    CURVE_V1_EXCHANGE_ONLY,\n    YEARN_V2,\n    CURVE_V1_2ASSETS,\n    CURVE_V1_3ASSETS,\n    CURVE_V1_4ASSETS,\n    CURVE_V1_STECRV_POOL,\n    CURVE_V1_WRAPPER,\n    CONVEX_V1_BASE_REWARD_POOL,\n    CONVEX_V1_BOOSTER,\n    CONVEX_V1_CLAIM_ZAP,\n    LIDO_V1,\n    UNIVERSAL,\n    LIDO_WSTETH_V1\n}\n\ninterface IAdapterExceptions {\n    /// @dev Thrown when the adapter attempts to use a token\n    ///      that is not recognized as collateral in the connected\n    ///      Credit Manager\n    error TokenIsNotInAllowedList(address);\n}\n\ninterface IAdapter is IAdapterExceptions {\n    /// @dev Returns the Credit Manager connected to the adapter\n    function creditManager() external view returns (ICreditManagerV2);\n\n    /// @dev Returns the address of the contract the adapter is interacting with\n    function targetContract() external view returns (address);\n\n    /// @dev Returns the adapter type\n    function _gearboxAdapterType() external pure returns (AdapterType);\n\n    /// @dev Returns the adapter version\n    function _gearboxAdapterVersion() external pure returns (uint16);\n}\n"
    },
    "@openzeppelin/contracts/security/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n\n        _;\n\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n}\n"
    },
    "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `recipient`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address recipient, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `sender` to `recipient` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address sender,\n        address recipient,\n        uint256 amount\n    ) external returns (bool);\n\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
    },
    "@openzeppelin/contracts/utils/math/SafeCast.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        require(value >= 0, \"SafeCast: value must be positive\");\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128) {\n        require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n        return int128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64) {\n        require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n        return int64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32) {\n        require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n        return int32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16) {\n        require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n        return int16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits.\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8) {\n        require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n        return int8(value);\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/adapters/AbstractAdapter.sol": {
      "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\nimport { Address } from \"@openzeppelin/contracts/utils/Address.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { ICreditManagerV2 } from \"../interfaces/ICreditManagerV2.sol\";\nimport { IAdapter } from \"../interfaces/adapters/IAdapter.sol\";\nimport { ZeroAddressException } from \"../interfaces/IErrors.sol\";\n\nabstract contract AbstractAdapter is IAdapter {\n    using Address for address;\n\n    ICreditManagerV2 public immutable override creditManager;\n    address public immutable override targetContract;\n\n    constructor(address _creditManager, address _targetContract) {\n        if (_creditManager == address(0) || _targetContract == address(0))\n            revert ZeroAddressException(); // F:[AA-2]\n\n        creditManager = ICreditManagerV2(_creditManager); // F:[AA-1]\n        targetContract = _targetContract; // F:[AA-1]\n    }\n\n    /// @dev Approves a token from the Credit Account to the target contract\n    /// @param token Token to be approved\n    /// @param amount Amount to be approved\n    function _approveToken(address token, uint256 amount) internal {\n        creditManager.approveCreditAccount(\n            msg.sender,\n            targetContract,\n            token,\n            amount\n        );\n    }\n\n    /// @dev Sends CallData to call the target contract from the Credit Account\n    /// @param callData Data to be sent to the target contract\n    function _execute(bytes memory callData)\n        internal\n        returns (bytes memory result)\n    {\n        result = creditManager.executeOrder(\n            msg.sender,\n            targetContract,\n            callData\n        );\n    }\n\n    /// @dev Calls a target contract with maximal allowance and performs a fast check after\n    /// @param creditAccount A credit account from which a call is made\n    /// @param tokenIn The token that the interaction is expected to spend\n    /// @param tokenOut The token that the interaction is expected to produce\n    /// @param callData Data to call targetContract with\n    /// @param allowTokenIn Whether the input token must be approved beforehand\n    /// @param disableTokenIn Whether the input token should be disable afterwards (for interaction that spend the entire balance)\n    /// @notice Must only be used for highly secure and immutable protocols, such as Uniswap & Curve\n    function _executeMaxAllowanceFastCheck(\n        address creditAccount,\n        address tokenIn,\n        address tokenOut,\n        bytes memory callData,\n        bool allowTokenIn,\n        bool disableTokenIn\n    ) internal returns (bytes memory result) {\n        address creditFacade = creditManager.creditFacade();\n\n        uint256 balanceInBefore;\n        uint256 balanceOutBefore;\n\n        if (msg.sender != creditFacade) {\n            balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // F:[AA-4A]\n            balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // F:[AA-4A]\n        }\n\n        if (allowTokenIn) {\n            _approveToken(tokenIn, type(uint256).max);\n        }\n\n        result = creditManager.executeOrder(\n            msg.sender,\n            targetContract,\n            callData\n        );\n\n        if (allowTokenIn) {\n            _approveToken(tokenIn, type(uint256).max);\n        }\n\n        _fastCheck(\n            creditAccount,\n            creditFacade,\n            tokenIn,\n            tokenOut,\n            balanceInBefore,\n            balanceOutBefore,\n            disableTokenIn\n        );\n    }\n\n    /// @dev Wrapper for _executeMaxAllowanceFastCheck that computes the Credit Account on the spot\n    /// See params and other details above\n    function _executeMaxAllowanceFastCheck(\n        address tokenIn,\n        address tokenOut,\n        bytes memory callData,\n        bool allowTokenIn,\n        bool disableTokenIn\n    ) internal returns (bytes memory result) {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        ); // F:[AA-3]\n\n        result = _executeMaxAllowanceFastCheck(\n            creditAccount,\n            tokenIn,\n            tokenOut,\n            callData,\n            allowTokenIn,\n            disableTokenIn\n        );\n    }\n\n    /// @dev Calls a target contract with maximal allowance, then sets allowance to 1 and performs a fast check\n    /// @param creditAccount A credit account from which a call is made\n    /// @param tokenIn The token that the interaction is expected to spend\n    /// @param tokenOut The token that the interaction is expected to produce\n    /// @param callData Data to call targetContract with\n    /// @param allowTokenIn Whether the input token must be approved beforehand\n    /// @param disableTokenIn Whether the input token should be disable afterwards (for interaction that spend the entire balance)\n    function _safeExecuteFastCheck(\n        address creditAccount,\n        address tokenIn,\n        address tokenOut,\n        bytes memory callData,\n        bool allowTokenIn,\n        bool disableTokenIn\n    ) internal returns (bytes memory result) {\n        address creditFacade = creditManager.creditFacade();\n\n        uint256 balanceInBefore;\n        uint256 balanceOutBefore;\n\n        if (msg.sender != creditFacade) {\n            balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount);\n            balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // F:[AA-4A]\n        }\n\n        if (allowTokenIn) {\n            _approveToken(tokenIn, type(uint256).max);\n        }\n\n        result = creditManager.executeOrder(\n            msg.sender,\n            targetContract,\n            callData\n        );\n\n        if (allowTokenIn) {\n            _approveToken(tokenIn, 1);\n        }\n\n        _fastCheck(\n            creditAccount,\n            creditFacade,\n            tokenIn,\n            tokenOut,\n            balanceInBefore,\n            balanceOutBefore,\n            disableTokenIn\n        );\n    }\n\n    /// @dev Wrapper for _safeExecuteFastCheck that computes the Credit Account on the spot\n    /// See params and other details above\n    function _safeExecuteFastCheck(\n        address tokenIn,\n        address tokenOut,\n        bytes memory callData,\n        bool allowTokenIn,\n        bool disableTokenIn\n    ) internal returns (bytes memory result) {\n        address creditAccount = creditManager.getCreditAccountOrRevert(\n            msg.sender\n        );\n\n        result = _safeExecuteFastCheck(\n            creditAccount,\n            tokenIn,\n            tokenOut,\n            callData,\n            allowTokenIn,\n            disableTokenIn\n        );\n    }\n\n    //\n    // HEALTH CHECK FUNCTIONS\n    //\n\n    /// @dev Performs a fast check during ordinary adapter call, or skips\n    /// it for multicalls (since a full collateral check is always performed after a multicall)\n    /// @param creditAccount Credit Account for which the fast check is performed\n    /// @param creditFacade CreditFacade currently associated with CreditManager\n    /// @param tokenIn Token that is spent by the operation\n    /// @param tokenOut Token that is received as a result of operation\n    /// @param balanceInBefore Balance of tokenIn before the operation\n    /// @param balanceOutBefore Balance of tokenOut before the operation\n    /// @param disableTokenIn Whether tokenIn needs to be disabled (required for multicalls, where the fast check is skipped)\n    function _fastCheck(\n        address creditAccount,\n        address creditFacade,\n        address tokenIn,\n        address tokenOut,\n        uint256 balanceInBefore,\n        uint256 balanceOutBefore,\n        bool disableTokenIn\n    ) private {\n        if (msg.sender != creditFacade) {\n            creditManager.fastCollateralCheck(\n                creditAccount,\n                tokenIn,\n                tokenOut,\n                balanceInBefore,\n                balanceOutBefore\n            );\n        } else {\n            if (disableTokenIn)\n                creditManager.disableToken(creditAccount, tokenIn);\n            creditManager.checkAndEnableToken(creditAccount, tokenOut);\n        }\n    }\n\n    /// @dev Performs a full collateral check during ordinary adapter call, or skips\n    /// it for multicalls (since a full collateral check is always performed after a multicall)\n    /// @param creditAccount Credit Account for which the full check is performed\n    function _fullCheck(address creditAccount) internal {\n        address creditFacade = creditManager.creditFacade();\n\n        if (msg.sender != creditFacade) {\n            creditManager.fullCollateralCheck(creditAccount);\n        }\n    }\n\n    /// @dev Performs a enabled token optimization on account or skips\n    /// it for multicalls (since a full collateral check is always performed after a multicall,\n    /// and includes enabled token optimization by default)\n    /// @param creditAccount Credit Account for which the full check is performed\n    /// @notice Used when new tokens are added on an account but no tokens are subtracted\n    ///         (e.g., claiming rewards)\n    function _checkAndOptimizeEnabledTokens(address creditAccount) internal {\n        address creditFacade = creditManager.creditFacade();\n\n        if (msg.sender != creditFacade) {\n            creditManager.checkAndOptimizeEnabledTokens(creditAccount);\n        }\n    }\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/interfaces/IErrors.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n/// @dev Common contract exceptions\n\n/// @dev Thrown on attempting to set an important address to zero address\nerror ZeroAddressException();\n\n/// @dev Thrown on attempting to call a non-implemented function\nerror NotImplementedException();\n\n/// @dev Thrown on attempting to set an EOA as an important contract in the system\nerror AddressIsNotContractException(address);\n\n/// @dev Thrown on attempting to use a non-ERC20 contract or an EOA as a token\nerror IncorrectTokenContractException();\n\n/// @dev Thrown on attempting to set a token price feed to an address that is not a\n///      correct price feed\nerror IncorrectPriceFeedException();\n\n/// @dev Thrown on attempting to call an access restricted function as a non-Configurator\nerror CallerNotConfiguratorException();\n\n/// @dev Thrown on attempting to pause a contract as a non-Pausable admin\nerror CallerNotPausableAdminException();\n\n/// @dev Thrown on attempting to pause a contract as a non-Unpausable admin\nerror CallerNotUnPausableAdminException();\n\nerror TokenIsNotAddedToCreditManagerException(address token);\n"
    },
    "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n// Denominations\n\nuint256 constant WAD = 1e18;\nuint256 constant RAY = 1e27;\n\n// 25% of type(uint256).max\nuint256 constant ALLOWANCE_THRESHOLD = type(uint96).max >> 3;\n\n// FEE = 50%\nuint16 constant DEFAULT_FEE_INTEREST = 50_00; // 50%\n\n// LIQUIDATION_FEE 1.5%\nuint16 constant DEFAULT_FEE_LIQUIDATION = 1_50; // 1.5%\n\n// LIQUIDATION PREMIUM 4%\nuint16 constant DEFAULT_LIQUIDATION_PREMIUM = 4_00; // 4%\n\n// LIQUIDATION_FEE_EXPIRED 2%\nuint16 constant DEFAULT_FEE_LIQUIDATION_EXPIRED = 1_00; // 2%\n\n// LIQUIDATION PREMIUM EXPIRED 2%\nuint16 constant DEFAULT_LIQUIDATION_PREMIUM_EXPIRED = 2_00; // 2%\n\n// DEFAULT PROPORTION OF MAX BORROWED PER BLOCK TO MAX BORROWED PER ACCOUNT\nuint16 constant DEFAULT_LIMIT_PER_BLOCK_MULTIPLIER = 2;\n\n// Seconds in a year\nuint256 constant SECONDS_PER_YEAR = 365 days;\nuint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = (SECONDS_PER_YEAR * 3) / 2;\n\n// OPERATIONS\n\n// Leverage decimals - 100 is equal to 2x leverage (100% * collateral amount + 100% * borrowed amount)\nuint8 constant LEVERAGE_DECIMALS = 100;\n\n// Maximum withdraw fee for pool in PERCENTAGE_FACTOR format\nuint8 constant MAX_WITHDRAW_FEE = 100;\n\nuint256 constant EXACT_INPUT = 1;\nuint256 constant EXACT_OUTPUT = 2;\n\naddress constant UNIVERSAL_CONTRACT = 0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC;\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/integrations/curve/ICurvePool_3.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\nimport { ICurvePool } from \"./ICurvePool.sol\";\n\nuint256 constant N_COINS = 3;\n\n/// @title ICurvePool3Assets\n/// @dev Extends original pool contract with liquidity functions\ninterface ICurvePool3Assets is ICurvePool {\n    function add_liquidity(\n        uint256[N_COINS] memory amounts,\n        uint256 min_mint_amount\n    ) external;\n\n    function remove_liquidity(\n        uint256 _amount,\n        uint256[N_COINS] memory min_amounts\n    ) external;\n\n    function remove_liquidity_imbalance(\n        uint256[N_COINS] memory amounts,\n        uint256 max_burn_amount\n    ) external;\n\n    function calc_token_amount(\n        uint256[N_COINS] calldata _amounts,\n        bool _is_deposit\n    ) external view returns (uint256);\n\n    function get_twap_balances(\n        uint256[N_COINS] calldata _first_balances,\n        uint256[N_COINS] calldata _last_balances,\n        uint256 _time_elapsed\n    ) external view returns (uint256[N_COINS] memory);\n\n    function get_balances() external view returns (uint256[N_COINS] memory);\n\n    function get_previous_balances()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n\n    function get_price_cumulative_last()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n}\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/integrations/curve/ICurvePool_2.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\nimport { ICurvePool } from \"./ICurvePool.sol\";\n\nuint256 constant N_COINS = 2;\n\n/// @title ICurvePool2Assets\n/// @dev Extends original pool contract with liquidity functions\ninterface ICurvePool2Assets is ICurvePool {\n    function add_liquidity(\n        uint256[N_COINS] memory amounts,\n        uint256 min_mint_amount\n    ) external;\n\n    function remove_liquidity(\n        uint256 _amount,\n        uint256[N_COINS] memory min_amounts\n    ) external;\n\n    function remove_liquidity_imbalance(\n        uint256[N_COINS] calldata amounts,\n        uint256 max_burn_amount\n    ) external;\n\n    function calc_token_amount(\n        uint256[N_COINS] calldata _amounts,\n        bool _is_deposit\n    ) external view returns (uint256);\n\n    function get_twap_balances(\n        uint256[N_COINS] calldata _first_balances,\n        uint256[N_COINS] calldata _last_balances,\n        uint256 _time_elapsed\n    ) external view returns (uint256[N_COINS] memory);\n\n    function get_balances() external view returns (uint256[N_COINS] memory);\n\n    function get_previous_balances()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n\n    function get_price_cumulative_last()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n}\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/interfaces/curve/ICurveV1Adapter.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IAdapter } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\nimport { ICurvePool } from \"../../integrations/curve/ICurvePool.sol\";\n\ninterface ICurveV1AdapterExceptions {\n    error IncorrectIndexException();\n}\n\ninterface ICurveV1Adapter is IAdapter, ICurvePool, ICurveV1AdapterExceptions {\n    /// @dev Sends an order to exchange the entire balance of one asset to another\n    /// @param i Index for the coin sent\n    /// @param j Index for the coin received\n    /// @param rateMinRAY Minimum exchange rate between coins i and j\n    function exchange_all(\n        int128 i,\n        int128 j,\n        uint256 rateMinRAY\n    ) external;\n\n    /// @dev Sends an order to exchange the entire balance of one underlying asset to another\n    /// @param i Index for the underlying coin sent\n    /// @param j Index for the underlying coin received\n    /// @param rateMinRAY Minimum exchange rate between underlyings i and j\n    function exchange_all_underlying(\n        int128 i,\n        int128 j,\n        uint256 rateMinRAY\n    ) external;\n\n    /// @dev Sends an order to add liquidity with only 1 input asset\n    /// @param amount Amount of asset to deposit\n    /// @param i Index of the asset to deposit\n    /// @param minAmount Minimal number of LP tokens to receive\n    function add_liquidity_one_coin(\n        uint256 amount,\n        int128 i,\n        uint256 minAmount\n    ) external;\n\n    /// @dev Sends an order to add liquidity with only 1 input asset, using the entire balance\n    /// @param i Index of the asset to deposit\n    /// @param rateMinRAY Minimal exchange rate between the deposited asset and the LP token\n    function add_all_liquidity_one_coin(int128 i, uint256 rateMinRAY) external;\n\n    /// @dev Sends an order to remove all liquidity from the pool in a single asset\n    /// @param i Index of the asset to withdraw\n    /// @param minRateRAY Minimal exchange rate between the LP token and the received token\n    function remove_all_liquidity_one_coin(int128 i, uint256 minRateRAY)\n        external;\n\n    //\n    // GETTERS\n    //\n\n    /// @dev The pool LP token\n    function lp_token() external view returns (address);\n\n    /// @dev Address of the base pool (for metapools only)\n    function metapoolBase() external view returns (address);\n\n    /// @dev Number of coins in the pool\n    function nCoins() external view returns (uint256);\n\n    /// @dev Token in the pool under index 0\n    function token0() external view returns (address);\n\n    /// @dev Token in the pool under index 1\n    function token1() external view returns (address);\n\n    /// @dev Token in the pool under index 2\n    function token2() external view returns (address);\n\n    /// @dev Token in the pool under index 3\n    function token3() external view returns (address);\n\n    /// @dev Underlying in the pool under index 0\n    function underlying0() external view returns (address);\n\n    /// @dev Underlying in the pool under index 1\n    function underlying1() external view returns (address);\n\n    /// @dev Underlying in the pool under index 2\n    function underlying2() external view returns (address);\n\n    /// @dev Underlying in the pool under index 3\n    function underlying3() external view returns (address);\n\n    /// @dev Returns the amount of lp token received when adding a single coin to the pool\n    /// @param amount Amount of coin to be deposited\n    /// @param i Index of a coin to be deposited\n    function calc_add_one_coin(uint256 amount, int128 i)\n        external\n        view\n        returns (uint256);\n}\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/integrations/curve/ICurvePool_4.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\nimport { ICurvePool } from \"./ICurvePool.sol\";\n\nuint256 constant N_COINS = 4;\n\n/// @title ICurvePool4Assets\n/// @dev Extends original pool contract with liquidity functions\ninterface ICurvePool4Assets is ICurvePool {\n    function add_liquidity(\n        uint256[N_COINS] memory amounts,\n        uint256 min_mint_amount\n    ) external;\n\n    function remove_liquidity(\n        uint256 _amount,\n        uint256[N_COINS] memory min_amounts\n    ) external;\n\n    function remove_liquidity_imbalance(\n        uint256[N_COINS] memory amounts,\n        uint256 max_burn_amount\n    ) external;\n\n    function calc_token_amount(\n        uint256[N_COINS] calldata _amounts,\n        bool _is_deposit\n    ) external view returns (uint256);\n\n    function get_twap_balances(\n        uint256[N_COINS] calldata _first_balances,\n        uint256[N_COINS] calldata _last_balances,\n        uint256 _time_elapsed\n    ) external view returns (uint256[N_COINS] memory);\n\n    function get_balances() external view returns (uint256[N_COINS] memory);\n\n    function get_previous_balances()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n\n    function get_price_cumulative_last()\n        external\n        view\n        returns (uint256[N_COINS] memory);\n}\n"
    },
    "@gearbox-protocol/integrations-v2/contracts/integrations/curve/ICurvePool.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\ninterface ICurvePool {\n    function coins(uint256 i) external view returns (address);\n\n    function underlying_coins(uint256 i) external view returns (address);\n\n    function balances(uint256 i) external view returns (uint256);\n\n    function coins(int128) external view returns (address);\n\n    function underlying_coins(int128) external view returns (address);\n\n    function balances(int128) external view returns (uint256);\n\n    function exchange(\n        int128 i,\n        int128 j,\n        uint256 dx,\n        uint256 min_dy\n    ) external;\n\n    function exchange_underlying(\n        int128 i,\n        int128 j,\n        uint256 dx,\n        uint256 min_dy\n    ) external;\n\n    function get_dy_underlying(\n        int128 i,\n        int128 j,\n        uint256 dx\n    ) external view returns (uint256);\n\n    function get_dy(\n        int128 i,\n        int128 j,\n        uint256 dx\n    ) external view returns (uint256);\n\n    function get_virtual_price() external view returns (uint256);\n\n    function token() external view returns (address);\n\n    function remove_liquidity_one_coin(\n        uint256 _token_amount,\n        int128 i,\n        uint256 min_amount\n    ) external;\n\n    function A() external view returns (uint256);\n\n    function A_precise() external view returns (uint256);\n\n    function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)\n        external\n        view\n        returns (uint256);\n\n    function admin_balances(uint256 i) external view returns (uint256);\n\n    function admin() external view returns (address);\n\n    function fee() external view returns (uint256);\n\n    function admin_fee() external view returns (uint256);\n\n    function block_timestamp_last() external view returns (uint256);\n\n    function initial_A() external view returns (uint256);\n\n    function future_A() external view returns (uint256);\n\n    function initial_A_time() external view returns (uint256);\n\n    function future_A_time() external view returns (uint256);\n\n    // Some pools implement ERC20\n\n    function name() external view returns (string memory);\n\n    function symbol() external view returns (string memory);\n\n    function decimals() external view returns (uint256);\n\n    function balanceOf(address) external view returns (uint256);\n\n    function allowance(address, address) external view returns (uint256);\n\n    function totalSupply() external view returns (uint256);\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/interfaces/ICreditManagerV2.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IPriceOracleV2 } from \"./IPriceOracle.sol\";\nimport { IVersion } from \"./IVersion.sol\";\n\nenum ClosureAction {\n    CLOSE_ACCOUNT,\n    LIQUIDATE_ACCOUNT,\n    LIQUIDATE_EXPIRED_ACCOUNT,\n    LIQUIDATE_PAUSED\n}\n\ninterface ICreditManagerV2Events {\n    /// @dev Emits when a call to an external contract is made through the Credit Manager\n    event ExecuteOrder(address indexed borrower, address indexed target);\n\n    /// @dev Emits when a configurator is upgraded\n    event NewConfigurator(address indexed newConfigurator);\n}\n\ninterface ICreditManagerV2Exceptions {\n    /// @dev Thrown if an access-restricted function is called by an address that is not\n    ///      the connected Credit Facade, or an allowed adapter\n    error AdaptersOrCreditFacadeOnlyException();\n\n    /// @dev Thrown if an access-restricted function is called by an address that is not\n    ///      the connected Credit Facade\n    error CreditFacadeOnlyException();\n\n    /// @dev Thrown if an access-restricted function is called by an address that is not\n    ///      the connected Credit Configurator\n    error CreditConfiguratorOnlyException();\n\n    /// @dev Thrown on attempting to open a Credit Account for or transfer a Credit Account\n    ///      to the zero address or an address that already owns a Credit Account\n    error ZeroAddressOrUserAlreadyHasAccountException();\n\n    /// @dev Thrown on attempting to execute an order to an address that is not an allowed\n    ///      target contract\n    error TargetContractNotAllowedException();\n\n    /// @dev Thrown on failing a full collateral check after an operation\n    error NotEnoughCollateralException();\n\n    /// @dev Thrown on attempting to receive a token that is not a collateral token\n    ///      or was forbidden\n    error TokenNotAllowedException();\n\n    /// @dev Thrown if an attempt to approve a collateral token to a target contract failed\n    error AllowanceFailedException();\n\n    /// @dev Thrown on attempting to perform an action for an address that owns no Credit Account\n    error HasNoOpenedAccountException();\n\n    /// @dev Thrown on attempting to add a token that is already in a collateral list\n    error TokenAlreadyAddedException();\n\n    /// @dev Thrown on configurator attempting to add more than 256 collateral tokens\n    error TooManyTokensException();\n\n    /// @dev Thrown if more than the maximal number of tokens were enabled on a Credit Account,\n    ///      and there are not enough unused token to disable\n    error TooManyEnabledTokensException();\n\n    /// @dev Thrown when a reentrancy into the contract is attempted\n    error ReentrancyLockException();\n}\n\n/// @notice All Credit Manager functions are access-restricted and can only be called\n///         by the Credit Facade or allowed adapters. Users are not allowed to\n///         interact with the Credit Manager directly\ninterface ICreditManagerV2 is\n    ICreditManagerV2Events,\n    ICreditManagerV2Exceptions,\n    IVersion\n{\n    //\n    // CREDIT ACCOUNT MANAGEMENT\n    //\n\n    ///  @dev Opens credit account and borrows funds from the pool.\n    /// - Takes Credit Account from the factory;\n    /// - Requests the pool to lend underlying to the Credit Account\n    ///\n    /// @param borrowedAmount Amount to be borrowed by the Credit Account\n    /// @param onBehalfOf The owner of the newly opened Credit Account\n    function openCreditAccount(uint256 borrowedAmount, address onBehalfOf)\n        external\n        returns (address);\n\n    ///  @dev Closes a Credit Account - covers both normal closure and liquidation\n    /// - Checks whether the contract is paused, and, if so, if the payer is an emergency liquidator.\n    ///   Only emergency liquidators are able to liquidate account while the CM is paused.\n    ///   Emergency liquidations do not pay a liquidator premium or liquidation fees.\n    /// - Calculates payments to various recipients on closure:\n    ///    + Computes amountToPool, which is the amount to be sent back to the pool.\n    ///      This includes the principal, interest and fees, but can't be more than\n    ///      total position value\n    ///    + Computes remainingFunds during liquidations - these are leftover funds\n    ///      after paying the pool and the liquidator, and are sent to the borrower\n    ///    + Computes protocol profit, which includes interest and liquidation fees\n    ///    + Computes loss if the totalValue is less than borrow amount + interest\n    /// - Checks the underlying token balance:\n    ///    + if it is larger than amountToPool, then the pool is paid fully from funds on the Credit Account\n    ///    + else tries to transfer the shortfall from the payer - either the borrower during closure, or liquidator during liquidation\n    /// - Send assets to the \"to\" address, as long as they are not included into skipTokenMask\n    /// - If convertWETH is true, the function converts WETH into ETH before sending\n    /// - Returns the Credit Account back to factory\n    ///\n    /// @param borrower Borrower address\n    /// @param closureActionType Whether the account is closed, liquidated or liquidated due to expiry\n    /// @param totalValue Portfolio value for liqution, 0 for ordinary closure\n    /// @param payer Address which would be charged if credit account has not enough funds to cover amountToPool\n    /// @param to Address to which the leftover funds will be sent\n    /// @param skipTokenMask Tokenmask contains 1 for tokens which needed to be skipped for sending\n    /// @param convertWETH If true converts WETH to ETH\n    function closeCreditAccount(\n        address borrower,\n        ClosureAction closureActionType,\n        uint256 totalValue,\n        address payer,\n        address to,\n        uint256 skipTokenMask,\n        bool convertWETH\n    ) external returns (uint256 remainingFunds);\n\n    /// @dev Manages debt size for borrower:\n    ///\n    /// - Increase debt:\n    ///   + Increases debt by transferring funds from the pool to the credit account\n    ///   + Updates the cumulative index to keep interest the same. Since interest\n    ///     is always computed dynamically as borrowedAmount * (cumulativeIndexNew / cumulativeIndexOpen - 1),\n    ///     cumulativeIndexOpen needs to be updated, as the borrow amount has changed\n    ///\n    /// - Decrease debt:\n    ///   + Repays debt partially + all interest and fees accrued thus far\n    ///   + Updates cunulativeIndex to cumulativeIndex now\n    ///\n    /// @param creditAccount Address of the Credit Account to change debt for\n    /// @param amount Amount to increase / decrease the principal by\n    /// @param increase True to increase principal, false to decrease\n    /// @return newBorrowedAmount The new debt principal\n    function manageDebt(\n        address creditAccount,\n        uint256 amount,\n        bool increase\n    ) external returns (uint256 newBorrowedAmount);\n\n    /// @dev Adds collateral to borrower's credit account\n    /// @param payer Address of the account which will be charged to provide additional collateral\n    /// @param creditAccount Address of the Credit Account\n    /// @param token Collateral token to add\n    /// @param amount Amount to add\n    function addCollateral(\n        address payer,\n        address creditAccount,\n        address token,\n        uint256 amount\n    ) external;\n\n    /// @dev Transfers Credit Account ownership to another address\n    /// @param from Address of previous owner\n    /// @param to Address of new owner\n    function transferAccountOwnership(address from, address to) external;\n\n    /// @dev Requests the Credit Account to approve a collateral token to another contract.\n    /// @param borrower Borrower's address\n    /// @param targetContract Spender to change allowance for\n    /// @param token Collateral token to approve\n    /// @param amount New allowance amount\n    function approveCreditAccount(\n        address borrower,\n        address targetContract,\n        address token,\n        uint256 amount\n    ) external;\n\n    /// @dev Requests a Credit Account to make a low-level call with provided data\n    /// This is the intended pathway for state-changing interactions with 3rd-party protocols\n    /// @param borrower Borrower's address\n    /// @param targetContract Contract to be called\n    /// @param data Data to pass with the call\n    function executeOrder(\n        address borrower,\n        address targetContract,\n        bytes memory data\n    ) external returns (bytes memory);\n\n    //\n    // COLLATERAL VALIDITY AND ACCOUNT HEALTH CHECKS\n    //\n\n    /// @dev Enables a token on a Credit Account, including it\n    /// into account health and total value calculations\n    /// @param creditAccount Address of a Credit Account to enable the token for\n    /// @param token Address of the token to be enabled\n    function checkAndEnableToken(address creditAccount, address token) external;\n\n    /// @dev Optimized health check for individual swap-like operations.\n    /// @notice Fast health check assumes that only two tokens (input and output)\n    ///         participate in the operation and computes a % change in weighted value between\n    ///         inbound and outbound collateral. The cumulative negative change across several\n    ///         swaps in sequence cannot be larger than feeLiquidation (a fee that the\n    ///         protocol is ready to waive if needed). Since this records a % change\n    ///         between just two tokens, the corresponding % change in TWV will always be smaller,\n    ///         which makes this check safe.\n    ///         More details at https://dev.gearbox.fi/docs/documentation/risk/fast-collateral-check#fast-check-protection\n    /// @param creditAccount Address of the Credit Account\n    /// @param tokenIn Address of the token spent by the swap\n    /// @param tokenOut Address of the token received from the swap\n    /// @param balanceInBefore Balance of tokenIn before the operation\n    /// @param balanceOutBefore Balance of tokenOut before the operation\n    function fastCollateralCheck(\n        address creditAccount,\n        address tokenIn,\n        address tokenOut,\n        uint256 balanceInBefore,\n        uint256 balanceOutBefore\n    ) external;\n\n    /// @dev Performs a full health check on an account, summing up\n    /// value of all enabled collateral tokens\n    /// @param creditAccount Address of the Credit Account to check\n    function fullCollateralCheck(address creditAccount) external;\n\n    /// @dev Checks that the number of enabled tokens on a Credit Account\n    ///      does not violate the maximal enabled token limit and tries\n    ///      to disable unused tokens if it does\n    /// @param creditAccount Account to check enabled tokens for\n    function checkAndOptimizeEnabledTokens(address creditAccount) external;\n\n    /// @dev Disables a token on a credit account\n    /// @notice Usually called by adapters to disable spent tokens during a multicall,\n    ///         but can also be called separately from the Credit Facade to remove\n    ///         unwanted tokens\n    /// @return True if token mask was change otherwise False\n    function disableToken(address creditAccount, address token)\n        external\n        returns (bool);\n\n    //\n    // GETTERS\n    //\n\n    /// @dev Returns the address of a borrower's Credit Account, or reverts if there is none.\n    /// @param borrower Borrower's address\n    function getCreditAccountOrRevert(address borrower)\n        external\n        view\n        returns (address);\n\n    /// @dev Computes amounts that must be sent to various addresses before closing an account\n    /// @param totalValue Credit Accounts total value in underlying\n    /// @param closureActionType Type of account closure\n    ///        * CLOSE_ACCOUNT: The account is healthy and is closed normally\n    ///        * LIQUIDATE_ACCOUNT: The account is unhealthy and is being liquidated to avoid bad debt\n    ///        * LIQUIDATE_EXPIRED_ACCOUNT: The account has expired and is being liquidated (lowered liquidation premium)\n    ///        * LIQUIDATE_PAUSED: The account is liquidated while the system is paused due to emergency (no liquidation premium)\n    /// @param borrowedAmount Credit Account's debt principal\n    /// @param borrowedAmountWithInterest Credit Account's debt principal + interest\n    /// @return amountToPool Amount of underlying to be sent to the pool\n    /// @return remainingFunds Amount of underlying to be sent to the borrower (only applicable to liquidations)\n    /// @return profit Protocol's profit from fees (if any)\n    /// @return loss Protocol's loss from bad debt (if any)\n    function calcClosePayments(\n        uint256 totalValue,\n        ClosureAction closureActionType,\n        uint256 borrowedAmount,\n        uint256 borrowedAmountWithInterest\n    )\n        external\n        view\n        returns (\n            uint256 amountToPool,\n            uint256 remainingFunds,\n            uint256 profit,\n            uint256 loss\n        );\n\n    /// @dev Calculates the debt accrued by a Credit Account\n    /// @param creditAccount Address of the Credit Account\n    /// @return borrowedAmount The debt principal\n    /// @return borrowedAmountWithInterest The debt principal + accrued interest\n    /// @return borrowedAmountWithInterestAndFees The debt principal + accrued interest and protocol fees\n    function calcCreditAccountAccruedInterest(address creditAccount)\n        external\n        view\n        returns (\n            uint256 borrowedAmount,\n            uint256 borrowedAmountWithInterest,\n            uint256 borrowedAmountWithInterestAndFees\n        );\n\n    /// @dev Maps Credit Accounts to bit masks encoding their enabled token sets\n    /// Only enabled tokens are counted as collateral for the Credit Account\n    /// @notice An enabled token mask encodes an enabled token by setting\n    ///         the bit at the position equal to token's index to 1\n    function enabledTokensMap(address creditAccount)\n        external\n        view\n        returns (uint256);\n\n    /// @dev Maps the Credit Account to its current percentage drop across all swaps since\n    ///      the last full check, in RAY format\n    function cumulativeDropAtFastCheckRAY(address creditAccount)\n        external\n        view\n        returns (uint256);\n\n    /// @dev Returns the collateral token at requested index and its liquidation threshold\n    /// @param id The index of token to return\n    function collateralTokens(uint256 id)\n        external\n        view\n        returns (address token, uint16 liquidationThreshold);\n\n    /// @dev Returns the collateral token with requested mask and its liquidationThreshold\n    /// @param tokenMask Token mask corresponding to the token\n    function collateralTokensByMask(uint256 tokenMask)\n        external\n        view\n        returns (address token, uint16 liquidationThreshold);\n\n    /// @dev Total number of known collateral tokens.\n    function collateralTokensCount() external view returns (uint256);\n\n    /// @dev Returns the mask for the provided token\n    /// @param token Token to returns the mask for\n    function tokenMasksMap(address token) external view returns (uint256);\n\n    /// @dev Bit mask encoding a set of forbidden tokens\n    function forbiddenTokenMask() external view returns (uint256);\n\n    /// @dev Maps allowed adapters to their respective target contracts.\n    function adapterToContract(address adapter) external view returns (address);\n\n    /// @dev Maps 3rd party contracts to their respective adapters\n    function contractToAdapter(address targetContract)\n        external\n        view\n        returns (address);\n\n    /// @dev Address of the underlying asset\n    function underlying() external view returns (address);\n\n    /// @dev Address of the connected pool\n    function pool() external view returns (address);\n\n    /// @dev Address of the connected pool\n    /// @notice [DEPRECATED]: use pool() instead.\n    function poolService() external view returns (address);\n\n    /// @dev A map from borrower addresses to Credit Account addresses\n    function creditAccounts(address borrower) external view returns (address);\n\n    /// @dev Address of the connected Credit Configurator\n    function creditConfigurator() external view returns (address);\n\n    /// @dev Address of WETH\n    function wethAddress() external view returns (address);\n\n    /// @dev Returns the liquidation threshold for the provided token\n    /// @param token Token to retrieve the LT for\n    function liquidationThresholds(address token)\n        external\n        view\n        returns (uint16);\n\n    /// @dev The maximal number of enabled tokens on a single Credit Account\n    function maxAllowedEnabledTokenLength() external view returns (uint8);\n\n    /// @dev Maps addresses to their status as emergency liquidator.\n    /// @notice Emergency liquidators are trusted addresses\n    /// that are able to liquidate positions while the contracts are paused,\n    /// e.g. when there is a risk of bad debt while an exploit is being patched.\n    /// In the interest of fairness, emergency liquidators do not receive a premium\n    /// And are compensated by the Gearbox DAO separately.\n    function canLiquidateWhilePaused(address) external view returns (bool);\n\n    /// @dev Returns the fee parameters of the Credit Manager\n    /// @return feeInterest Percentage of interest taken by the protocol as profit\n    /// @return feeLiquidation Percentage of account value taken by the protocol as profit\n    ///         during unhealthy account liquidations\n    /// @return liquidationDiscount Multiplier that reduces the effective totalValue during unhealthy account liquidations,\n    ///         allowing the liquidator to take the unaccounted for remainder as premium. Equal to (1 - liquidationPremium)\n    /// @return feeLiquidationExpired Percentage of account value taken by the protocol as profit\n    ///         during expired account liquidations\n    /// @return liquidationDiscountExpired Multiplier that reduces the effective totalValue during expired account liquidations,\n    ///         allowing the liquidator to take the unaccounted for remainder as premium. Equal to (1 - liquidationPremiumExpired)\n    function fees()\n        external\n        view\n        returns (\n            uint16 feeInterest,\n            uint16 feeLiquidation,\n            uint16 liquidationDiscount,\n            uint16 feeLiquidationExpired,\n            uint16 liquidationDiscountExpired\n        );\n\n    /// @dev Address of the connected Credit Facade\n    function creditFacade() external view returns (address);\n\n    /// @dev Address of the connected Price Oracle\n    function priceOracle() external view returns (IPriceOracleV2);\n\n    /// @dev Address of the universal adapter\n    function universalAdapter() external view returns (address);\n\n    /// @dev Contract's version\n    function version() external view returns (uint256);\n\n    /// @dev Paused() state\n    function checkEmergencyPausable(address caller, bool state)\n        external\n        returns (bool);\n}\n"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize, which returns 0 for contracts in\n        // construction, since the code is only stored at the end of the\n        // constructor execution.\n\n        uint256 size;\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracle.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\nimport { IVersion } from \"./IVersion.sol\";\n\ninterface IPriceOracleV2Events {\n    /// @dev Emits when a new price feed is added\n    event NewPriceFeed(address indexed token, address indexed priceFeed);\n}\n\ninterface IPriceOracleV2Exceptions {\n    /// @dev Thrown if a price feed returns 0\n    error ZeroPriceException();\n\n    /// @dev Thrown if the last recorded result was not updated in the last round\n    error ChainPriceStaleException();\n\n    /// @dev Thrown on attempting to get a result for a token that does not have a price feed\n    error PriceOracleNotExistsException();\n}\n\n/// @title Price oracle interface\ninterface IPriceOracleV2 is\n    IPriceOracleV2Events,\n    IPriceOracleV2Exceptions,\n    IVersion\n{\n    /// @dev Converts a quantity of an asset to USD (decimals = 8).\n    /// @param amount Amount to convert\n    /// @param token Address of the token to be converted\n    function convertToUSD(uint256 amount, address token)\n        external\n        view\n        returns (uint256);\n\n    /// @dev Converts a quantity of USD (decimals = 8) to an equivalent amount of an asset\n    /// @param amount Amount to convert\n    /// @param token Address of the token converted to\n    function convertFromUSD(uint256 amount, address token)\n        external\n        view\n        returns (uint256);\n\n    /// @dev Converts one asset into another\n    ///\n    /// @param amount Amount to convert\n    /// @param tokenFrom Address of the token to convert from\n    /// @param tokenTo Address of the token to convert to\n    function convert(\n        uint256 amount,\n        address tokenFrom,\n        address tokenTo\n    ) external view returns (uint256);\n\n    /// @dev Returns collateral values for two tokens, required for a fast check\n    /// @param amountFrom Amount of the outbound token\n    /// @param tokenFrom Address of the outbound token\n    /// @param amountTo Amount of the inbound token\n    /// @param tokenTo Address of the inbound token\n    /// @return collateralFrom Value of the outbound token amount in USD\n    /// @return collateralTo Value of the inbound token amount in USD\n    function fastCheck(\n        uint256 amountFrom,\n        address tokenFrom,\n        uint256 amountTo,\n        address tokenTo\n    ) external view returns (uint256 collateralFrom, uint256 collateralTo);\n\n    /// @dev Returns token's price in USD (8 decimals)\n    /// @param token The token to compute the price for\n    function getPrice(address token) external view returns (uint256);\n\n    /// @dev Returns the price feed address for the passed token\n    /// @param token Token to get the price feed for\n    function priceFeeds(address token)\n        external\n        view\n        returns (address priceFeed);\n\n    /// @dev Returns the price feed for the passed token,\n    ///      with additional parameters\n    /// @param token Token to get the price feed for\n    function priceFeedsWithFlags(address token)\n        external\n        view\n        returns (\n            address priceFeed,\n            bool skipCheck,\n            uint256 decimals\n        );\n}\n\ninterface IPriceOracleV2Ext is IPriceOracleV2 {\n    /// @dev Sets a price feed if it doesn't exist, or updates an existing one\n    /// @param token Address of the token to set the price feed for\n    /// @param priceFeed Address of a USD price feed adhering to Chainlink's interface\n    function addPriceFeed(address token, address priceFeed) external;\n}\n"
    },
    "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol": {
      "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n/// @title IVersion\n/// @dev Declares a version function which returns the contract's version\ninterface IVersion {\n    /// @dev Returns contract version\n    function version() external view returns (uint256);\n}\n"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 1000000
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    },
    "libraries": {}
  }
}