{ "language": "Solidity", "sources": { "@gearbox-protocol/integrations-v2/contracts/adapters/uniswap/UniswapV3.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;\npragma abicoder v2;\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 { IUniswapV3Adapter } from \"../../interfaces/uniswap/IUniswapV3Adapter.sol\";\nimport { AdapterType } from \"@gearbox-protocol/core-v2/contracts/interfaces/adapters/IAdapter.sol\";\nimport { ISwapRouter } from \"../../integrations/uniswap/IUniswapV3.sol\";\nimport { BytesLib } from \"../../integrations/uniswap/BytesLib.sol\";\n\nimport { RAY } from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\n/// @dev The length of the bytes encoded address\nuint256 constant ADDR_SIZE = 20;\n\n/// @dev The length of the uint24 encoded address\nuint256 constant FEE_SIZE = 3;\n\n/// @dev Minimal path length in bytes\nuint256 constant MIN_PATH_LENGTH = 2 * ADDR_SIZE + FEE_SIZE;\n\n/// @dev Number of bytes in path per single token\nuint256 constant ADDR_PLUS_FEE_LENGTH = ADDR_SIZE + FEE_SIZE;\n\n/// @title UniswapV3 Router adapter\ncontract UniswapV3Adapter is\n AbstractAdapter,\n IUniswapV3Adapter,\n ReentrancyGuard\n{\n using BytesLib for bytes;\n\n AdapterType public constant _gearboxAdapterType =\n AdapterType.UNISWAP_V3_ROUTER;\n uint16 public constant _gearboxAdapterVersion = 2;\n\n /// @dev Constructor\n /// @param _creditManager Address Credit manager\n /// @param _router Address of ISwapRouter\n constructor(address _creditManager, address _router)\n AbstractAdapter(_creditManager, _router)\n {}\n\n /// @notice Sends an order to swap `amountIn` of one token for as much as possible of another token\n /// - Makes a max allowance fast check call, replacing the recipient with the Credit Account\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params)\n external\n payable\n override\n nonReentrant\n returns (uint256 amountOut)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n ExactInputSingleParams memory paramsUpdate = params; // F:[AUV3-2,10]\n paramsUpdate.recipient = creditAccount; // F:[AUV3-2,10]\n\n amountOut = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n params.tokenIn,\n params.tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactInputSingle.selector,\n paramsUpdate\n ),\n true,\n false\n ),\n (uint256)\n ); // F:[AUV2-2,10]\n }\n\n /// @notice Sends an order to swap the entire balance of one token for as much as possible of another token\n /// - Fills the `ExactInputSingleParams` struct\n /// - Makes a max allowance fast check call, passing the new struct as params\n /// @param params The parameters necessary for the swap, encoded as `ExactAllInputSingleParams` in calldata\n /// `ExactAllInputSingleParams` has the following fields:\n /// - tokenIn - same as normal params\n /// - tokenOut - same as normal params\n /// - fee - same as normal params\n /// - deadline - same as normal params\n /// - rateMinRAY - Minimal exchange rate between the input and the output tokens\n /// - sqrtPriceLimitX96 - same as normal params\n /// @return amountOut The amount of the received token\n function exactAllInputSingle(ExactAllInputSingleParams calldata params)\n external\n returns (uint256 amountOut)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n uint256 balanceInBefore = IERC20(params.tokenIn).balanceOf(\n creditAccount\n ); // F:[AUV3-3]\n\n // We keep 1 on tokenIn balance for gas efficiency\n if (balanceInBefore > 1) {\n unchecked {\n balanceInBefore--;\n }\n\n ExactInputSingleParams\n memory paramsUpdate = ExactInputSingleParams({\n tokenIn: params.tokenIn,\n tokenOut: params.tokenOut,\n fee: params.fee,\n recipient: creditAccount,\n deadline: params.deadline,\n amountIn: balanceInBefore,\n amountOutMinimum: (balanceInBefore * params.rateMinRAY) /\n RAY,\n sqrtPriceLimitX96: params.sqrtPriceLimitX96\n }); // F:[AUV3-3]\n\n amountOut = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n params.tokenIn,\n params.tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactInputSingle.selector,\n paramsUpdate\n ),\n true,\n true\n ),\n (uint256)\n ); // F:[AUV3-3]\n }\n }\n\n /// @notice Sends an order to swap `amountIn` of one token for as much as possible of another along the specified path\n /// - Makes a max allowance fast check call, replacing the recipient with the Credit Account\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params)\n external\n payable\n override\n nonReentrant\n returns (uint256 amountOut)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n (address tokenIn, address tokenOut) = _extractTokens(params.path); // F:[AUV3-4]\n\n ExactInputParams memory paramsUpdate = params; // F:[AUV3-4]\n paramsUpdate.recipient = creditAccount; // F:[AUV3-4]\n\n amountOut = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactInput.selector,\n paramsUpdate\n ),\n true,\n false\n ),\n (uint256)\n ); // F:[AUV3-4]\n }\n\n /// @notice Swaps the entire balance of one token for as much as possible of another along the specified path\n /// - Fills the `ExactAllInputParams` struct\n /// - Makes a max allowance fast check call, passing the new struct as `params`\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactAllInputParams` in calldata\n /// `ExactAllInputParams` has the following fields:\n /// - path - same as normal params\n /// - deadline - same as normal params\n /// - rateMinRAY - minimal exchange rate between the input and the output tokens\n /// @return amountOut The amount of the received token\n function exactAllInput(ExactAllInputParams calldata params)\n external\n returns (uint256 amountOut)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n (address tokenIn, address tokenOut) = _extractTokens(params.path); // F:[AUV3-5]\n\n uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // F:[AUV3-5]\n\n // We keep 1 on tokenIn balance for gas efficiency\n if (balanceInBefore > 1) {\n unchecked {\n balanceInBefore--;\n }\n ExactInputParams memory paramsUpdate = ExactInputParams({\n path: params.path,\n recipient: creditAccount,\n deadline: params.deadline,\n amountIn: balanceInBefore,\n amountOutMinimum: (balanceInBefore * params.rateMinRAY) / RAY\n }); // F:[AUV3-5]\n\n amountOut = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactInput.selector,\n paramsUpdate\n ),\n true,\n true\n ),\n (uint256)\n ); // F:[AUV3-5]\n }\n }\n\n /// @notice Sends an order to swap as little as possible of one token for `amountOut` of another token\n /// - Makes a max allowance fast check call, replacing the recipient with the Credit Account\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params)\n external\n payable\n override\n nonReentrant\n returns (uint256 amountIn)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n ExactOutputSingleParams memory paramsUpdate = params; // F:[AUV3-6]\n paramsUpdate.recipient = creditAccount; // F:[AUV3-6]\n\n amountIn = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n paramsUpdate.tokenIn,\n paramsUpdate.tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactOutputSingle.selector,\n paramsUpdate\n ),\n true,\n false\n ),\n (uint256)\n ); // F:[AUV3-6]\n }\n\n /// @notice Sends an order to swap as little as possible of one token for\n /// `amountOut` of another along the specified path (reversed)\n /// - Makes a max allowance fast check call, replacing the recipient with the Credit Account\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params)\n external\n payable\n override\n nonReentrant\n returns (uint256 amountIn)\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n ); // F:[AUV3-1]\n\n (address tokenOut, address tokenIn) = _extractTokens(params.path); // F:[AUV3-7]\n\n ExactOutputParams memory paramsUpdate = params; // F:[AUV3-7]\n paramsUpdate.recipient = creditAccount; // F:[AUV3-7]\n\n amountIn = abi.decode(\n _executeMaxAllowanceFastCheck(\n creditAccount,\n tokenIn,\n tokenOut,\n abi.encodeWithSelector(\n ISwapRouter.exactOutput.selector,\n paramsUpdate\n ),\n true,\n false\n ),\n (uint256)\n ); // F:[AUV3-7]\n }\n\n /// @dev Returns the input and the output token of a specified path\n /// @param path The swap path encoded according to the UniswapV3 standard\n /// @notice Discards any extra bytes that are less than ADDR_PLUS_FEE_LENGTH\n function _extractTokens(bytes memory path)\n internal\n pure\n returns (address tokenA, address tokenB)\n {\n if (path.length < MIN_PATH_LENGTH)\n revert IncorrectPathLengthException();\n tokenA = path.toAddress(0);\n tokenB = path.toAddress(\n ((path.length - ADDR_SIZE) / ADDR_PLUS_FEE_LENGTH) *\n ADDR_PLUS_FEE_LENGTH\n );\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/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/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/integrations-v2/contracts/integrations/uniswap/BytesLib.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity >=0.8.0 <0.9.0;\n\nlibrary BytesLib {\n function toAddress(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (address)\n {\n require(_bytes.length >= _start + 20, \"toAddress_outOfBounds\");\n address tempAddress;\n\n assembly {\n tempAddress := div(\n mload(add(add(_bytes, 0x20), _start)),\n 0x1000000000000000000000000\n )\n }\n\n return tempAddress;\n }\n\n function toUint24(bytes memory _bytes, uint256 _start)\n internal\n pure\n returns (uint24)\n {\n require(_start + 3 >= _start, \"toUint24_overflow\");\n require(_bytes.length >= _start + 3, \"toUint24_outOfBounds\");\n uint24 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x3), _start))\n }\n\n return tempUint;\n }\n\n function concat(bytes memory _preBytes, bytes memory _postBytes)\n internal\n pure\n returns (bytes memory)\n {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(\n 0x40,\n and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n )\n )\n }\n\n return tempBytes;\n }\n\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n ) internal pure returns (bytes memory) {\n require(_length + 31 >= _length, \"slice_overflow\");\n require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(\n add(tempBytes, lengthmod),\n mul(0x20, iszero(lengthmod))\n )\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(\n add(\n add(_bytes, lengthmod),\n mul(0x20, iszero(lengthmod))\n ),\n _start\n )\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\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 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/interfaces/uniswap/IUniswapV3Adapter.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 { ISwapRouter } from \"../../integrations/uniswap/IUniswapV3.sol\";\n\ninterface IUniswapV3AdapterExceptions {\n error IncorrectPathLengthException();\n}\n\ninterface IUniswapV3Adapter is\n IAdapter,\n ISwapRouter,\n IUniswapV3AdapterExceptions\n{\n /// @dev A struct encoding parameters for exactAllInputSingle,\n /// which is unique to the Gearbox adapter\n /// @param tokenIn Token that is spent by the swap\n /// @param tokenOut Token that is received from the swap\n /// @param fee The fee category to use\n /// @param deadline The timestamp, after which the swap will revert\n /// @param rateMinRAY The minimal exhange rate between tokenIn and tokenOut\n /// used to calculate amountOutMin on the spot, since the input amount\n /// may not always be known in advance\n /// @param sqrtPriceLimitX96 The max execution price. Will be ignored if set to 0.\n struct ExactAllInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n uint256 deadline;\n uint256 rateMinRAY;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Sends an order to swap the entire balance of one token for as much as possible of another token\n /// - Fills the `ExactInputSingleParams` struct\n /// - Makes a max allowance fast check call, passing the new struct as params\n /// @param params The parameters necessary for the swap, encoded as `ExactAllInputSingleParams` in calldata\n function exactAllInputSingle(ExactAllInputSingleParams calldata params)\n external\n returns (uint256 amountOut);\n\n /// @dev A struct encoding parameters for exactAllInput,\n /// which is unique to the Gearbox adapter\n /// @param path Bytes array encoding the sequence of swaps to perform,\n /// in the format TOKEN_FEE_TOKEN_FEE_TOKEN...\n /// @param deadline The timestamp, after which the swap will revert\n /// @param rateMinRAY The minimal exhange rate between tokenIn and tokenOut\n /// used to calculate amountOutMin on the spot, since the input amount\n /// may not always be known in advance\n struct ExactAllInputParams {\n bytes path;\n uint256 deadline;\n uint256 rateMinRAY;\n }\n\n /// @notice Swaps the entire balance of one token for as much as possible of another along the specified path\n /// - Fills the `ExactAllInputParams` struct\n /// - Makes a max allowance fast check call, passing the new struct as `params`\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactAllInputParams` in calldata\n function exactAllInput(ExactAllInputParams calldata params)\n external\n returns (uint256 amountOut);\n}\n" }, "@gearbox-protocol/integrations-v2/contracts/integrations/uniswap/IUniswapV3.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params)\n external\n payable\n returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params)\n external\n payable\n returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params)\n external\n payable\n returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params)\n external\n payable\n returns (uint256 amountIn);\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/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/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/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/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" } }, "settings": { "optimizer": { "enabled": true, "runs": 1000000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }