zellic-audit
Initial commit
f998fcd
raw
history blame
38.4 kB
{
"language": "Solidity",
"sources": {
"@gearbox-protocol/core-v2/contracts/adapters/UniversalAdapter.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IUniversalAdapter, RevocationPair } from \"../interfaces/adapters/IUniversalAdapter.sol\";\nimport { AdapterType } from \"../interfaces/adapters/IAdapter.sol\";\nimport { ICreditManagerV2 } from \"../interfaces/ICreditManagerV2.sol\";\nimport { ZeroAddressException } from \"../interfaces/IErrors.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { UNIVERSAL_CONTRACT } from \"../libraries/Constants.sol\";\n\n/// @title UniversalAdapter\n/// @dev Implements the initial version of universal adapter, which handles allowance revocations\ncontract UniversalAdapter is IUniversalAdapter {\n /// @dev The target contract, which is always the same special address for the universal adapter\n address public immutable targetContract = UNIVERSAL_CONTRACT;\n\n /// @dev The credit manager this universal adapter connects to\n ICreditManagerV2 public immutable override creditManager;\n\n /// @dev The credit facade attached to the credit manager\n address public immutable override creditFacade;\n\n AdapterType public constant _gearboxAdapterType = AdapterType.UNIVERSAL;\n uint16 public constant _gearboxAdapterVersion = 1;\n\n /// @dev Constructor\n /// @param _creditManager Address of the Credit Manager\n constructor(address _creditManager) {\n if (_creditManager == address(0)) revert ZeroAddressException();\n\n creditManager = ICreditManagerV2(_creditManager);\n creditFacade = ICreditManagerV2(_creditManager).creditFacade();\n }\n\n /// @dev Sets allowances to zero for the provided spender/token pairs, for msg.sender's CA\n /// @param revocations Pairs of spenders/tokens to revoke allowances for\n function revokeAdapterAllowances(RevocationPair[] calldata revocations)\n external\n {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n );\n\n _revokeAdapterAllowances(revocations, creditAccount);\n }\n\n /// @dev Sets allowances to zero for the provided spender/token pairs\n /// Checks that the msg.sender CA matches the expected account, since the\n /// Provided revocations can be specific to a particular CA\n /// @param revocations Pairs of spenders/tokens to revoke allowances for\n /// @param expectedCreditAccount Credit account that msg.sender is expected to have\n function revokeAdapterAllowances(\n RevocationPair[] calldata revocations,\n address expectedCreditAccount\n ) external {\n address creditAccount = creditManager.getCreditAccountOrRevert(\n msg.sender\n );\n\n if (creditAccount != expectedCreditAccount) {\n revert UnexpectedCreditAccountException(\n expectedCreditAccount,\n creditAccount\n );\n }\n\n _revokeAdapterAllowances(revocations, creditAccount);\n }\n\n /// @dev Internal implementation for allowance revocations\n /// Checks that there are no zero addresses in a pair and sets allowance to 1\n /// through CreditManager.approveCreditAccount\n /// @param revocations Pairs of spenders/tokens to revoke allowances for\n /// @param creditAccount Credit account to revoke allowances for\n function _revokeAdapterAllowances(\n RevocationPair[] calldata revocations,\n address creditAccount\n ) internal {\n uint256 numRevocations = revocations.length;\n\n for (uint256 i; i < numRevocations; ) {\n address spender = revocations[i].spender;\n address token = revocations[i].token;\n\n if (spender == address(0) || token == address(0)) {\n revert ZeroAddressException();\n }\n\n uint256 allowance = IERC20(token).allowance(creditAccount, spender);\n\n if (allowance > 1) {\n creditManager.approveCreditAccount(\n msg.sender,\n spender,\n token,\n 1\n );\n }\n\n unchecked {\n ++i;\n }\n }\n }\n\n /// @notice For demonstration purposes only. Not in V2 launch scope\n ///\n // function withdraw(address token, uint256 amount) external {\n // address creditAccount = creditManager.getCreditAccountOrRevert(\n // msg.sender\n // );\n\n // if (creditManager.tokenMasksMap(token) == 0)\n // revert(\"Token contract is not allowed\");\n\n // creditManager.executeOrder(\n // msg.sender,\n // token,\n // abi.encodeWithSelector(IERC20.transfer.selector, msg.sender, amount)\n // );\n\n // creditManager.fullCollateralCheck(creditAccount);\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/IUniversalAdapter.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IAdapter } from \"./IAdapter.sol\";\n\nstruct RevocationPair {\n address spender;\n address token;\n}\n\ninterface IUniversalAdapterExceptions {\n /// @dev Thrown when the Credit Account of msg.sender does not match the provided expected account\n error UnexpectedCreditAccountException(address expected, address actual);\n}\n\ninterface IUniversalAdapter is IAdapter, IUniversalAdapterExceptions {\n /// @dev Sets allowances to zero for provided spender/token pairs, for msg.sender's CA\n /// @param revocations Pairs of spenders/tokens to revoke allowances for\n function revokeAdapterAllowances(RevocationPair[] calldata revocations)\n external;\n\n /// @dev Sets allowances to zero for the provided spender/token pairs\n /// Checks that the msg.sender CA matches the expected account, since\n /// provided revocations are specific to a particular CA\n /// @param revocations Pairs of spenders/tokens to revoke allowances for\n /// @param expectedCreditAccount Credit account that msg.sender is expected to have\n function revokeAdapterAllowances(\n RevocationPair[] calldata revocations,\n address expectedCreditAccount\n ) external;\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/core-v2/contracts/interfaces/IErrors.sol": {
"content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n/// @dev Common contract exceptions\n\n/// @dev Thrown on attempting to set an important address to zero address\nerror ZeroAddressException();\n\n/// @dev Thrown on attempting to call a non-implemented function\nerror NotImplementedException();\n\n/// @dev Thrown on attempting to set an EOA as an important contract in the system\nerror AddressIsNotContractException(address);\n\n/// @dev Thrown on attempting to use a non-ERC20 contract or an EOA as a token\nerror IncorrectTokenContractException();\n\n/// @dev Thrown on attempting to set a token price feed to an address that is not a\n/// correct price feed\nerror IncorrectPriceFeedException();\n\n/// @dev Thrown on attempting to call an access restricted function as a non-Configurator\nerror CallerNotConfiguratorException();\n\n/// @dev Thrown on attempting to pause a contract as a non-Pausable admin\nerror CallerNotPausableAdminException();\n\n/// @dev Thrown on attempting to pause a contract as a non-Unpausable admin\nerror CallerNotUnPausableAdminException();\n\nerror TokenIsNotAddedToCreditManagerException(address token);\n"
},
"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol": {
"content": "// SPDX-License-Identifier: 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/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"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 1000000
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}