{ "language": "Solidity", "sources": { "@gearbox-protocol/integrations-v2/contracts/adapters/uniswap/UniswapV2.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\";\n\nimport { AbstractAdapter } from \"@gearbox-protocol/core-v2/contracts/adapters/AbstractAdapter.sol\";\nimport { IUniswapV2Router02 } from \"../../integrations/uniswap/IUniswapV2Router02.sol\";\nimport { IUniswapV2Adapter } from \"../../interfaces/uniswap/IUniswapV2Adapter.sol\";\nimport { IAdapter, AdapterType } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\n\nimport { RAY } from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\n// EXCEPTIONS\nimport { NotImplementedException } from \"@gearbox-protocol/core-v2/contracts/interfaces/IErrors.sol\";\n\n/// @title UniswapV2 Router adapter\ncontract UniswapV2Adapter is\n AbstractAdapter,\n IUniswapV2Adapter,\n ReentrancyGuard\n{\n AdapterType public constant _gearboxAdapterType =\n AdapterType.UNISWAP_V2_ROUTER;\n uint16 public constant _gearboxAdapterVersion = 2;\n\n /// @dev Constructor\n /// @param _creditManager Address Credit manager\n /// @param _router Address of IUniswapV2Router02\n constructor(address _creditManager, address _router)\n AbstractAdapter(_creditManager, _router)\n {}\n\n /**\n * @dev Sends an order to swap tokens to exact tokens using a Uniswap-compatible protocol\n * - Makes a max allowance fast check call to target, replacing the `to` parameter with the CA address\n * @param amountOut The amount of output tokens to receive.\n * @param amountInMax The maximum amount of input tokens that can be required before the transaction reverts.\n * @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of\n * addresses must exist and have liquidity.\n * @param deadline Unix timestamp after which the transaction will revert.\n * for more information, see: https://uniswap.org/docs/v2/smart-contracts/router02/\n * @notice `to` is ignored, since it is forbidden to transfer funds from a CA\n * @notice Fast check parameters:\n * Input token: First token in the path\n * Output token: Last token in the path\n * Input token is allowed, since the target does a transferFrom for the input token\n * The input token does not need to be disabled, because this does not spend the entire\n * balance, generally\n */\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address,\n uint256 deadline\n ) external override nonReentrant returns (uint256[] memory amounts) {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV2-1]\n\n address tokenIn = path[0]; // F:[AUV2-2]\n address tokenOut = path[path.length - 1]; // F:[AUV2-2]\n\n amounts = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n IUniswapV2Router02.swapTokensForExactTokens.selector,\n amountOut,\n amountInMax,\n path,\n creditAccount,\n deadline\n ),\n true,\n false\n ),\n (uint256[])\n ); // F:[AUV2-2]\n }\n\n /**\n * @dev Sends an order to swap an exact amount of token to another token using a Uniswap-compatible protocol\n * - Makes a max allowance fast check call to target, replacing the `to` parameter with the CA address\n * @param amountIn The amount of input tokens to send.\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of\n * addresses must exist and have liquidity.\n * @param deadline Unix timestamp after which the transaction will revert.\n * for more information, see: https://uniswap.org/docs/v2/smart-contracts/router02/\n * @notice `to` is ignored, since it is forbidden to transfer funds from a CA\n * @notice Fast check parameters:\n * Input token: First token in the path\n * Output token: Last token in the path\n * Input token is allowed, since the target does a transferFrom for the input token\n * The input token does not need to be disabled, because this does not spend the entire\n * balance, generally\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address,\n uint256 deadline\n ) external override nonReentrant returns (uint256[] memory amounts) {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV2-1]\n\n address tokenIn = path[0]; // F:[AUV2-3]\n address tokenOut = path[path.length - 1]; // F:[AUV2-3]\n\n amounts = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n IUniswapV2Router02.swapExactTokensForTokens.selector,\n amountIn,\n amountOutMin,\n path,\n creditAccount,\n deadline\n ),\n true,\n false\n ),\n (uint256[])\n ); // F:[AUV2-3]\n }\n\n /**\n * @dev Sends an order to swap the entire token balance to another token using a Uniswap-compatible protocol\n * - Makes a max allowance fast check call to target, replacing the `to` parameter with the CA address\n * @param rateMinRAY The minimal exchange rate between the input and the output tokens.\n * @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of\n * addresses must exist and have liquidity.\n * @param deadline Unix timestamp after which the transaction will revert.\n * for more information, see: https://uniswap.org/docs/v2/smart-contracts/router02/\n * @notice Under the hood, calls swapExactTokensForTokens, passing balance minus 1 as the amount\n * @notice Fast check parameters:\n * Input token: First token in the path\n * Output token: Last token in the path\n * Input token is allowed, since the target does a transferFrom for the input token\n * The input token does need to be disabled, because this spends the entire balance\n */\n function swapAllTokensForTokens(\n uint256 rateMinRAY,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant returns (uint256[] memory amounts) {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV2-1]\n\n address tokenIn = path[0]; // F:[AUV2-4]\n address tokenOut = path[path.length - 1]; // F:[AUV2-4]\n\n uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // F:[AUV2-4]\n\n if (balanceInBefore > 1) {\n unchecked {\n balanceInBefore--;\n }\n\n amounts = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n IUniswapV2Router02.swapExactTokensForTokens.selector,\n balanceInBefore,\n (balanceInBefore * rateMinRAY) / RAY,\n path,\n creditAccount,\n deadline\n ),\n true,\n true\n ),\n (uint256[])\n ); // F:[AUV2-4]\n }\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address, // token,\n uint256, // liquidity,\n uint256, // amountTokenMin,\n uint256, // amountETHMin,\n address, // to,\n uint256 // deadline\n ) external pure override returns (uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address, // token,\n uint256, // liquidity,\n uint256, // amountTokenMin,\n uint256, // amountETHMin,\n address, // to,\n uint256, // deadline,\n bool, // approveMax,\n uint8, // v,\n bytes32, // r,\n bytes32 // s\n ) external pure override returns (uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as FeeOnTransfer tokens are not supported by Gearbox\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint256, // amountIn,\n uint256, // amountOutMin,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external pure override {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as FeeOnTransfer tokens are not supported by Gearbox\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint256, // amountOutMin,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external payable override {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as FeeOnTransfer tokens are not supported by Gearbox\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint256, // amountIn,\n uint256, // amountOutMin,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external pure override {\n revert NotImplementedException();\n }\n\n /// @dev Returns the address of the Uniswap pool factory\n function factory() external view override returns (address) {\n return IUniswapV2Router02(targetContract).factory();\n }\n\n /// @dev Returns the address of WETH\n function WETH() external view override returns (address) {\n return IUniswapV2Router02(targetContract).WETH();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function addLiquidity(\n address, // tokenA,\n address, // tokenB,\n uint256, // amountADesired,\n uint256, // amountBDesired,\n uint256, // amountAMin,\n uint256, // amountBMin,\n address, // to,\n uint256 // deadline\n )\n external\n pure\n override\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function addLiquidityETH(\n address, // token,\n uint256, // amountTokenDesired,\n uint256, // amountTokenMin,\n uint256, // amountETHMin,\n address, // to,\n uint256 // deadline\n )\n external\n payable\n override\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function removeLiquidity(\n address, // tokenA,\n address, // tokenB,\n uint256, // liquidity,\n uint256, // amountAMin,\n uint256, // amountBMin,\n address, // to,\n uint256 // deadline\n ) external pure override returns (uint256, uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function removeLiquidityETH(\n address, // token,\n uint256, // liquidity,\n uint256, // amountTokenMin,\n uint256, // amountETHMin,\n address, // to,\n uint256 // deadline\n ) external pure override returns (uint256, uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function removeLiquidityWithPermit(\n address, // tokenA,\n address, // tokenB,\n uint256, // liquidity,\n uint256, // amountAMin,\n uint256, // amountBMin,\n address, // to,\n uint256, // deadline,\n bool, // approveMax,\n uint8, // v,\n bytes32, // r,\n bytes32 // s\n ) external pure override returns (uint256, uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as Uniswap liquidity provision is not yet supported\n function removeLiquidityETHWithPermit(\n address, // token,\n uint256, // liquidity,\n uint256, // amountTokenMin,\n uint256, // amountETHMin,\n address, // to,\n uint256, // deadline,\n bool, // approveMax,\n uint8, // v,\n bytes32, // r,\n bytes32 // s\n ) external pure override returns (uint256, uint256) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function swapExactETHForTokens(\n uint256, // amountOutMin,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external payable override returns (uint256[] memory) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function swapTokensForExactETH(\n uint256, // amountOut,\n uint256, // amountInMax,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external pure override returns (uint256[] memory) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function swapExactTokensForETH(\n uint256, // amountIn,\n uint256, //amountOutMin,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external pure override returns (uint256[] memory) {\n revert NotImplementedException();\n }\n\n /// @dev Not implemented, as native ETH is not supported\n function swapETHForExactTokens(\n uint256, // amountOut,\n address[] calldata, // path,\n address, // to,\n uint256 // deadline\n ) external payable override returns (uint256[] memory) {\n revert NotImplementedException();\n }\n\n /// @dev Returns the amount of token B that is equivalent\n /// to a specifed amount of token A, not accounting for fees\n /// @param amountA The amount of the input token being swapped\n /// @param reserveA Size of the input token reserve\n /// @param reserveB Size of the output token reserve\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) external view override returns (uint256 amountB) {\n return\n IUniswapV2Router02(targetContract).quote(\n amountA,\n reserveA,\n reserveB\n ); // F:[AUV2-5]\n }\n\n /// @dev Returns the amount of the output token received when swapping\n /// a specific amount of the input token\n /// @param amountIn The amount of input token being swapped\n /// @param reserveIn Size of the input token reserve\n /// @param reserveOut Size of the output token reserve\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view override returns (uint256 amountOut) {\n return\n IUniswapV2Router02(targetContract).getAmountOut(\n amountIn,\n reserveIn,\n reserveOut\n ); // F:[AUV2-6]\n }\n\n /// @dev Returns the amount of the input token required to\n /// receive a specified amount of the output token\n /// @param amountOut The desired amount of output token\n /// @param reserveIn Size of the input token reserve\n /// @param reserveOut Size of the output token reserve\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view override returns (uint256 amountIn) {\n return\n IUniswapV2Router02(targetContract).getAmountIn(\n amountOut,\n reserveIn,\n reserveOut\n ); // F:[AUV2-7]\n }\n\n /// @dev Returns the amount of tokens received for each token along the path\n /// receive a specified amount of the output token\n /// @param amountIn The amount of input token being swapped\n /// @param path An array of token addresses\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n override\n returns (uint256[] memory amounts)\n {\n return IUniswapV2Router02(targetContract).getAmountsOut(amountIn, path); // F:[AUV2-8]\n }\n\n /// @dev Returns the amount of tokens required for each token in the path,\n /// in order to receive the spcified amount\n /// receive a specified amount of the output token\n /// @param amountOut The desired amount of output token\n /// @param path An array of token addresses\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n override\n returns (uint256[] memory amounts)\n {\n return IUniswapV2Router02(targetContract).getAmountsIn(amountOut, path); // F:[AUV2-9]\n }\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" }, "@gearbox-protocol/core-v2/contracts/libraries/Constants.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// 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/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 creditFacade;\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 creditFacade = ICreditManagerV2(_creditManager).creditFacade(); // 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 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 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 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 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 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 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 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 if (msg.sender != creditFacade) {\n creditManager.checkAndOptimizeEnabledTokens(creditAccount);\n }\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" }, "@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 Credit Facade connected to the adapter's Credit Manager\n function creditFacade() external view returns (address);\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" }, "@gearbox-protocol/integrations-v2/contracts/integrations/uniswap/IUniswapV2Router02.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.2;\n\nimport \"./IUniswapV2Router01.sol\";\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountETH);\n\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountETH);\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external;\n\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable;\n\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external;\n\n function factory() external view override returns (address);\n\n function WETH() external view override returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n )\n external\n override\n returns (\n uint256 amountA,\n uint256 amountB,\n uint256 liquidity\n );\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n override\n returns (\n uint256 amountToken,\n uint256 amountETH,\n uint256 liquidity\n );\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external override returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external override returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external override returns (uint256 amountToken, uint256 amountETH);\n\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override returns (uint256[] memory amounts);\n\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable override returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override returns (uint256[] memory amounts);\n\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable override returns (uint256[] memory amounts);\n\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) external view override returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view override returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view override returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n override\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n override\n returns (uint256[] memory amounts);\n}\n" }, "@gearbox-protocol/integrations-v2/contracts/interfaces/uniswap/IUniswapV2Adapter.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 { IAdapter } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\nimport { IUniswapV2Router02 } from \"../../integrations/uniswap/IUniswapV2Router02.sol\";\n\ninterface IUniswapV2Adapter is IAdapter, IUniswapV2Router02 {\n /// @dev Sends an order to swap the entire token balance to another token using a Uniswap-compatible protocol\n /// @param rateMinRAY The minimal exchange rate between the input and the output tokens.\n //// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of\n /// addresses must exist and have liquidity.\n /// @param deadline Unix timestamp after which the transaction will revert.\n /// @return amounts amountsOut, in the order of swaps in the path\n function swapAllTokensForTokens(\n uint256 rateMinRAY,\n address[] calldata path,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\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" }, "@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/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" }, "@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" }, "@gearbox-protocol/integrations-v2/contracts/integrations/uniswap/IUniswapV2Router01.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n function factory() external view returns (address);\n\n function WETH() external view returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n )\n external\n returns (\n uint256 amountA,\n uint256 amountB,\n uint256 liquidity\n );\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (\n uint256 amountToken,\n uint256 amountETH,\n uint256 liquidity\n );\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) external view returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external view returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path)\n external\n view\n returns (uint256[] memory amounts);\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 1000000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }