More Info
Private Name Tags
ContractCreator
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Loading...
Loading
Contract Name:
CErc20Delegate
Compiler Version
v0.8.10+commit.fc410830
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "./CToken.sol"; /** * @title Compound's CErc20Delegate Contract * @notice CTokens which wrap an EIP-20 underlying and are delegated to * @author Compound */ contract CErc20Delegate is CErc20 { function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory functionSelectors) { uint8 fnsCount = 3; bytes4[] memory superFunctionSelectors = super._getExtensionFunctions(); functionSelectors = new bytes4[](superFunctionSelectors.length + fnsCount); for (uint256 i = 0; i < superFunctionSelectors.length; i++) { functionSelectors[i] = superFunctionSelectors[i]; } functionSelectors[--fnsCount + superFunctionSelectors.length] = this.contractType.selector; functionSelectors[--fnsCount + superFunctionSelectors.length] = this.delegateType.selector; functionSelectors[--fnsCount + superFunctionSelectors.length] = this._becomeImplementation.selector; require(fnsCount == 0, "use the correct array length"); } /** * @notice Called by the delegator on a delegate to initialize it for duty */ function _becomeImplementation(bytes memory) public virtual override { require(msg.sender == address(this) || hasAdminRights(), "!self || !admin"); } function delegateType() public pure virtual override returns (uint8) { return 1; } function contractType() external pure virtual override returns (string memory) { return "CErc20Delegate"; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializing the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overridden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: UNLICENSED // Copyright (C) 2024 Lavra Holdings Limited - All Rights Reserved pragma solidity ^0.8.0; interface IExpressRelay { // Check if the combination of protocol and permissionKey is allowed within this transaction. // This will return true if and only if it's being called while executing the auction winner(s) call. // @param protocolFeeReceiver The address of the protocol that is gating an action behind this permission // @param permissionId The id that represents the action being gated // @return permissioned True if the permission is allowed, false otherwise function isPermissioned( address protocolFeeReceiver, bytes calldata permissionId ) external view returns (bool permissioned); }
// SPDX-License-Identifier: UNLICENSED // Copyright (C) 2024 Lavra Holdings Limited - All Rights Reserved pragma solidity ^0.8.0; interface IExpressRelayFeeReceiver { // Receive the proceeds of an auction. // @param permissionKey The permission key where the auction was conducted on. function receiveAuctionProceedings( bytes calldata permissionKey ) external payable; }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { ICErc20 } from "./compound/CTokenInterfaces.sol"; import "./liquidators/IRedemptionStrategy.sol"; import "./liquidators/IFundsConversionStrategy.sol"; interface ILiquidator { /** * borrower The borrower's Ethereum address. * repayAmount The amount to repay to liquidate the unhealthy loan. * cErc20 The borrowed CErc20 contract to repay. * cTokenCollateral The cToken collateral contract to be liquidated. * minProfitAmount The minimum amount of profit required for execution (in terms of `exchangeProfitTo`). Reverts if this condition is not met. * redemptionStrategies The IRedemptionStrategy contracts to use, if any, to redeem "special" collateral tokens (before swapping the output for borrowed tokens to be repaid via Uniswap). * strategyData The data for the chosen IRedemptionStrategy contracts, if any. */ struct LiquidateToTokensWithFlashSwapVars { address borrower; uint256 repayAmount; ICErc20 cErc20; ICErc20 cTokenCollateral; address flashSwapContract; uint256 minProfitAmount; IRedemptionStrategy[] redemptionStrategies; bytes[] strategyData; IFundsConversionStrategy[] debtFundingStrategies; bytes[] debtFundingStrategiesData; } function redemptionStrategiesWhitelist(address strategy) external view returns (bool); function safeLiquidate( address borrower, uint256 repayAmount, ICErc20 cErc20, ICErc20 cTokenCollateral, uint256 minOutputAmount ) external returns (uint256); function safeLiquidateToTokensWithFlashLoan(LiquidateToTokensWithFlashSwapVars calldata vars) external returns (uint256); function _whitelistRedemptionStrategy(IRedemptionStrategy strategy, bool whitelisted) external; function _whitelistRedemptionStrategies(IRedemptionStrategy[] calldata strategies, bool[] calldata whitelisted) external; function setExpressRelay(address _expressRelay) external; function setPoolLens(address _poolLens) external; function setHealthFactorThreshold(uint256 _healthFactorThreshold) external; }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol"; import "openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol"; import "openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./liquidators/IRedemptionStrategy.sol"; import "./liquidators/IFundsConversionStrategy.sol"; import "./ILiquidator.sol"; import "./external/uniswap/IUniswapV3FlashCallback.sol"; import "./external/uniswap/IUniswapV3Pool.sol"; import { IUniswapV3Quoter } from "./external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol"; import { ICErc20 } from "./compound/CTokenInterfaces.sol"; import "./PoolLens.sol"; import "@pythnetwork/express-relay-sdk-solidity/IExpressRelay.sol"; import "@pythnetwork/express-relay-sdk-solidity/IExpressRelayFeeReceiver.sol"; /** * @title IonicUniV3Liquidator * @author Veliko Minkov <[email protected]> (https://github.com/vminkov) * @notice IonicUniV3Liquidator liquidates unhealthy borrowers with flashloan support. */ contract IonicUniV3Liquidator is OwnableUpgradeable, ILiquidator, IUniswapV3FlashCallback, IExpressRelayFeeReceiver { using AddressUpgradeable for address payable; using SafeERC20Upgradeable for IERC20Upgradeable; event VaultReceivedETH(address sender, uint256 amount, bytes permissionKey); /** * @dev Cached liquidator profit exchange source. * ERC20 token address or the zero address for NATIVE. * For use in `safeLiquidateToTokensWithFlashLoan` after it is set by `postFlashLoanTokens`. */ address private _liquidatorProfitExchangeSource; /** * @dev Cached flash swap amount. * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`. */ uint256 private _flashSwapAmount; /** * @dev Cached flash swap token. * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`. */ address private _flashSwapToken; address public W_NATIVE_ADDRESS; mapping(address => bool) public redemptionStrategiesWhitelist; IUniswapV3Quoter public quoter; /** * @dev Addres of Pyth Express Relay for preventing value leakage in liquidations. */ IExpressRelay public expressRelay; /** * @dev Pool Lens. */ PoolLens public lens; /** * @dev Health Factor below which PER permissioning is bypassed. */ uint256 public healthFactorThreshold; modifier onlyPERPermissioned(address borrower, ICErc20 cToken) { uint256 currentHealthFactor = lens.getHealthFactor(borrower, cToken.comptroller()); if (currentHealthFactor > healthFactorThreshold) { require(expressRelay.isPermissioned(address(this), abi.encode(borrower)), "invalid liquidation"); } _; } function initialize(address _wtoken, address _quoter) external initializer { __Ownable_init(); W_NATIVE_ADDRESS = _wtoken; quoter = IUniswapV3Quoter(_quoter); } /** * @notice Safely liquidate an unhealthy loan (using capital from the sender), confirming that at least `minOutputAmount` in collateral is seized (or outputted by exchange if applicable). * @param borrower The borrower's Ethereum address. * @param repayAmount The amount to repay to liquidate the unhealthy loan. * @param cErc20 The borrowed cErc20 to repay. * @param cTokenCollateral The cToken collateral to be liquidated. * @param minOutputAmount The minimum amount of collateral to seize (or the minimum exchange output if applicable) required for execution. Reverts if this condition is not met. */ function safeLiquidate( address borrower, uint256 repayAmount, ICErc20 cErc20, ICErc20 cTokenCollateral, uint256 minOutputAmount ) external onlyPERPermissioned(borrower, cTokenCollateral) returns (uint256) { // Transfer tokens in, approve to cErc20, and liquidate borrow require(repayAmount > 0, "Repay amount (transaction value) must be greater than 0."); IERC20Upgradeable underlying = IERC20Upgradeable(cErc20.underlying()); underlying.safeTransferFrom(msg.sender, address(this), repayAmount); underlying.approve(address(cErc20), repayAmount); require(cErc20.liquidateBorrow(borrower, repayAmount, address(cTokenCollateral)) == 0, "Liquidation failed."); // Redeem seized cTokens for underlying asset uint256 seizedCTokenAmount = cTokenCollateral.balanceOf(address(this)); require(seizedCTokenAmount > 0, "No cTokens seized."); uint256 redeemResult = cTokenCollateral.redeem(seizedCTokenAmount); require(redeemResult == 0, "Error calling redeeming seized cToken: error code not equal to 0"); return transferSeizedFunds(address(cTokenCollateral.underlying()), minOutputAmount); } /** * @dev Transfers seized funds to the sender. * @param erc20Contract The address of the token to transfer. * @param minOutputAmount The minimum amount to transfer. */ function transferSeizedFunds(address erc20Contract, uint256 minOutputAmount) internal returns (uint256) { IERC20Upgradeable token = IERC20Upgradeable(erc20Contract); uint256 seizedOutputAmount = token.balanceOf(address(this)); require(seizedOutputAmount >= minOutputAmount, "Minimum token output amount not satified."); if (seizedOutputAmount > 0) token.safeTransfer(msg.sender, seizedOutputAmount); return seizedOutputAmount; } function safeLiquidateToTokensWithFlashLoan(LiquidateToTokensWithFlashSwapVars calldata vars) external onlyPERPermissioned(vars.borrower, vars.cTokenCollateral) returns (uint256) { // Input validation require(vars.repayAmount > 0, "Repay amount must be greater than 0."); // we want to calculate the needed flashSwapAmount on-chain to // avoid errors due to changing market conditions // between the time of calculating and including the tx in a block uint256 fundingAmount = vars.repayAmount; IERC20Upgradeable fundingToken; if (vars.debtFundingStrategies.length > 0) { require( vars.debtFundingStrategies.length == vars.debtFundingStrategiesData.length, "Funding IFundsConversionStrategy contract array and strategy data bytes array must be the same length." ); // estimate the initial (flash-swapped token) input from the expected output (debt token) for (uint256 i = 0; i < vars.debtFundingStrategies.length; i++) { bytes memory strategyData = vars.debtFundingStrategiesData[i]; IFundsConversionStrategy fcs = vars.debtFundingStrategies[i]; (fundingToken, fundingAmount) = fcs.estimateInputAmount(fundingAmount, strategyData); } } else { fundingToken = IERC20Upgradeable(ICErc20(address(vars.cErc20)).underlying()); } // the last outputs from estimateInputAmount are the ones to be flash-swapped _flashSwapAmount = fundingAmount; _flashSwapToken = address(fundingToken); IUniswapV3Pool flashSwapPool = IUniswapV3Pool(vars.flashSwapContract); bool token0IsFlashSwapFundingToken = flashSwapPool.token0() == address(fundingToken); flashSwapPool.flash( address(this), token0IsFlashSwapFundingToken ? fundingAmount : 0, !token0IsFlashSwapFundingToken ? fundingAmount : 0, msg.data ); return transferSeizedFunds(_liquidatorProfitExchangeSource, vars.minProfitAmount); } /** * @dev Receives NATIVE from liquidations and flashloans. * Requires that `msg.sender` is W_NATIVE, a CToken, or a Uniswap V2 Router, or another contract. */ receive() external payable { require(payable(msg.sender).isContract(), "Sender is not a contract."); } /** * @notice receiveAuctionProceedings function - receives native token from the express relay * You can use permission key to distribute the received funds to users who got liquidated, LPs, etc... */ function receiveAuctionProceedings(bytes calldata permissionKey) external payable { emit VaultReceivedETH(msg.sender, msg.value, permissionKey); } function withdrawAll() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No Ether left to withdraw"); // Transfer all Ether to the owner (bool sent, ) = msg.sender.call{ value: balance }(""); require(sent, "Failed to send Ether"); } /** * @dev Callback function for Uniswap flashloans. */ function supV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external { uniswapV3FlashCallback(fee0, fee1, data); } function algebraFlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external { uniswapV3FlashCallback(fee0, fee1, data); } function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) public { // Liquidate unhealthy borrow, exchange seized collateral, return flashloaned funds, and exchange profit // Decode params LiquidateToTokensWithFlashSwapVars memory vars = abi.decode(data[4:], (LiquidateToTokensWithFlashSwapVars)); // Post token flashloan // Cache liquidation profit token (or the zero address for NATIVE) for use as source for exchange later _liquidatorProfitExchangeSource = postFlashLoanTokens(vars, fee0, fee1); } /** * @dev Liquidate unhealthy token borrow, exchange seized collateral, return flashloaned funds, and exchange profit. */ function postFlashLoanTokens( LiquidateToTokensWithFlashSwapVars memory vars, uint256 fee0, uint256 fee1 ) private returns (address) { IERC20Upgradeable debtRepaymentToken = IERC20Upgradeable(_flashSwapToken); uint256 debtRepaymentAmount = _flashSwapAmount; if (vars.debtFundingStrategies.length > 0) { // loop backwards to convert the initial (flash-swapped token) input to the final expected output (debt token) for (uint256 i = vars.debtFundingStrategies.length; i > 0; i--) { (debtRepaymentToken, debtRepaymentAmount) = convertCustomFunds( debtRepaymentToken, debtRepaymentAmount, vars.debtFundingStrategies[i - 1], vars.debtFundingStrategiesData[i - 1] ); } } // Approve the debt repayment transfer, liquidate and redeem the seized collateral { address underlyingBorrow = vars.cErc20.underlying(); require( address(debtRepaymentToken) == underlyingBorrow, "the debt repayment funds should be converted to the underlying debt token" ); require(debtRepaymentAmount >= vars.repayAmount, "debt repayment amount not enough"); // Approve repayAmount to cErc20 IERC20Upgradeable(underlyingBorrow).approve(address(vars.cErc20), vars.repayAmount); // Liquidate borrow require( vars.cErc20.liquidateBorrow(vars.borrower, vars.repayAmount, address(vars.cTokenCollateral)) == 0, "Liquidation failed." ); // Redeem seized cTokens for underlying asset uint256 seizedCTokenAmount = vars.cTokenCollateral.balanceOf(address(this)); require(seizedCTokenAmount > 0, "No cTokens seized."); uint256 redeemResult = vars.cTokenCollateral.redeem(seizedCTokenAmount); require(redeemResult == 0, "Error calling redeeming seized cToken: error code not equal to 0"); } // Repay flashloan return repayTokenFlashLoan(vars.cTokenCollateral, vars.redemptionStrategies, vars.strategyData, fee0, fee1); } /** * @dev Repays token flashloans. */ function repayTokenFlashLoan( ICErc20 cTokenCollateral, IRedemptionStrategy[] memory redemptionStrategies, bytes[] memory strategyData, uint256 fee0, uint256 fee1 ) private returns (address) { IUniswapV3Pool pool = IUniswapV3Pool(msg.sender); uint256 flashSwapReturnAmount = _flashSwapAmount; if (IUniswapV3Pool(msg.sender).token0() == _flashSwapToken) { flashSwapReturnAmount += fee0; } else if (IUniswapV3Pool(msg.sender).token1() == _flashSwapToken) { flashSwapReturnAmount += fee1; } else { revert("wrong pool or _flashSwapToken"); } // Swap cTokenCollateral for cErc20 via Uniswap // Check underlying collateral seized IERC20Upgradeable underlyingCollateral = IERC20Upgradeable(ICErc20(address(cTokenCollateral)).underlying()); uint256 underlyingCollateralSeized = underlyingCollateral.balanceOf(address(this)); // Redeem custom collateral if liquidation strategy is set if (redemptionStrategies.length > 0) { require( redemptionStrategies.length == strategyData.length, "IRedemptionStrategy contract array and strategy data bytes array mnust the the same length." ); for (uint256 i = 0; i < redemptionStrategies.length; i++) (underlyingCollateral, underlyingCollateralSeized) = redeemCustomCollateral( underlyingCollateral, underlyingCollateralSeized, redemptionStrategies[i], strategyData[i] ); } // Check if we can repay directly one of the sides with collateral if (address(underlyingCollateral) == pool.token0() || address(underlyingCollateral) == pool.token1()) { // Repay flashloan directly with collateral uint256 collateralRequired; if (address(underlyingCollateral) == _flashSwapToken) { // repay the borrowed asset directly collateralRequired = flashSwapReturnAmount; // Repay flashloan IERC20Upgradeable(_flashSwapToken).transfer(address(pool), flashSwapReturnAmount); } else { // TODO swap within the same pool and then repay the FL to the pool bool zeroForOne = address(underlyingCollateral) == pool.token0(); { collateralRequired = quoter.quoteExactOutputSingle( zeroForOne ? pool.token0() : pool.token1(), zeroForOne ? pool.token1() : pool.token0(), pool.fee(), _flashSwapAmount, 0 // sqrtPriceLimitX96 ); } require( collateralRequired <= underlyingCollateralSeized, "Token flashloan return amount greater than seized collateral." ); // Repay flashloan pool.swap( address(pool), zeroForOne, int256(collateralRequired), 0, // sqrtPriceLimitX96 "" ); } return address(underlyingCollateral); } else { revert("the redemptions strategy did not swap to the flash swapped pool assets"); } } /** * @dev for security reasons only whitelisted redemption strategies may be used. * Each whitelisted redemption strategy has to be checked to not be able to * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral` */ function _whitelistRedemptionStrategy(IRedemptionStrategy strategy, bool whitelisted) external onlyOwner { redemptionStrategiesWhitelist[address(strategy)] = whitelisted; } /** * @dev for security reasons only whitelisted redemption strategies may be used. * Each whitelisted redemption strategy has to be checked to not be able to * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral` */ function _whitelistRedemptionStrategies(IRedemptionStrategy[] calldata strategies, bool[] calldata whitelisted) external onlyOwner { require( strategies.length > 0 && strategies.length == whitelisted.length, "list of strategies empty or whitelist does not match its length" ); for (uint256 i = 0; i < strategies.length; i++) { redemptionStrategiesWhitelist[address(strategies[i])] = whitelisted[i]; } } function setExpressRelay(address _expressRelay) external onlyOwner { expressRelay = IExpressRelay(_expressRelay); } function setPoolLens(address _poolLens) external onlyOwner { lens = PoolLens(_poolLens); } function setHealthFactorThreshold(uint256 _healthFactorThreshold) external onlyOwner { require(_healthFactorThreshold <= 1e18, "Invalid Health Factor Threshold"); healthFactorThreshold = _healthFactorThreshold; } /** * @dev Redeem "special" collateral tokens (before swapping the output for borrowed tokens to be repaid via Uniswap). * Public visibility because we have to call this function externally if called from a payable IonicLiquidator function (for some reason delegatecall fails when called with msg.value > 0). */ function redeemCustomCollateral( IERC20Upgradeable underlyingCollateral, uint256 underlyingCollateralSeized, IRedemptionStrategy strategy, bytes memory strategyData ) private returns (IERC20Upgradeable, uint256) { require(redemptionStrategiesWhitelist[address(strategy)], "only whitelisted redemption strategies can be used"); bytes memory returndata = _functionDelegateCall( address(strategy), abi.encodeWithSelector(strategy.redeem.selector, underlyingCollateral, underlyingCollateralSeized, strategyData) ); return abi.decode(returndata, (IERC20Upgradeable, uint256)); } function convertCustomFunds( IERC20Upgradeable inputToken, uint256 inputAmount, IFundsConversionStrategy strategy, bytes memory strategyData ) private returns (IERC20Upgradeable, uint256) { require(redemptionStrategiesWhitelist[address(strategy)], "only whitelisted redemption strategies can be used"); bytes memory returndata = _functionDelegateCall( address(strategy), abi.encodeWithSelector(strategy.convert.selector, inputToken, inputAmount, strategyData) ); return abi.decode(returndata, (IERC20Upgradeable, uint256)); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call. * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L37 */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } /** * @dev Used by `_functionDelegateCall` to verify the result of a delegate call. * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L45 */ function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/utils/Create2Upgradeable.sol"; import { IonicComptroller } from "./compound/ComptrollerInterface.sol"; import { BasePriceOracle } from "./oracles/BasePriceOracle.sol"; import { Unitroller } from "./compound/Unitroller.sol"; import "./ionic/SafeOwnableUpgradeable.sol"; import "./ionic/DiamondExtension.sol"; /** * @title PoolDirectory * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice PoolDirectory is a directory for Ionic interest rate pools. */ contract PoolDirectory is SafeOwnableUpgradeable { /** * @dev Initializes a deployer whitelist if desired. * @param _enforceDeployerWhitelist Boolean indicating if the deployer whitelist is to be enforced. * @param _deployerWhitelist Array of Ethereum accounts to be whitelisted. */ function initialize(bool _enforceDeployerWhitelist, address[] memory _deployerWhitelist) public initializer { __SafeOwnable_init(msg.sender); enforceDeployerWhitelist = _enforceDeployerWhitelist; for (uint256 i = 0; i < _deployerWhitelist.length; i++) deployerWhitelist[_deployerWhitelist[i]] = true; } /** * @dev Struct for a Ionic interest rate pool. */ struct Pool { string name; address creator; address comptroller; uint256 blockPosted; uint256 timestampPosted; } /** * @dev Array of Ionic interest rate pools. */ Pool[] public pools; /** * @dev Maps Ethereum accounts to arrays of Ionic pool indexes. */ mapping(address => uint256[]) private _poolsByAccount; /** * @dev Maps Ionic pool Comptroller addresses to bools indicating if they have been registered via the directory. */ mapping(address => bool) public poolExists; /** * @dev Emitted when a new Ionic pool is added to the directory. */ event PoolRegistered(uint256 index, Pool pool); /** * @dev Booleans indicating if the deployer whitelist is enforced. */ bool public enforceDeployerWhitelist; /** * @dev Maps Ethereum accounts to booleans indicating if they are allowed to deploy pools. */ mapping(address => bool) public deployerWhitelist; /** * @dev Controls if the deployer whitelist is to be enforced. * @param enforce Boolean indicating if the deployer whitelist is to be enforced. */ function _setDeployerWhitelistEnforcement(bool enforce) external onlyOwner { enforceDeployerWhitelist = enforce; } /** * @dev Adds/removes Ethereum accounts to the deployer whitelist. * @param deployers Array of Ethereum accounts to be whitelisted. * @param status Whether to add or remove the accounts. */ function _editDeployerWhitelist(address[] calldata deployers, bool status) external onlyOwner { require(deployers.length > 0, "No deployers supplied."); for (uint256 i = 0; i < deployers.length; i++) deployerWhitelist[deployers[i]] = status; } /** * @dev Adds a new Ionic pool to the directory (without checking msg.sender). * @param name The name of the pool. * @param comptroller The pool's Comptroller proxy contract address. * @return The index of the registered Ionic pool. */ function _registerPool(string memory name, address comptroller) internal returns (uint256) { require(!poolExists[comptroller], "Pool already exists in the directory."); require(!enforceDeployerWhitelist || deployerWhitelist[msg.sender], "Sender is not on deployer whitelist."); require(bytes(name).length <= 100, "No pool name supplied."); Pool memory pool = Pool(name, msg.sender, comptroller, block.number, block.timestamp); pools.push(pool); _poolsByAccount[msg.sender].push(pools.length - 1); poolExists[comptroller] = true; emit PoolRegistered(pools.length - 1, pool); return pools.length - 1; } function _deprecatePool(address comptroller) external onlyOwner { for (uint256 i = 0; i < pools.length; i++) { if (pools[i].comptroller == comptroller) { _deprecatePool(i); break; } } } function _deprecatePool(uint256 index) public onlyOwner { Pool storage ionicPool = pools[index]; require(ionicPool.comptroller != address(0), "pool already deprecated"); // swap with the last pool of the creator and delete uint256[] storage creatorPools = _poolsByAccount[ionicPool.creator]; for (uint256 i = 0; i < creatorPools.length; i++) { if (creatorPools[i] == index) { creatorPools[i] = creatorPools[creatorPools.length - 1]; creatorPools.pop(); break; } } // leave it to true to deny the re-registering of the same pool poolExists[ionicPool.comptroller] = true; // nullify the storage ionicPool.comptroller = address(0); ionicPool.creator = address(0); ionicPool.name = ""; ionicPool.blockPosted = 0; ionicPool.timestampPosted = 0; } /** * @dev Deploys a new Ionic pool and adds to the directory. * @param name The name of the pool. * @param implementation The Comptroller implementation contract address. * @param constructorData Encoded construction data for `Unitroller constructor()` * @param enforceWhitelist Boolean indicating if the pool's supplier/borrower whitelist is to be enforced. * @param closeFactor The pool's close factor (scaled by 1e18). * @param liquidationIncentive The pool's liquidation incentive (scaled by 1e18). * @param priceOracle The pool's PriceOracle contract address. * @return Index of the registered Ionic pool and the Unitroller proxy address. */ function deployPool( string memory name, address implementation, bytes calldata constructorData, bool enforceWhitelist, uint256 closeFactor, uint256 liquidationIncentive, address priceOracle ) external returns (uint256, address) { // Input validation require(implementation != address(0), "No Comptroller implementation contract address specified."); require(priceOracle != address(0), "No PriceOracle contract address specified."); // Deploy Unitroller using msg.sender, name, and block.number as a salt bytes memory unitrollerCreationCode = abi.encodePacked(type(Unitroller).creationCode, constructorData); address proxy = Create2Upgradeable.deploy( 0, keccak256(abi.encodePacked(msg.sender, name, ++poolsCounter)), unitrollerCreationCode ); // Setup the pool IonicComptroller comptrollerProxy = IonicComptroller(proxy); // Set up the extensions comptrollerProxy._upgrade(); // Set pool parameters require(comptrollerProxy._setCloseFactor(closeFactor) == 0, "Failed to set pool close factor."); require( comptrollerProxy._setLiquidationIncentive(liquidationIncentive) == 0, "Failed to set pool liquidation incentive." ); require(comptrollerProxy._setPriceOracle(BasePriceOracle(priceOracle)) == 0, "Failed to set pool price oracle."); // Whitelist if (enforceWhitelist) require(comptrollerProxy._setWhitelistEnforcement(true) == 0, "Failed to enforce supplier/borrower whitelist."); // Make msg.sender the admin require(comptrollerProxy._setPendingAdmin(msg.sender) == 0, "Failed to set pending admin on Unitroller."); // Register the pool with this PoolDirectory return (_registerPool(name, proxy), proxy); } /** * @notice Returns `ids` and directory information of all non-deprecated Ionic pools. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getActivePools() public view returns (uint256[] memory, Pool[] memory) { uint256 count = 0; for (uint256 i = 0; i < pools.length; i++) { if (pools[i].comptroller != address(0)) count++; } Pool[] memory activePools = new Pool[](count); uint256[] memory poolIds = new uint256[](count); uint256 index = 0; for (uint256 i = 0; i < pools.length; i++) { if (pools[i].comptroller != address(0)) { poolIds[index] = i; activePools[index] = pools[i]; index++; } } return (poolIds, activePools); } /** * @notice Returns arrays of all Ionic pools' data. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getAllPools() public view returns (Pool[] memory) { uint256 count = 0; for (uint256 i = 0; i < pools.length; i++) { if (pools[i].comptroller != address(0)) count++; } Pool[] memory result = new Pool[](count); uint256 index = 0; for (uint256 i = 0; i < pools.length; i++) { if (pools[i].comptroller != address(0)) { result[index++] = pools[i]; } } return result; } /** * @notice Returns arrays of all public Ionic pool indexes and data. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getPublicPools() external view returns (uint256[] memory, Pool[] memory) { uint256 arrayLength = 0; (, Pool[] memory activePools) = getActivePools(); for (uint256 i = 0; i < activePools.length; i++) { try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) { if (enforceWhitelist) continue; } catch {} arrayLength++; } uint256[] memory indexes = new uint256[](arrayLength); Pool[] memory publicPools = new Pool[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < activePools.length; i++) { try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) { if (enforceWhitelist) continue; } catch {} indexes[index] = i; publicPools[index] = activePools[i]; index++; } return (indexes, publicPools); } /** * @notice Returns arrays of all public Ionic pool indexes and data. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getPoolsOfUser(address user) external view returns (uint256[] memory, Pool[] memory) { uint256 arrayLength = 0; (, Pool[] memory activePools) = getActivePools(); for (uint256 i = 0; i < activePools.length; i++) { try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) { if (!isUsing) continue; } catch {} arrayLength++; } uint256[] memory indexes = new uint256[](arrayLength); Pool[] memory poolsOfUser = new Pool[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < activePools.length; i++) { try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) { if (!isUsing) continue; } catch {} indexes[index] = i; poolsOfUser[index] = activePools[i]; index++; } return (indexes, poolsOfUser); } /** * @notice Returns arrays of Ionic pool indexes and data created by `account`. */ function getPoolsByAccount(address account) external view returns (uint256[] memory, Pool[] memory) { uint256[] memory indexes = new uint256[](_poolsByAccount[account].length); Pool[] memory accountPools = new Pool[](_poolsByAccount[account].length); (, Pool[] memory activePools) = getActivePools(); for (uint256 i = 0; i < _poolsByAccount[account].length; i++) { indexes[i] = _poolsByAccount[account][i]; accountPools[i] = activePools[_poolsByAccount[account][i]]; } return (indexes, accountPools); } /** * @notice Modify existing Ionic pool name. */ function setPoolName(uint256 index, string calldata name) external { IonicComptroller _comptroller = IonicComptroller(pools[index].comptroller); require( (msg.sender == _comptroller.admin() && _comptroller.adminHasRights()) || msg.sender == owner(), "!permission" ); pools[index].name = name; } /** * @dev Maps Ethereum accounts to booleans indicating if they are a whitelisted admin. */ mapping(address => bool) public adminWhitelist; /** * @dev used as salt for the creation of new pools */ uint256 public poolsCounter; /** * @dev Event emitted when the admin whitelist is updated. */ event AdminWhitelistUpdated(address[] admins, bool status); /** * @dev Adds/removes Ethereum accounts to the admin whitelist. * @param admins Array of Ethereum accounts to be whitelisted. * @param status Whether to add or remove the accounts. */ function _editAdminWhitelist(address[] calldata admins, bool status) external onlyOwner { require(admins.length > 0, "No admins supplied."); for (uint256 i = 0; i < admins.length; i++) adminWhitelist[admins[i]] = status; emit AdminWhitelistUpdated(admins, status); } /** * @notice Returns arrays of all Ionic pool indexes and data with whitelisted admins. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getPublicPoolsByVerification(bool whitelistedAdmin) external view returns (uint256[] memory, Pool[] memory) { uint256 arrayLength = 0; (, Pool[] memory activePools) = getActivePools(); for (uint256 i = 0; i < activePools.length; i++) { IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller); try comptroller.admin() returns (address admin) { if (whitelistedAdmin != adminWhitelist[admin]) continue; } catch {} arrayLength++; } uint256[] memory indexes = new uint256[](arrayLength); Pool[] memory publicPools = new Pool[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < activePools.length; i++) { IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller); try comptroller.admin() returns (address admin) { if (whitelistedAdmin != adminWhitelist[admin]) continue; } catch {} indexes[index] = i; publicPools[index] = activePools[i]; index++; } return (indexes, publicPools); } /** * @notice Returns arrays of all verified Ionic pool indexes and data for which the account is whitelisted * @param account who is whitelisted in the returned verified whitelist-enabled pools. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getVerifiedPoolsOfWhitelistedAccount(address account) external view returns (uint256[] memory, Pool[] memory) { uint256 arrayLength = 0; (, Pool[] memory activePools) = getActivePools(); for (uint256 i = 0; i < activePools.length; i++) { IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller); try comptroller.enforceWhitelist() returns (bool enforceWhitelist) { if (!enforceWhitelist || !comptroller.whitelist(account)) continue; } catch {} arrayLength++; } uint256[] memory indexes = new uint256[](arrayLength); Pool[] memory accountWhitelistedPools = new Pool[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < activePools.length; i++) { IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller); try comptroller.enforceWhitelist() returns (bool enforceWhitelist) { if (!enforceWhitelist || !comptroller.whitelist(account)) continue; } catch {} indexes[index] = i; accountWhitelistedPools[index] = activePools[i]; index++; } return (indexes, accountWhitelistedPools); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; import "openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol"; import { IonicComptroller } from "./compound/ComptrollerInterface.sol"; import { BasePriceOracle } from "./oracles/BasePriceOracle.sol"; import { ICErc20 } from "./compound/CTokenInterfaces.sol"; import { PoolDirectory } from "./PoolDirectory.sol"; import { MasterPriceOracle } from "./oracles/MasterPriceOracle.sol"; /** * @title PoolLens * @author David Lucid <[email protected]> (https://github.com/davidlucid) * @notice PoolLens returns data on Ionic interest rate pools in mass for viewing by dApps, bots, etc. */ contract PoolLens is Initializable { error ComptrollerError(uint256 errCode); /** * @notice Initialize the `PoolDirectory` contract object. * @param _directory The PoolDirectory * @param _name Name for the nativeToken * @param _symbol Symbol for the nativeToken * @param _hardcodedAddresses Underlying token addresses for a token like maker which are DSToken and/or use bytes32 for `symbol` * @param _hardcodedNames Harcoded name for these tokens * @param _hardcodedSymbols Harcoded symbol for these tokens * @param _uniswapLPTokenNames Harcoded names for underlying uniswap LpToken * @param _uniswapLPTokenSymbols Harcoded symbols for underlying uniswap LpToken * @param _uniswapLPTokenDisplayNames Harcoded display names for underlying uniswap LpToken */ function initialize( PoolDirectory _directory, string memory _name, string memory _symbol, address[] memory _hardcodedAddresses, string[] memory _hardcodedNames, string[] memory _hardcodedSymbols, string[] memory _uniswapLPTokenNames, string[] memory _uniswapLPTokenSymbols, string[] memory _uniswapLPTokenDisplayNames ) public initializer { require(address(_directory) != address(0), "PoolDirectory instance cannot be the zero address."); require( _hardcodedAddresses.length == _hardcodedNames.length && _hardcodedAddresses.length == _hardcodedSymbols.length, "Hardcoded addresses lengths not equal." ); require( _uniswapLPTokenNames.length == _uniswapLPTokenSymbols.length && _uniswapLPTokenNames.length == _uniswapLPTokenDisplayNames.length, "Uniswap LP token names lengths not equal." ); directory = _directory; name = _name; symbol = _symbol; for (uint256 i = 0; i < _hardcodedAddresses.length; i++) { hardcoded[_hardcodedAddresses[i]] = TokenData({ name: _hardcodedNames[i], symbol: _hardcodedSymbols[i] }); } for (uint256 i = 0; i < _uniswapLPTokenNames.length; i++) { uniswapData.push( UniswapData({ name: _uniswapLPTokenNames[i], symbol: _uniswapLPTokenSymbols[i], displayName: _uniswapLPTokenDisplayNames[i] }) ); } } string public name; string public symbol; struct TokenData { string name; string symbol; } mapping(address => TokenData) hardcoded; struct UniswapData { string name; // ie "Uniswap V2" or "SushiSwap LP Token" string symbol; // ie "UNI-V2" or "SLP" string displayName; // ie "SushiSwap" or "Uniswap" } UniswapData[] uniswapData; /** * @notice `PoolDirectory` contract object. */ PoolDirectory public directory; /** * @dev Struct for Ionic pool summary data. */ struct IonicPoolData { uint256 totalSupply; uint256 totalBorrow; address[] underlyingTokens; string[] underlyingSymbols; bool whitelistedAdmin; } /** * @notice Returns arrays of all public Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getPublicPoolsWithData() external returns ( uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory ) { (uint256[] memory indexes, PoolDirectory.Pool[] memory publicPools) = directory.getPublicPools(); (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(publicPools); return (indexes, publicPools, data, errored); } /** * @notice Returns arrays of all whitelisted public Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getPublicPoolsByVerificationWithData(bool whitelistedAdmin) external returns ( uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory ) { (uint256[] memory indexes, PoolDirectory.Pool[] memory publicPools) = directory.getPublicPoolsByVerification( whitelistedAdmin ); (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(publicPools); return (indexes, publicPools, data, errored); } /** * @notice Returns arrays of the indexes of Ionic pools created by `account`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getPoolsByAccountWithData(address account) external returns ( uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory ) { (uint256[] memory indexes, PoolDirectory.Pool[] memory accountPools) = directory.getPoolsByAccount(account); (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(accountPools); return (indexes, accountPools, data, errored); } /** * @notice Returns arrays of the indexes of Ionic pools used by `user`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getPoolsOIonicrWithData(address user) external returns ( uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory ) { (uint256[] memory indexes, PoolDirectory.Pool[] memory userPools) = directory.getPoolsOfUser(user); (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(userPools); return (indexes, userPools, data, errored); } /** * @notice Internal function returning arrays of requested Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getPoolsData(PoolDirectory.Pool[] memory pools) internal returns (IonicPoolData[] memory, bool[] memory) { IonicPoolData[] memory data = new IonicPoolData[](pools.length); bool[] memory errored = new bool[](pools.length); for (uint256 i = 0; i < pools.length; i++) { try this.getPoolSummary(IonicComptroller(pools[i].comptroller)) returns ( uint256 _totalSupply, uint256 _totalBorrow, address[] memory _underlyingTokens, string[] memory _underlyingSymbols, bool _whitelistedAdmin ) { data[i] = IonicPoolData(_totalSupply, _totalBorrow, _underlyingTokens, _underlyingSymbols, _whitelistedAdmin); } catch { errored[i] = true; } } return (data, errored); } /** * @notice Returns total supply balance (in ETH), total borrow balance (in ETH), underlying token addresses, and underlying token symbols of a Ionic pool. */ function getPoolSummary(IonicComptroller comptroller) external returns ( uint256, uint256, address[] memory, string[] memory, bool ) { uint256 totalBorrow = 0; uint256 totalSupply = 0; ICErc20[] memory cTokens = comptroller.getAllMarkets(); address[] memory underlyingTokens = new address[](cTokens.length); string[] memory underlyingSymbols = new string[](cTokens.length); BasePriceOracle oracle = comptroller.oracle(); for (uint256 i = 0; i < cTokens.length; i++) { ICErc20 cToken = cTokens[i]; (bool isListed, ) = comptroller.markets(address(cToken)); if (!isListed) continue; cToken.accrueInterest(); uint256 assetTotalBorrow = cToken.totalBorrowsCurrent(); uint256 assetTotalSupply = cToken.getCash() + assetTotalBorrow - (cToken.totalReserves() + cToken.totalAdminFees() + cToken.totalIonicFees()); uint256 underlyingPrice = oracle.getUnderlyingPrice(cToken); totalBorrow = totalBorrow + (assetTotalBorrow * underlyingPrice) / 1e18; totalSupply = totalSupply + (assetTotalSupply * underlyingPrice) / 1e18; underlyingTokens[i] = ICErc20(address(cToken)).underlying(); (, underlyingSymbols[i]) = getTokenNameAndSymbol(underlyingTokens[i]); } bool whitelistedAdmin = directory.adminWhitelist(comptroller.admin()); return (totalSupply, totalBorrow, underlyingTokens, underlyingSymbols, whitelistedAdmin); } /** * @dev Struct for a Ionic pool asset. */ struct PoolAsset { address cToken; address underlyingToken; string underlyingName; string underlyingSymbol; uint256 underlyingDecimals; uint256 underlyingBalance; uint256 supplyRatePerBlock; uint256 borrowRatePerBlock; uint256 totalSupply; uint256 totalBorrow; uint256 supplyBalance; uint256 borrowBalance; uint256 liquidity; bool membership; uint256 exchangeRate; // Price of cTokens in terms of underlying tokens uint256 underlyingPrice; // Price of underlying tokens in ETH (scaled by 1e18) address oracle; uint256 collateralFactor; uint256 reserveFactor; uint256 adminFee; uint256 ionicFee; bool borrowGuardianPaused; bool mintGuardianPaused; } /** * @notice Returns data on the specified assets of the specified Ionic pool. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. * @param comptroller The Comptroller proxy contract address of the Ionic pool. * @param cTokens The cToken contract addresses of the assets to query. * @param user The user for which to get account data. * @return An array of Ionic pool assets. */ function getPoolAssetsWithData( IonicComptroller comptroller, ICErc20[] memory cTokens, address user ) internal returns (PoolAsset[] memory) { uint256 arrayLength = 0; for (uint256 i = 0; i < cTokens.length; i++) { (bool isListed, ) = comptroller.markets(address(cTokens[i])); if (isListed) arrayLength++; } PoolAsset[] memory detailedAssets = new PoolAsset[](arrayLength); uint256 index = 0; BasePriceOracle oracle = BasePriceOracle(address(comptroller.oracle())); for (uint256 i = 0; i < cTokens.length; i++) { // Check if market is listed and get collateral factor (bool isListed, uint256 collateralFactorMantissa) = comptroller.markets(address(cTokens[i])); if (!isListed) continue; // Start adding data to PoolAsset PoolAsset memory asset; ICErc20 cToken = cTokens[i]; asset.cToken = address(cToken); cToken.accrueInterest(); // Get underlying asset data asset.underlyingToken = ICErc20(address(cToken)).underlying(); ERC20Upgradeable underlying = ERC20Upgradeable(asset.underlyingToken); (asset.underlyingName, asset.underlyingSymbol) = getTokenNameAndSymbol(asset.underlyingToken); asset.underlyingDecimals = underlying.decimals(); asset.underlyingBalance = underlying.balanceOf(user); // Get cToken data asset.supplyRatePerBlock = cToken.supplyRatePerBlock(); asset.borrowRatePerBlock = cToken.borrowRatePerBlock(); asset.liquidity = cToken.getCash(); asset.totalBorrow = cToken.totalBorrowsCurrent(); asset.totalSupply = asset.liquidity + asset.totalBorrow - (cToken.totalReserves() + cToken.totalAdminFees() + cToken.totalIonicFees()); asset.supplyBalance = cToken.balanceOfUnderlying(user); asset.borrowBalance = cToken.borrowBalanceCurrent(user); asset.membership = comptroller.checkMembership(user, cToken); asset.exchangeRate = cToken.exchangeRateCurrent(); // We would use exchangeRateCurrent but we already accrue interest above asset.underlyingPrice = oracle.price(asset.underlyingToken); // Get oracle for this cToken asset.oracle = address(oracle); try MasterPriceOracle(asset.oracle).oracles(asset.underlyingToken) returns (BasePriceOracle _oracle) { asset.oracle = address(_oracle); } catch {} // More cToken data asset.collateralFactor = collateralFactorMantissa; asset.reserveFactor = cToken.reserveFactorMantissa(); asset.adminFee = cToken.adminFeeMantissa(); asset.ionicFee = cToken.ionicFeeMantissa(); asset.borrowGuardianPaused = comptroller.borrowGuardianPaused(address(cToken)); asset.mintGuardianPaused = comptroller.mintGuardianPaused(address(cToken)); // Add to assets array and increment index detailedAssets[index] = asset; index++; } return (detailedAssets); } function getBorrowCapsPerCollateral(ICErc20 borrowedAsset, IonicComptroller comptroller) internal view returns ( address[] memory collateral, uint256[] memory borrowCapsAgainstCollateral, bool[] memory borrowingBlacklistedAgainstCollateral ) { ICErc20[] memory poolMarkets = comptroller.getAllMarkets(); collateral = new address[](poolMarkets.length); borrowCapsAgainstCollateral = new uint256[](poolMarkets.length); borrowingBlacklistedAgainstCollateral = new bool[](poolMarkets.length); for (uint256 i = 0; i < poolMarkets.length; i++) { address collateralAddress = address(poolMarkets[i]); if (collateralAddress != address(borrowedAsset)) { collateral[i] = collateralAddress; borrowCapsAgainstCollateral[i] = comptroller.borrowCapForCollateral(address(borrowedAsset), collateralAddress); borrowingBlacklistedAgainstCollateral[i] = comptroller.borrowingAgainstCollateralBlacklist( address(borrowedAsset), collateralAddress ); } } } /** * @notice Returns the `name` and `symbol` of `token`. * Supports Uniswap V2 and SushiSwap LP tokens as well as MKR. * @param token An ERC20 token contract object. * @return The `name` and `symbol`. */ function getTokenNameAndSymbol(address token) internal view returns (string memory, string memory) { // i.e. MKR is a DSToken and uses bytes32 if (bytes(hardcoded[token].symbol).length != 0) { return (hardcoded[token].name, hardcoded[token].symbol); } // Get name and symbol from token contract ERC20Upgradeable tokenContract = ERC20Upgradeable(token); string memory _name = tokenContract.name(); string memory _symbol = tokenContract.symbol(); return (_name, _symbol); } /** * @notice Returns the assets of the specified Ionic pool. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. * @param comptroller The Comptroller proxy contract of the Ionic pool. * @return An array of Ionic pool assets. */ function getPoolAssetsWithData(IonicComptroller comptroller) external returns (PoolAsset[] memory) { return getPoolAssetsWithData(comptroller, comptroller.getAllMarkets(), msg.sender); } /** * @dev Struct for a Ionic pool user. */ struct IonicPoolUser { address account; uint256 totalBorrow; uint256 totalCollateral; uint256 health; } /** * @notice Returns arrays of PoolAsset for a specific user * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getPoolAssetsByUser(IonicComptroller comptroller, address user) public returns (PoolAsset[] memory) { PoolAsset[] memory assets = getPoolAssetsWithData(comptroller, comptroller.getAssetsIn(user), user); return assets; } /** * @notice returns the total supply cap for each asset in the pool * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getSupplyCapsForPool(IonicComptroller comptroller) public view returns (address[] memory, uint256[] memory) { ICErc20[] memory poolMarkets = comptroller.getAllMarkets(); address[] memory assets = new address[](poolMarkets.length); uint256[] memory supplyCapsPerAsset = new uint256[](poolMarkets.length); for (uint256 i = 0; i < poolMarkets.length; i++) { assets[i] = address(poolMarkets[i]); supplyCapsPerAsset[i] = comptroller.supplyCaps(assets[i]); } return (assets, supplyCapsPerAsset); } /** * @notice returns the total supply cap for each asset in the pool and the total non-whitelist supplied assets * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getSupplyCapsDataForPool(IonicComptroller comptroller) public view returns ( address[] memory, uint256[] memory, uint256[] memory ) { ICErc20[] memory poolMarkets = comptroller.getAllMarkets(); address[] memory assets = new address[](poolMarkets.length); uint256[] memory supplyCapsPerAsset = new uint256[](poolMarkets.length); uint256[] memory nonWhitelistedTotalSupply = new uint256[](poolMarkets.length); for (uint256 i = 0; i < poolMarkets.length; i++) { assets[i] = address(poolMarkets[i]); supplyCapsPerAsset[i] = comptroller.supplyCaps(assets[i]); uint256 assetTotalSupplied = poolMarkets[i].getTotalUnderlyingSupplied(); uint256 whitelistedSuppliersSupply = comptroller.getWhitelistedSuppliersSupply(assets[i]); if (whitelistedSuppliersSupply >= assetTotalSupplied) nonWhitelistedTotalSupply[i] = 0; else nonWhitelistedTotalSupply[i] = assetTotalSupplied - whitelistedSuppliersSupply; } return (assets, supplyCapsPerAsset, nonWhitelistedTotalSupply); } /** * @notice returns the total borrow cap and the per collateral borrowing cap/blacklist for the asset * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getBorrowCapsForAsset(ICErc20 asset) public view returns ( address[] memory collateral, uint256[] memory borrowCapsPerCollateral, bool[] memory collateralBlacklisted, uint256 totalBorrowCap ) { IonicComptroller comptroller = IonicComptroller(asset.comptroller()); (collateral, borrowCapsPerCollateral, collateralBlacklisted) = getBorrowCapsPerCollateral(asset, comptroller); totalBorrowCap = comptroller.borrowCaps(address(asset)); } /** * @notice returns the total borrow cap, the per collateral borrowing cap/blacklist for the asset and the total non-whitelist borrows * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getBorrowCapsDataForAsset(ICErc20 asset) public view returns ( address[] memory collateral, uint256[] memory borrowCapsPerCollateral, bool[] memory collateralBlacklisted, uint256 totalBorrowCap, uint256 nonWhitelistedTotalBorrows ) { IonicComptroller comptroller = IonicComptroller(asset.comptroller()); (collateral, borrowCapsPerCollateral, collateralBlacklisted) = getBorrowCapsPerCollateral(asset, comptroller); totalBorrowCap = comptroller.borrowCaps(address(asset)); uint256 totalBorrows = asset.totalBorrowsCurrent(); uint256 whitelistedBorrowersBorrows = comptroller.getWhitelistedBorrowersBorrows(address(asset)); if (whitelistedBorrowersBorrows >= totalBorrows) nonWhitelistedTotalBorrows = 0; else nonWhitelistedTotalBorrows = totalBorrows - whitelistedBorrowersBorrows; } /** * @notice Returns arrays of Ionic pool indexes and data with a whitelist containing `account`. * Note that the whitelist does not have to be enforced. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. */ function getWhitelistedPoolsByAccount(address account) public view returns (uint256[] memory, PoolDirectory.Pool[] memory) { (, PoolDirectory.Pool[] memory pools) = directory.getActivePools(); uint256 arrayLength = 0; for (uint256 i = 0; i < pools.length; i++) { IonicComptroller comptroller = IonicComptroller(pools[i].comptroller); if (comptroller.whitelist(account)) arrayLength++; } uint256[] memory indexes = new uint256[](arrayLength); PoolDirectory.Pool[] memory accountPools = new PoolDirectory.Pool[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < pools.length; i++) { IonicComptroller comptroller = IonicComptroller(pools[i].comptroller); if (comptroller.whitelist(account)) { indexes[index] = i; accountPools[index] = pools[i]; index++; break; } } return (indexes, accountPools); } /** * @notice Returns arrays of the indexes of Ionic pools with a whitelist containing `account`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed. * @dev This function is not designed to be called in a transaction: it is too gas-intensive. * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state. */ function getWhitelistedPoolsByAccountWithData(address account) external returns ( uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory ) { (uint256[] memory indexes, PoolDirectory.Pool[] memory accountPools) = getWhitelistedPoolsByAccount(account); (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(accountPools); return (indexes, accountPools, data, errored); } function getHealthFactor(address user, IonicComptroller pool) external view returns (uint256) { return getHealthFactorHypothetical(pool, user, address(0), 0, 0, 0); } function getHealthFactorHypothetical( IonicComptroller pool, address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount, uint256 repayAmount ) public view returns (uint256) { (uint256 err, uint256 collateralValue, uint256 liquidity, uint256 shortfall) = pool.getHypotheticalAccountLiquidity( account, cTokenModify, redeemTokens, borrowAmount, repayAmount ); if (err != 0) revert ComptrollerError(err); if (shortfall > 0) { // HF < 1.0 return (collateralValue * 1e18) / (collateralValue + shortfall); } else { // HF >= 1.0 if (collateralValue <= liquidity) return type(uint256).max; else return (collateralValue * 1e18) / (collateralValue - liquidity); } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { IonicComptroller } from "./ComptrollerInterface.sol"; import { CTokenSecondExtensionBase, ICErc20 } from "./CTokenInterfaces.sol"; import { TokenErrorReporter } from "./ErrorReporter.sol"; import { Exponential } from "./Exponential.sol"; import { EIP20Interface } from "./EIP20Interface.sol"; import { InterestRateModel } from "./InterestRateModel.sol"; import { ComptrollerV3Storage } from "./ComptrollerStorage.sol"; import { IFeeDistributor } from "./IFeeDistributor.sol"; import { DiamondExtension, LibDiamond } from "../ionic/DiamondExtension.sol"; import { PoolLens } from "../PoolLens.sol"; import { IonicUniV3Liquidator } from "../IonicUniV3Liquidator.sol"; /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @dev This contract should not to be deployed on its own; instead, deploy `CErc20Delegator` (proxy contract) and `CErc20Delegate` (logic/implementation contract). * @author Compound */ abstract contract CErc20 is CTokenSecondExtensionBase, TokenErrorReporter, Exponential, DiamondExtension { modifier isAuthorized() { require( IFeeDistributor(ionicAdmin).canCall(address(comptroller), msg.sender, address(this), msg.sig), "not authorized" ); _; } modifier isMinHFThresholdExceeded(address borrower) { PoolLens lens = PoolLens(ap.getAddress("PoolLens")); IonicUniV3Liquidator liquidator = IonicUniV3Liquidator(payable(ap.getAddress("IonicUniV3Liquidator"))); if (lens.getHealthFactor(borrower, comptroller) > liquidator.healthFactorThreshold()) { require(msg.sender == address(liquidator), "Health factor not low enough for non-permissioned liquidations"); _; } else { _; } } function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory) { uint8 fnsCount = 13; bytes4[] memory functionSelectors = new bytes4[](fnsCount); functionSelectors[--fnsCount] = this.mint.selector; functionSelectors[--fnsCount] = this.redeem.selector; functionSelectors[--fnsCount] = this.redeemUnderlying.selector; functionSelectors[--fnsCount] = this.borrow.selector; functionSelectors[--fnsCount] = this.repayBorrow.selector; functionSelectors[--fnsCount] = this.repayBorrowBehalf.selector; functionSelectors[--fnsCount] = this.liquidateBorrow.selector; functionSelectors[--fnsCount] = this.getCash.selector; functionSelectors[--fnsCount] = this.seize.selector; functionSelectors[--fnsCount] = this.selfTransferOut.selector; functionSelectors[--fnsCount] = this.selfTransferIn.selector; functionSelectors[--fnsCount] = this._withdrawIonicFees.selector; functionSelectors[--fnsCount] = this._withdrawAdminFees.selector; require(fnsCount == 0, "use the correct array length"); return functionSelectors; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint256 mintAmount) external override isAuthorized returns (uint256) { (uint256 err, ) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external override isAuthorized returns (uint256) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external override isAuthorized returns (uint256) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external override isAuthorized returns (uint256) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint256 repayAmount) external override isAuthorized returns (uint256) { (uint256 err, ) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint256 repayAmount) external override isAuthorized returns (uint256) { (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external override isAuthorized isMinHFThresholdExceeded(borrower) returns (uint256) { (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view override returns (uint256) { return getCashInternal(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external override nonReentrant(true) returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } function selfTransferOut(address to, uint256 amount) external override { require(msg.sender == address(this), "!self"); doTransferOut(to, amount); } function selfTransferIn(address from, uint256 amount) external override returns (uint256) { require(msg.sender == address(this), "!self"); return doTransferIn(from, amount); } /** * @notice Accrues interest and reduces Ionic fees by transferring to Ionic * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawIonicFees(uint256 withdrawAmount) external override nonReentrant(false) returns (uint256) { asCTokenExtension().accrueInterest(); if (accrualBlockNumber != block.number) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_IONIC_FEES_FRESH_CHECK); } if (getCashInternal() < withdrawAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE); } if (withdrawAmount > totalIonicFees) { return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_IONIC_FEES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) uint256 totalIonicFeesNew = totalIonicFees - withdrawAmount; totalIonicFees = totalIonicFeesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(address(ionicAdmin), withdrawAmount); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces admin fees by transferring to admin * @param withdrawAmount Amount of fees to withdraw * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawAdminFees(uint256 withdrawAmount) external override nonReentrant(false) returns (uint256) { asCTokenExtension().accrueInterest(); if (accrualBlockNumber != block.number) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_ADMIN_FEES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashInternal() < withdrawAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE); } if (withdrawAmount > totalAdminFees) { return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_ADMIN_FEES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalAdminFees = totalAdminFees - withdrawAmount; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(ComptrollerV3Storage(address(comptroller)).admin(), withdrawAmount); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashInternal() internal view virtual returns (uint256) { return EIP20Interface(underlying).balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint256 amount) internal virtual returns (uint256) { uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); _callOptionalReturn( abi.encodeWithSelector(EIP20Interface.transferFrom.selector, from, address(this), amount), "TOKEN_TRANSFER_IN_FAILED" ); // Calculate the amount that was *actually* transferred uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address to, uint256 amount) internal virtual { _callOptionalReturn( abi.encodeWithSelector(EIP20Interface.transfer.selector, to, amount), "TOKEN_TRANSFER_OUT_FAILED" ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param data The call data (encoded using abi.encode or one of its variants). * @param errorMessage The revert string to return on failure. */ function _callOptionalReturn(bytes memory data, string memory errorMessage) internal { bytes memory returndata = _functionCall(underlying, data, errorMessage); if (returndata.length > 0) require(abi.decode(returndata, (bool)), errorMessage); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount) internal nonReentrant(false) returns (uint256, uint256) { asCTokenExtension().accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 mintTokens; uint256 totalSupplyNew; uint256 accountTokensNew; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256) { /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != block.number) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent(); // Check max supply // unused function /* allowed = comptroller.mintWithinLimits(address(this), vars.exchangeRateMantissa, accountTokens[minter], mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } */ ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ // mintTokens is rounded down here - correct (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate( vars.actualMintAmount, Exp({ mantissa: vars.exchangeRateMantissa }) ); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); require(vars.mintTokens > 0, "MINT_ZERO_CTOKENS_REJECTED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ vars.totalSupplyNew = totalSupply + vars.mintTokens; vars.accountTokensNew = accountTokens[minter] + vars.mintTokens; /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens) internal nonReentrant(false) returns (uint256) { asCTokenExtension().accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant(false) returns (uint256) { asCTokenExtension().accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; uint256 totalSupplyNew; uint256 accountTokensNew; } function divRoundUp(uint256 x, uint256 y) internal pure returns (uint256 res) { res = (x * 1e18) / y; if (x % y != 0) res += 1; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal returns (uint256) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "!redeem tokens or amount"); RedeemLocalVars memory vars; vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent(); if (redeemTokensIn > 0) { // don't allow dust tokens/assets to be left after if (totalSupply - redeemTokensIn < 5000) redeemTokensIn = totalSupply; /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate( Exp({ mantissa: vars.exchangeRateMantissa }), redeemTokensIn ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr)); } } else { if (redeemAmountIn == type(uint256).max) { redeemAmountIn = comptroller.getMaxRedeemOrBorrow(redeemer, ICErc20(address(this)), false); } // don't allow dust tokens/assets to be left after uint256 totalUnderlyingSupplied = asCTokenExtension().getTotalUnderlyingSupplied(); if (totalUnderlyingSupplied - redeemAmountIn < 1000) redeemAmountIn = totalUnderlyingSupplied; /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = divRoundUp(redeemAmountIn, vars.exchangeRateMantissa); // don't allow dust tokens/assets to be left after if (totalSupply - vars.redeemTokens < 1000) vars.redeemTokens = totalSupply; vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint256 allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != block.number) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashInternal() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint256(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount) internal nonReentrant(false) returns (uint256) { asCTokenExtension().accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address borrower, uint256 borrowAmount) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != block.number) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ uint256 cashPrior = getCashInternal(); if (cashPrior < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ vars.accountBorrows = asCTokenExtension().borrowBalanceCurrent(borrower); (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } // Check min borrow for this user for this asset allowed = comptroller.borrowWithinLimits(address(this), vars.accountBorrowsNew); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount) internal nonReentrant(false) returns (uint256, uint256) { asCTokenExtension().accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint256 repayAmount) internal nonReentrant(false) returns (uint256, uint256) { asCTokenExtension().accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != block.number) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ vars.accountBorrows = asCTokenExtension().borrowBalanceCurrent(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == type(uint256).max) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, address cTokenCollateral ) internal nonReentrant(false) returns (uint256, uint256) { asCTokenExtension().accrueInterest(); ICErc20(cTokenCollateral).accrueInterest(); // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), cTokenCollateral, liquidator, borrower, repayAmount ); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != block.number) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (CErc20(cTokenCollateral).accrualBlockNumber() != block.number) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == type(uint256).max) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint256(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = comptroller.liquidateCalculateSeizeTokens( address(this), cTokenCollateral, actualRepayAmount ); require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(ICErc20(cTokenCollateral).balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (cTokenCollateral == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = CErc20(cTokenCollateral).seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "!seize"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, cTokenCollateral, seizeTokens); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), cTokenCollateral, liquidator, borrower, actualRepayAmount, seizeTokens); return (uint256(Error.NO_ERROR), actualRepayAmount); } struct SeizeInternalLocalVars { MathError mathErr; uint256 borrowerTokensNew; uint256 liquidatorTokensNew; uint256 liquidatorSeizeTokens; uint256 protocolSeizeTokens; uint256 protocolSeizeAmount; uint256 exchangeRateMantissa; uint256 totalReservesNew; uint256 totalIonicFeeNew; uint256 totalSupplyNew; uint256 feeSeizeTokens; uint256 feeSeizeAmount; } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } SeizeInternalLocalVars memory vars; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(vars.mathErr)); } vars.protocolSeizeTokens = mul_(seizeTokens, Exp({ mantissa: protocolSeizeShareMantissa })); vars.feeSeizeTokens = mul_(seizeTokens, Exp({ mantissa: feeSeizeShareMantissa })); vars.liquidatorSeizeTokens = seizeTokens - vars.protocolSeizeTokens - vars.feeSeizeTokens; vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent(); vars.protocolSeizeAmount = mul_ScalarTruncate( Exp({ mantissa: vars.exchangeRateMantissa }), vars.protocolSeizeTokens ); vars.feeSeizeAmount = mul_ScalarTruncate(Exp({ mantissa: vars.exchangeRateMantissa }), vars.feeSeizeTokens); vars.totalReservesNew = totalReserves + vars.protocolSeizeAmount; vars.totalSupplyNew = totalSupply - vars.protocolSeizeTokens - vars.feeSeizeTokens; vars.totalIonicFeeNew = totalIonicFees + vars.feeSeizeAmount; (vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ totalReserves = vars.totalReservesNew; totalSupply = vars.totalSupplyNew; totalIonicFees = vars.totalIonicFeeNew; accountTokens[borrower] = vars.borrowerTokensNew; accountTokens[liquidator] = vars.liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens); emit Transfer(borrower, address(this), vars.protocolSeizeTokens); emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint256(Error.NO_ERROR); } function asCTokenExtension() internal view returns (ICErc20) { return ICErc20(address(this)); } /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant(bool localOnly) { _beforeNonReentrant(localOnly); _; _afterNonReentrant(localOnly); } /** * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit. * Saves space because function modifier code is "inlined" into every function with the modifier). * In this specific case, the optimization saves around 1500 bytes of that valuable 24 KB limit. */ function _beforeNonReentrant(bool localOnly) private { require(_notEntered, "re-entered"); if (!localOnly) comptroller._beforeNonReentrant(); _notEntered = false; } /** * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit. * Saves space because function modifier code is "inlined" into every function with the modifier). * In this specific case, the optimization saves around 150 bytes of that valuable 24 KB limit. */ function _afterNonReentrant(bool localOnly) private { _notEntered = true; // get a gas-refund post-Istanbul if (!localOnly) comptroller._afterNonReentrant(); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * @param data The call data (encoded using abi.encode or one of its variants). * @param errorMessage The revert string to return on failure. */ function _functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.call(data); if (!success) { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } return returndata; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { IonicComptroller } from "./ComptrollerInterface.sol"; import { InterestRateModel } from "./InterestRateModel.sol"; import { ComptrollerV3Storage } from "./ComptrollerStorage.sol"; import { AddressesProvider } from "../ionic/AddressesProvider.sol"; abstract contract CTokenAdminStorage { /* * Administrator for Ionic */ address payable public ionicAdmin; } abstract contract CErc20Storage is CTokenAdminStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /* * Maximum borrow rate that can ever be applied (.0005% / block) */ uint256 internal constant borrowRateMaxMantissa = 0.0005e16; /* * Maximum fraction of interest that can be set aside for reserves + fees */ uint256 internal constant reserveFactorPlusFeesMaxMantissa = 1e18; /** * @notice Contract which oversees inter-cToken operations */ IonicComptroller public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /* * Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint256 internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for admin fees */ uint256 public adminFeeMantissa; /** * @notice Fraction of interest currently set aside for Ionic fees */ uint256 public ionicFeeMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint256 public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint256 public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint256 public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint256 public totalReserves; /** * @notice Total amount of admin fees of the underlying held in this market */ uint256 public totalAdminFees; /** * @notice Total amount of Ionic fees of the underlying held in this market */ uint256 public totalIonicFees; /** * @notice Total number of tokens in circulation */ uint256 public totalSupply; /* * Official record of token balances for each account */ mapping(address => uint256) internal accountTokens; /* * Approved token transfer amounts on behalf of others */ mapping(address => mapping(address => uint256)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint256 principal; uint256 interestIndex; } /* * Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /* * Share of seized collateral that is added to reserves */ uint256 public constant protocolSeizeShareMantissa = 2.8e16; //2.8% /* * Share of seized collateral taken as fees */ uint256 public constant feeSeizeShareMantissa = 1e17; //10% /** * @notice Underlying asset for this CToken */ address public underlying; /** * @notice Addresses Provider */ AddressesProvider public ap; } abstract contract CTokenBaseEvents { /* ERC20 */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /*** Admin Events ***/ /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the admin fee is changed */ event NewAdminFee(uint256 oldAdminFeeMantissa, uint256 newAdminFeeMantissa); /** * @notice Event emitted when the Ionic fee is changed */ event NewIonicFee(uint256 oldIonicFeeMantissa, uint256 newIonicFeeMantissa); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); } abstract contract CTokenFirstExtensionEvents is CTokenBaseEvents { event Flash(address receiver, uint256 amount); } abstract contract CTokenSecondExtensionEvents is CTokenBaseEvents { /*** Market Events ***/ /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow( address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens ); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); } interface CTokenFirstExtensionInterface { /*** User Interface ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); /*** Admin Functions ***/ function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256); function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256); function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function exchangeRateCurrent() external view returns (uint256); function accrueInterest() external returns (uint256); function totalBorrowsCurrent() external view returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function getTotalUnderlyingSupplied() external view returns (uint256); function balanceOfUnderlying(address owner) external view returns (uint256); function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); function flash(uint256 amount, bytes calldata data) external; function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256); function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256); function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) external view returns (uint256); function registerInSFS() external returns (uint256); } interface CTokenSecondExtensionInterface { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getCash() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); /*** Admin Functions ***/ function _withdrawAdminFees(uint256 withdrawAmount) external returns (uint256); function _withdrawIonicFees(uint256 withdrawAmount) external returns (uint256); function selfTransferOut(address to, uint256 amount) external; function selfTransferIn(address from, uint256 amount) external returns (uint256); } interface CDelegatorInterface { function implementation() external view returns (address); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external; /** * @dev upgrades the implementation if necessary */ function _upgrade() external; } interface CDelegateInterface { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes calldata data) external; function delegateType() external pure returns (uint8); function contractType() external pure returns (string memory); } abstract contract CErc20AdminBase is CErc20Storage { /** * @notice Returns a boolean indicating if the sender has admin rights */ function hasAdminRights() internal view returns (bool) { ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller)); return (msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) || (msg.sender == address(ionicAdmin) && comptrollerStorage.ionicAdminHasRights()); } } abstract contract CErc20FirstExtensionBase is CErc20AdminBase, CTokenFirstExtensionEvents, CTokenFirstExtensionInterface {} abstract contract CTokenSecondExtensionBase is CErc20AdminBase, CTokenSecondExtensionEvents, CTokenSecondExtensionInterface, CDelegateInterface {} abstract contract CErc20DelegatorBase is CErc20AdminBase, CTokenSecondExtensionEvents, CDelegatorInterface {} interface CErc20StorageInterface { function admin() external view returns (address); function adminHasRights() external view returns (bool); function ionicAdmin() external view returns (address); function ionicAdminHasRights() external view returns (bool); function comptroller() external view returns (IonicComptroller); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function adminFeeMantissa() external view returns (uint256); function ionicFeeMantissa() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function protocolSeizeShareMantissa() external view returns (uint256); function feeSeizeShareMantissa() external view returns (uint256); function totalReserves() external view returns (uint256); function totalAdminFees() external view returns (uint256); function totalIonicFees() external view returns (uint256); function totalBorrows() external view returns (uint256); function accrualBlockNumber() external view returns (uint256); function underlying() external view returns (address); function borrowIndex() external view returns (uint256); function interestRateModel() external view returns (address); } interface CErc20PluginStorageInterface is CErc20StorageInterface { function plugin() external view returns (address); } interface CErc20PluginRewardsInterface is CErc20PluginStorageInterface { function approve(address, address) external; } interface ICErc20 is CErc20StorageInterface, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface, CDelegatorInterface, CDelegateInterface {} interface ICErc20Plugin is CErc20PluginStorageInterface, ICErc20 { function _updatePlugin(address _plugin) external; } interface ICErc20PluginRewards is CErc20PluginRewardsInterface, ICErc20 {}
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /** * @title Careful Math * @author Compound * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c; unchecked { c = a * b; } if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c; unchecked { c = a + b; } if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { ICErc20 } from "./CTokenInterfaces.sol"; import { ComptrollerErrorReporter } from "./ErrorReporter.sol"; import { Exponential } from "./Exponential.sol"; import { BasePriceOracle } from "../oracles/BasePriceOracle.sol"; import { Unitroller } from "./Unitroller.sol"; import { IFeeDistributor } from "./IFeeDistributor.sol"; import { IIonicFlywheel } from "../ionic/strategies/flywheel/IIonicFlywheel.sol"; import { DiamondExtension, DiamondBase, LibDiamond } from "../ionic/DiamondExtension.sol"; import { ComptrollerExtensionInterface, ComptrollerBase, ComptrollerInterface } from "./ComptrollerInterface.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** * @title Compound's Comptroller Contract * @author Compound * @dev This contract should not to be deployed alone; instead, deploy `Unitroller` (proxy contract) on top of this `Comptroller` (logic/implementation contract). */ contract Comptroller is ComptrollerBase, ComptrollerInterface, ComptrollerErrorReporter, Exponential, DiamondExtension { using EnumerableSet for EnumerableSet.AddressSet; /// @notice Emitted when an admin supports a market event MarketListed(ICErc20 cToken); /// @notice Emitted when an account enters a market event MarketEntered(ICErc20 cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(ICErc20 cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(ICErc20 cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(BasePriceOracle oldPriceOracle, BasePriceOracle newPriceOracle); /// @notice Emitted when the whitelist enforcement is changed event WhitelistEnforcementChanged(bool enforce); /// @notice Emitted when a new RewardsDistributor contract is added to hooks event AddedRewardsDistributor(address rewardsDistributor); // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 modifier isAuthorized() { require(IFeeDistributor(ionicAdmin).canCall(address(this), msg.sender, address(this), msg.sig), "not authorized"); _; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (ICErc20[] memory) { ICErc20[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, ICErc20 cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public override isAuthorized returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { ICErc20 cToken = ICErc20(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(ICErc20 cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); // Add to allBorrowers if (!borrowers[borrower]) { allBorrowers.push(borrower); borrowers[borrower] = true; borrowerIndexes[borrower] = allBorrowers.length - 1; } emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external override isAuthorized returns (uint256) { // TODO require(markets[cTokenAddress].isListed, "!Comptroller:exitMarket"); ICErc20 cToken = ICErc20(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "!exitMarket"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint256 allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[cTokenAddress]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration ICErc20[] memory userAssetList = accountAssets[msg.sender]; uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == ICErc20(cTokenAddress)) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 ICErc20[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); // If the user has exited all markets, remove them from the `allBorrowers` array if (storedList.length == 0) { allBorrowers[borrowerIndexes[msg.sender]] = allBorrowers[allBorrowers.length - 1]; // Copy last item in list to location of item to be removed allBorrowers.pop(); // Reduce length by 1 borrowerIndexes[allBorrowers[borrowerIndexes[msg.sender]]] = borrowerIndexes[msg.sender]; // Set borrower index of moved item to correct index borrowerIndexes[msg.sender] = 0; // Reset sender borrower index to 0 for a gas refund borrowers[msg.sender] = false; // Tell the contract that the sender is no longer a borrower (so it knows to add the borrower back if they enter a market in the future) } emit MarketExited(ICErc20(cTokenAddress), msg.sender); return uint256(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cTokenAddress The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cTokenAddress, address minter, uint256 mintAmount ) external override returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cTokenAddress], "!mint:paused"); // Make sure market is listed if (!markets[cTokenAddress].isListed) { return uint256(Error.MARKET_NOT_LISTED); } // Make sure minter is whitelisted if (enforceWhitelist && !whitelist[minter]) { return uint256(Error.SUPPLIER_NOT_WHITELISTED); } // Check supply cap uint256 supplyCap = supplyCaps[cTokenAddress]; // Supply cap of 0 corresponds to unlimited supplying if (supplyCap != 0 && !supplyCapWhitelist[cTokenAddress].contains(minter)) { uint256 totalUnderlyingSupply = ICErc20(cTokenAddress).getTotalUnderlyingSupplied(); uint256 whitelistedSuppliersSupply = asComptrollerExtension().getWhitelistedSuppliersSupply(cTokenAddress); uint256 nonWhitelistedTotalSupply; if (whitelistedSuppliersSupply >= totalUnderlyingSupply) nonWhitelistedTotalSupply = 0; else nonWhitelistedTotalSupply = totalUnderlyingSupply - whitelistedSuppliersSupply; require(nonWhitelistedTotalSupply + mintAmount < supplyCap, "!supply cap"); } // Keep the flywheel moving flywheelPreSupplierAction(cTokenAddress, minter); return uint256(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external override returns (uint256) { uint256 allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving flywheelPreSupplierAction(cToken, redeemer); return uint256(Error.NO_ERROR); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, ICErc20(cToken), redeemTokens, 0, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { // Add minter to suppliers mapping suppliers[minter] = true; } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external override { require(markets[msg.sender].isListed, "!market"); // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("!zero"); } } function getMaxRedeemOrBorrow( address account, ICErc20 cTokenModify, bool isBorrow ) external view override returns (uint256) { address cToken = address(cTokenModify); // Accrue interest uint256 balanceOfUnderlying = cTokenModify.balanceOfUnderlying(account); // Get account liquidity (Error err, , uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal( account, isBorrow ? cTokenModify : ICErc20(address(0)), 0, 0, 0 ); require(err == Error.NO_ERROR, "!liquidity"); if (shortfall > 0) return 0; // Shortfall, so no more borrow/redeem // Get max borrow/redeem uint256 maxBorrowOrRedeemAmount; if (!isBorrow && !markets[cToken].accountMembership[account]) { // Max redeem = balance of underlying if not used as collateral maxBorrowOrRedeemAmount = balanceOfUnderlying; } else { // Avoid "stack too deep" error by separating this logic maxBorrowOrRedeemAmount = _getMaxRedeemOrBorrow(liquidity, cTokenModify, isBorrow); // Redeem only: max out at underlying balance if (!isBorrow && balanceOfUnderlying < maxBorrowOrRedeemAmount) maxBorrowOrRedeemAmount = balanceOfUnderlying; } // Get max borrow or redeem considering cToken liquidity uint256 cTokenLiquidity = cTokenModify.getCash(); // Return the minimum of the two maximums return maxBorrowOrRedeemAmount <= cTokenLiquidity ? maxBorrowOrRedeemAmount : cTokenLiquidity; } /** * @dev Portion of the logic in `getMaxRedeemOrBorrow` above separated to avoid "stack too deep" errors. */ function _getMaxRedeemOrBorrow( uint256 liquidity, ICErc20 cTokenModify, bool isBorrow ) internal view returns (uint256) { if (liquidity == 0) return 0; // No available account liquidity, so no more borrow/redeem // Get the normalized price of the asset uint256 conversionFactor = oracle.getUnderlyingPrice(cTokenModify); require(conversionFactor > 0, "!oracle"); // Pre-compute a conversion factor from tokens -> ether (normalized price value) if (!isBorrow) { uint256 collateralFactorMantissa = markets[address(cTokenModify)].collateralFactorMantissa; conversionFactor = (collateralFactorMantissa * conversionFactor) / 1e18; } // Get max borrow or redeem considering excess account liquidity return (liquidity * 1e18) / conversionFactor; } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external override returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "!borrow:paused"); // Make sure market is listed if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "!ctoken"); // attempt to add borrower to the market Error err = addToMarketInternal(ICErc20(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } // Make sure oracle price is available if (oracle.getUnderlyingPrice(ICErc20(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } // Make sure borrower is whitelisted if (enforceWhitelist && !whitelist[borrower]) { return uint256(Error.SUPPLIER_NOT_WHITELISTED); } // Check borrow cap uint256 borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0 && !borrowCapWhitelist[cToken].contains(borrower)) { uint256 totalBorrows = ICErc20(cToken).totalBorrowsCurrent(); uint256 whitelistedBorrowersBorrows = asComptrollerExtension().getWhitelistedBorrowersBorrows(cToken); uint256 nonWhitelistedTotalBorrows; if (whitelistedBorrowersBorrows >= totalBorrows) nonWhitelistedTotalBorrows = 0; else nonWhitelistedTotalBorrows = totalBorrows - whitelistedBorrowersBorrows; require(nonWhitelistedTotalBorrows + borrowAmount < borrowCap, "!borrow:cap"); } // Keep the flywheel moving flywheelPreBorrowerAction(cToken, borrower); // Perform a hypothetical liquidity check to guard against shortfall (uint256 err, , , uint256 shortfall) = this.getHypotheticalAccountLiquidity(borrower, cToken, 0, borrowAmount, 0); if (err != uint256(Error.NO_ERROR)) { return err; } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken Asset whose underlying is being borrowed * @param accountBorrowsNew The user's new borrow balance of the underlying asset */ function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view override returns (uint256) { // Check if min borrow exists uint256 minBorrowEth = IFeeDistributor(ionicAdmin).minBorrowEth(); if (minBorrowEth > 0) { // Get new underlying borrow balance of account for this cToken uint256 oraclePriceMantissa = oracle.getUnderlyingPrice(ICErc20(cToken)); if (oraclePriceMantissa == 0) return uint256(Error.PRICE_ERROR); (MathError mathErr, uint256 borrowBalanceEth) = mulScalarTruncate( Exp({ mantissa: oraclePriceMantissa }), accountBorrowsNew ); if (mathErr != MathError.NO_ERROR) return uint256(Error.MATH_ERROR); // Check against min borrow if (borrowBalanceEth < minBorrowEth) return uint256(Error.BORROW_BELOW_MIN); } // Return no error return uint256(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external override returns (uint256) { // Make sure market is listed if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving flywheelPreBorrowerAction(cToken, borrower); return uint256(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external override returns (uint256) { // Make sure markets are listed if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint256(Error.MARKET_NOT_LISTED); } // Get borrowers' underlying borrow balance uint256 borrowBalance = ICErc20(cTokenBorrowed).borrowBalanceCurrent(borrower); /* allow accounts to be liquidated if the market is deprecated */ if (isDeprecated(ICErc20(cTokenBorrowed))) { require(borrowBalance >= repayAmount, "!borrow>repay"); } else { /* The borrower must have shortfall in order to be liquidateable */ (Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal( borrower, ICErc20(address(0)), 0, 0, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 maxClose = mul_ScalarTruncate(Exp({ mantissa: closeFactorMantissa }), borrowBalance); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external override returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "!seize:paused"); // Make sure markets are listed if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint256(Error.MARKET_NOT_LISTED); } // Make sure cToken Comptrollers are identical if (ICErc20(cTokenCollateral).comptroller() != ICErc20(cTokenBorrowed).comptroller()) { return uint256(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving flywheelPreTransferAction(cTokenCollateral, borrower, liquidator); return uint256(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external override returns (uint256) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "!transfer:paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint256 allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving flywheelPreTransferAction(cToken, src, dst); return uint256(Error.NO_ERROR); } /*** Flywheel Hooks ***/ /** * @notice Keeps the flywheel moving pre-mint and pre-redeem * @param cToken The relevant market * @param supplier The minter/redeemer */ function flywheelPreSupplierAction(address cToken, address supplier) internal { for (uint256 i = 0; i < rewardsDistributors.length; i++) IIonicFlywheel(rewardsDistributors[i]).flywheelPreSupplierAction(cToken, supplier); } /** * @notice Keeps the flywheel moving pre-borrow and pre-repay * @param cToken The relevant market * @param borrower The borrower */ function flywheelPreBorrowerAction(address cToken, address borrower) internal { for (uint256 i = 0; i < rewardsDistributors.length; i++) IIonicFlywheel(rewardsDistributors[i]).flywheelPreBorrowerAction(cToken, borrower); } /** * @notice Keeps the flywheel moving pre-transfer and pre-seize * @param cToken The relevant market * @param src The account which sources the tokens * @param dst The account which receives the tokens */ function flywheelPreTransferAction( address cToken, address src, address dst ) internal { for (uint256 i = 0; i < rewardsDistributors.length; i++) IIonicFlywheel(rewardsDistributors[i]).flywheelPreTransferAction(cToken, src, dst); } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { ICErc20 asset; uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; uint256 borrowCapForCollateral; uint256 borrowedAssetPrice; uint256 assetAsCollateralValueCap; } function getAccountLiquidity(address account) public view override returns ( uint256, uint256, uint256, uint256 ) { ( Error err, uint256 collateralValue, uint256 liquidity, uint256 shortfall ) = getHypotheticalAccountLiquidityInternal(account, ICErc20(address(0)), 0, 0, 0); return (uint256(err), collateralValue, liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount, uint256 repayAmount ) public view returns ( uint256, uint256, uint256, uint256 ) { ( Error err, uint256 collateralValue, uint256 liquidity, uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( account, ICErc20(cTokenModify), redeemTokens, borrowAmount, repayAmount ); return (uint256(err), collateralValue, liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code, hypothetical account collateral value, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, ICErc20 cTokenModify, uint256 redeemTokens, uint256 borrowAmount, uint256 repayAmount ) internal view returns ( Error, uint256, uint256, uint256 ) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results if (address(cTokenModify) != address(0)) { vars.borrowedAssetPrice = oracle.getUnderlyingPrice(cTokenModify); } // For each asset the account is in for (uint256 i = 0; i < accountAssets[account].length; i++) { vars.asset = accountAssets[account][i]; { // Read the balances and exchange rate from the cToken uint256 oErr; (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = vars.asset.getAccountSnapshot( account ); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0, 0); } } { vars.collateralFactor = Exp({ mantissa: markets[address(vars.asset)].collateralFactorMantissa }); vars.exchangeRate = Exp({ mantissa: vars.exchangeRateMantissa }); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(vars.asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0, 0); } vars.oraclePrice = Exp({ mantissa: vars.oraclePriceMantissa }); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); } { // Exclude the asset-to-be-borrowed from the liquidity, except for when redeeming vars.assetAsCollateralValueCap = asComptrollerExtension().getAssetAsCollateralValueCap( vars.asset, cTokenModify, redeemTokens > 0, account ); // accumulate the collateral value to sumCollateral uint256 assetCollateralValue = mul_ScalarTruncate(vars.tokensToDenom, vars.cTokenBalance); if (assetCollateralValue > vars.assetAsCollateralValueCap) assetCollateralValue = vars.assetAsCollateralValueCap; vars.sumCollateral += assetCollateralValue; } // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (vars.asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); uint256 repayEffect = mul_ScalarTruncate(vars.oraclePrice, repayAmount); if (repayEffect >= vars.sumBorrowPlusEffects) { vars.sumBorrowPlusEffects = 0; } else { vars.sumBorrowPlusEffects -= repayEffect; } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, vars.sumCollateral, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view override returns (uint256, uint256) { /* Read oracle prices for borrowed and collateral markets */ uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenBorrowed)); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint256(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ ICErc20 collateralCToken = ICErc20(cTokenCollateral); uint256 exchangeRateMantissa = collateralCToken.exchangeRateCurrent(); uint256 seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; uint256 protocolSeizeShareMantissa = collateralCToken.protocolSeizeShareMantissa(); uint256 feeSeizeShareMantissa = collateralCToken.feeSeizeShareMantissa(); /* * The liquidation penalty includes * - the liquidator incentive * - the protocol fees (Ionic admin fees) * - the market fee */ Exp memory totalPenaltyMantissa = add_( add_(Exp({ mantissa: liquidationIncentiveMantissa }), Exp({ mantissa: protocolSeizeShareMantissa })), Exp({ mantissa: feeSeizeShareMantissa }) ); numerator = mul_(totalPenaltyMantissa, Exp({ mantissa: priceBorrowedMantissa })); denominator = mul_(Exp({ mantissa: priceCollateralMantissa }), Exp({ mantissa: exchangeRateMantissa })); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Add a RewardsDistributor contracts. * @dev Admin function to add a RewardsDistributor contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addRewardsDistributor(address distributor) external returns (uint256) { require(hasAdminRights(), "!admin"); // Check marker method require(IIonicFlywheel(distributor).isRewardsDistributor(), "!isRewardsDistributor"); // Check for existing RewardsDistributor for (uint256 i = 0; i < rewardsDistributors.length; i++) require(distributor != rewardsDistributors[i], "!added"); // Add RewardsDistributor to array rewardsDistributors.push(distributor); emit AddedRewardsDistributor(distributor); return uint256(Error.NO_ERROR); } /** * @notice Sets the whitelist enforcement for the comptroller * @dev Admin function to set a new whitelist enforcement boolean * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setWhitelistEnforcement(bool enforce) external returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_ENFORCEMENT_OWNER_CHECK); } // Check if `enforceWhitelist` already equals `enforce` if (enforceWhitelist == enforce) { return uint256(Error.NO_ERROR); } // Set comptroller's `enforceWhitelist` to `enforce` enforceWhitelist = enforce; // Emit WhitelistEnforcementChanged(bool enforce); emit WhitelistEnforcementChanged(enforce); return uint256(Error.NO_ERROR); } /** * @notice Sets the whitelist `statuses` for `suppliers` * @dev Admin function to set the whitelist `statuses` for `suppliers` * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setWhitelistStatuses(address[] calldata suppliers, bool[] calldata statuses) external returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_STATUS_OWNER_CHECK); } // Set whitelist statuses for suppliers for (uint256 i = 0; i < suppliers.length; i++) { address supplier = suppliers[i]; if (statuses[i]) { // If not already whitelisted, add to whitelist if (!whitelist[supplier]) { whitelist[supplier] = true; whitelistArray.push(supplier); whitelistIndexes[supplier] = whitelistArray.length - 1; } } else { // If whitelisted, remove from whitelist if (whitelist[supplier]) { whitelistArray[whitelistIndexes[supplier]] = whitelistArray[whitelistArray.length - 1]; // Copy last item in list to location of item to be removed whitelistArray.pop(); // Reduce length by 1 whitelistIndexes[whitelistArray[whitelistIndexes[supplier]]] = whitelistIndexes[supplier]; // Set whitelist index of moved item to correct index whitelistIndexes[supplier] = 0; // Reset supplier whitelist index to 0 for a gas refund whitelist[supplier] = false; // Tell the contract that the supplier is no longer whitelisted } } } return uint256(Error.NO_ERROR); } /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(BasePriceOracle newOracle) public returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller BasePriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint256(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } // Check limits Exp memory newCloseFactorExp = Exp({ mantissa: newCloseFactorMantissa }); Exp memory lowLimit = Exp({ mantissa: closeFactorMinMantissa }); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({ mantissa: closeFactorMaxMantissa }); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } // Set pool close factor to new close factor, remember old value uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; // Emit event emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(ICErc20 cToken, uint256 newCollateralFactorMantissa) public returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({ mantissa: collateralFactorMaxMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint256(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({ mantissa: newLiquidationIncentiveMantissa }); Exp memory minLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMinMantissa }); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMaxMantissa }); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint256(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(ICErc20 cToken) internal returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } // Is market already listed? if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } // Check cToken.comptroller == this require(address(cToken.comptroller()) == address(this), "!comptroller"); // Make sure market is not already listed address underlying = ICErc20(address(cToken)).underlying(); if (address(cTokensByUnderlying[underlying]) != address(0)) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } // List market and emit event Market storage market = markets[address(cToken)]; market.isListed = true; market.collateralFactorMantissa = 0; allMarkets.push(cToken); cTokensByUnderlying[underlying] = cToken; emit MarketListed(cToken); return uint256(Error.NO_ERROR); } /** * @notice Deploy cToken, add the market to the markets mapping, and set it as listed and set the collateral factor * @dev Admin function to deploy cToken, set isListed, and add support for the market and set the collateral factor * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _deployMarket( uint8 delegateType, bytes calldata constructorData, bytes calldata becomeImplData, uint256 collateralFactorMantissa ) external returns (uint256) { // Check caller is admin if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } // Temporarily enable Ionic admin rights for asset deployment (storing the original value) bool oldIonicAdminHasRights = ionicAdminHasRights; ionicAdminHasRights = true; // Deploy via Ionic admin ICErc20 cToken = ICErc20(IFeeDistributor(ionicAdmin).deployCErc20(delegateType, constructorData, becomeImplData)); // Reset Ionic admin rights to the original value ionicAdminHasRights = oldIonicAdminHasRights; // Support market here in the Comptroller uint256 err = _supportMarket(cToken); IFeeDistributor(ionicAdmin).authoritiesRegistry().reconfigureAuthority(address(this)); // Set collateral factor return err == uint256(Error.NO_ERROR) ? _setCollateralFactor(cToken, collateralFactorMantissa) : err; } function _becomeImplementation() external { require(msg.sender == address(this), "!self call"); if (!_notEnteredInitialized) { _notEntered = true; _notEnteredInitialized = true; } } /*** Helper Functions ***/ /** * @notice Returns true if the given cToken market has been deprecated * @dev All borrows in a deprecated cToken market can be immediately liquidated * @param cToken The market to check if deprecated */ function isDeprecated(ICErc20 cToken) public view returns (bool) { return markets[address(cToken)].collateralFactorMantissa == 0 && borrowGuardianPaused[address(cToken)] == true && add_(add_(cToken.reserveFactorMantissa(), cToken.adminFeeMantissa()), cToken.ionicFeeMantissa()) == 1e18; } function asComptrollerExtension() internal view returns (ComptrollerExtensionInterface) { return ComptrollerExtensionInterface(address(this)); } function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory functionSelectors) { uint8 fnsCount = 30; functionSelectors = new bytes4[](fnsCount); functionSelectors[--fnsCount] = this.isDeprecated.selector; functionSelectors[--fnsCount] = this._deployMarket.selector; functionSelectors[--fnsCount] = this.getAssetsIn.selector; functionSelectors[--fnsCount] = this.checkMembership.selector; functionSelectors[--fnsCount] = this._setPriceOracle.selector; functionSelectors[--fnsCount] = this._setCloseFactor.selector; functionSelectors[--fnsCount] = this._setCollateralFactor.selector; functionSelectors[--fnsCount] = this._setLiquidationIncentive.selector; functionSelectors[--fnsCount] = this._setWhitelistEnforcement.selector; functionSelectors[--fnsCount] = this._setWhitelistStatuses.selector; functionSelectors[--fnsCount] = this._addRewardsDistributor.selector; functionSelectors[--fnsCount] = this.getHypotheticalAccountLiquidity.selector; functionSelectors[--fnsCount] = this.getMaxRedeemOrBorrow.selector; functionSelectors[--fnsCount] = this.enterMarkets.selector; functionSelectors[--fnsCount] = this.exitMarket.selector; functionSelectors[--fnsCount] = this.mintAllowed.selector; functionSelectors[--fnsCount] = this.redeemAllowed.selector; functionSelectors[--fnsCount] = this.redeemVerify.selector; functionSelectors[--fnsCount] = this.borrowAllowed.selector; functionSelectors[--fnsCount] = this.borrowWithinLimits.selector; functionSelectors[--fnsCount] = this.repayBorrowAllowed.selector; functionSelectors[--fnsCount] = this.liquidateBorrowAllowed.selector; functionSelectors[--fnsCount] = this.seizeAllowed.selector; functionSelectors[--fnsCount] = this.transferAllowed.selector; functionSelectors[--fnsCount] = this.mintVerify.selector; functionSelectors[--fnsCount] = this.getAccountLiquidity.selector; functionSelectors[--fnsCount] = this.liquidateCalculateSeizeTokens.selector; functionSelectors[--fnsCount] = this._beforeNonReentrant.selector; functionSelectors[--fnsCount] = this._afterNonReentrant.selector; functionSelectors[--fnsCount] = this._becomeImplementation.selector; require(fnsCount == 0, "use the correct array length"); } /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/ /** * @dev Called by cTokens before a non-reentrant function for pool-wide reentrancy prevention. * Prevents pool-wide/cross-asset reentrancy exploits like AMP on Cream. */ function _beforeNonReentrant() external override { require(markets[msg.sender].isListed, "!Comptroller:_beforeNonReentrant"); require(_notEntered, "!reentered"); _notEntered = false; } /** * @dev Called by cTokens after a non-reentrant function for pool-wide reentrancy prevention. * Prevents pool-wide/cross-asset reentrancy exploits like AMP on Cream. */ function _afterNonReentrant() external override { require(markets[msg.sender].isListed, "!Comptroller:_afterNonReentrant"); _notEntered = true; // get a gas-refund post-Istanbul } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { BasePriceOracle } from "../oracles/BasePriceOracle.sol"; import { ICErc20 } from "./CTokenInterfaces.sol"; import { ComptrollerV3Storage } from "../compound/ComptrollerStorage.sol"; interface ComptrollerInterface { function isDeprecated(ICErc20 cToken) external view returns (bool); function _becomeImplementation() external; function _deployMarket( uint8 delegateType, bytes memory constructorData, bytes calldata becomeImplData, uint256 collateralFactorMantissa ) external returns (uint256); function getAssetsIn(address account) external view returns (ICErc20[] memory); function checkMembership(address account, ICErc20 cToken) external view returns (bool); function _setPriceOracle(BasePriceOracle newOracle) external returns (uint256); function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256); function _setCollateralFactor(ICErc20 market, uint256 newCollateralFactorMantissa) external returns (uint256); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256); function _setWhitelistEnforcement(bool enforce) external returns (uint256); function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256); function _addRewardsDistributor(address distributor) external returns (uint256); function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount, uint256 repayAmount ) external view returns ( uint256, uint256, uint256, uint256 ); function getMaxRedeemOrBorrow( address account, ICErc20 cToken, bool isBorrow ) external view returns (uint256); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view returns (uint256); function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function getAccountLiquidity(address account) external view returns ( uint256 error, uint256 collateralValue, uint256 liquidity, uint256 shortfall ); function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/ function _beforeNonReentrant() external; function _afterNonReentrant() external; } interface ComptrollerStorageInterface { function admin() external view returns (address); function adminHasRights() external view returns (bool); function ionicAdmin() external view returns (address); function ionicAdminHasRights() external view returns (bool); function pendingAdmin() external view returns (address); function oracle() external view returns (BasePriceOracle); function pauseGuardian() external view returns (address); function closeFactorMantissa() external view returns (uint256); function liquidationIncentiveMantissa() external view returns (uint256); function isUserOfPool(address user) external view returns (bool); function whitelist(address account) external view returns (bool); function enforceWhitelist() external view returns (bool); function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256); function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool); function suppliers(address account) external view returns (bool); function cTokensByUnderlying(address) external view returns (address); function supplyCaps(address cToken) external view returns (uint256); function borrowCaps(address cToken) external view returns (uint256); function markets(address cToken) external view returns (bool, uint256); function accountAssets(address, uint256) external view returns (address); function borrowGuardianPaused(address cToken) external view returns (bool); function mintGuardianPaused(address cToken) external view returns (bool); function rewardsDistributors(uint256) external view returns (address); } interface SFSRegister { function register(address _recipient) external returns (uint256 tokenId); } interface ComptrollerExtensionInterface { function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied); function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed); function getAllMarkets() external view returns (ICErc20[] memory); function getAllBorrowers() external view returns (address[] memory); function getAllBorrowersCount() external view returns (uint256); function getPaginatedBorrowers(uint256 page, uint256 pageSize) external view returns (uint256 _totalPages, address[] memory _pageOfBorrowers); function getRewardsDistributors() external view returns (address[] memory); function getAccruingFlywheels() external view returns (address[] memory); function _supplyCapWhitelist( address cToken, address account, bool whitelisted ) external; function _setBorrowCapForCollateral( address cTokenBorrow, address cTokenCollateral, uint256 borrowCap ) external; function _setBorrowCapForCollateralWhitelist( address cTokenBorrow, address cTokenCollateral, address account, bool whitelisted ) external; function isBorrowCapForCollateralWhitelisted( address cTokenBorrow, address cTokenCollateral, address account ) external view returns (bool); function _blacklistBorrowingAgainstCollateral( address cTokenBorrow, address cTokenCollateral, bool blacklisted ) external; function _blacklistBorrowingAgainstCollateralWhitelist( address cTokenBorrow, address cTokenCollateral, address account, bool whitelisted ) external; function isBlacklistBorrowingAgainstCollateralWhitelisted( address cTokenBorrow, address cTokenCollateral, address account ) external view returns (bool); function isSupplyCapWhitelisted(address cToken, address account) external view returns (bool); function _borrowCapWhitelist( address cToken, address account, bool whitelisted ) external; function isBorrowCapWhitelisted(address cToken, address account) external view returns (bool); function _removeFlywheel(address flywheelAddress) external returns (bool); function getWhitelist() external view returns (address[] memory); function addNonAccruingFlywheel(address flywheelAddress) external returns (bool); function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external; function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external; function _setBorrowCapGuardian(address newBorrowCapGuardian) external; function _setPauseGuardian(address newPauseGuardian) external returns (uint256); function _setMintPaused(ICErc20 cToken, bool state) external returns (bool); function _setBorrowPaused(ICErc20 cToken, bool state) external returns (bool); function _setTransferPaused(bool state) external returns (bool); function _setSeizePaused(bool state) external returns (bool); function _unsupportMarket(ICErc20 cToken) external returns (uint256); function getAssetAsCollateralValueCap( ICErc20 collateral, ICErc20 cTokenModify, bool redeeming, address account ) external view returns (uint256); function registerInSFS() external returns (uint256); } interface UnitrollerInterface { function comptrollerImplementation() external view returns (address); function _upgrade() external; function _acceptAdmin() external returns (uint256); function _setPendingAdmin(address newPendingAdmin) external returns (uint256); function _toggleAdminRights(bool hasRights) external returns (uint256); } interface IComptrollerExtension is ComptrollerExtensionInterface, ComptrollerStorageInterface {} //interface IComptrollerBase is ComptrollerInterface, ComptrollerStorageInterface {} interface IonicComptroller is ComptrollerInterface, ComptrollerExtensionInterface, UnitrollerInterface, ComptrollerStorageInterface { } abstract contract ComptrollerBase is ComptrollerV3Storage { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "./IFeeDistributor.sol"; import "../oracles/BasePriceOracle.sol"; import { ICErc20 } from "./CTokenInterfaces.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract UnitrollerAdminStorage { /* * Administrator for Ionic */ address payable public ionicAdmin; /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Whether or not the Ionic admin has admin rights */ bool public ionicAdminHasRights = true; /** * @notice Whether or not the admin has admin rights */ bool public adminHasRights = true; /** * @notice Returns a boolean indicating if the sender has admin rights */ function hasAdminRights() internal view returns (bool) { return (msg.sender == admin && adminHasRights) || (msg.sender == address(ionicAdmin) && ionicAdminHasRights); } } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ BasePriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; /* * UNUSED AFTER UPGRADE: Max number of assets a single account can participate in (borrow or use as collateral) */ uint256 internal maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => ICErc20[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint256 collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /// @notice A list of all markets ICErc20[] public allMarkets; /** * @dev Maps borrowers to booleans indicating if they have entered any markets */ mapping(address => bool) internal borrowers; /// @notice A list of all borrowers who have entered markets address[] public allBorrowers; // Indexes of borrower account addresses in the `allBorrowers` array mapping(address => uint256) internal borrowerIndexes; /** * @dev Maps suppliers to booleans indicating if they have ever supplied to any markets */ mapping(address => bool) public suppliers; /// @notice All cTokens addresses mapped by their underlying token addresses mapping(address => ICErc20) public cTokensByUnderlying; /// @notice Whether or not the supplier whitelist is enforced bool public enforceWhitelist; /// @notice Maps addresses to booleans indicating if they are allowed to supply assets (i.e., mint cTokens) mapping(address => bool) public whitelist; /// @notice An array of all whitelisted accounts address[] public whitelistArray; // Indexes of account addresses in the `whitelistArray` array mapping(address => uint256) internal whitelistIndexes; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint256) public borrowCaps; /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying. mapping(address => uint256) public supplyCaps; /// @notice RewardsDistributor contracts to notify of flywheel changes. address[] public rewardsDistributors; /// @dev Guard variable for pool-wide/cross-asset re-entrancy checks bool internal _notEntered; /// @dev Whether or not _notEntered has been initialized bool internal _notEnteredInitialized; /// @notice RewardsDistributor to list for claiming, but not to notify of flywheel changes. address[] public nonAccruingRewardsDistributors; /// @dev cap for each user's borrows against specific assets - denominated in the borrowed asset mapping(address => mapping(address => uint256)) public borrowCapForCollateral; /// @dev blacklist to disallow the borrowing of an asset against specific collateral mapping(address => mapping(address => bool)) public borrowingAgainstCollateralBlacklist; /// @dev set of whitelisted accounts that are allowed to bypass the borrowing against specific collateral cap mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowCapForCollateralWhitelist; /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowingAgainstCollateralBlacklistWhitelist; /// @dev set of whitelisted accounts that are allowed to bypass the supply cap mapping(address => EnumerableSet.AddressSet) internal supplyCapWhitelist; /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap mapping(address => EnumerableSet.AddressSet) internal borrowCapWhitelist; }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return uint256 The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance uint256 The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success bool Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success bool Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success bool Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining uint256 The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY, SUPPLIER_NOT_WHITELISTED, BORROW_BELOW_MIN, SUPPLY_ABOVE_MAX, NONZERO_TOTAL_SUPPLY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, TOGGLE_ADMIN_RIGHTS_OWNER_CHECK, TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SET_WHITELIST_ENFORCEMENT_OWNER_CHECK, SET_WHITELIST_STATUS_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK, UNSUPPORT_MARKET_OWNER_CHECK, UNSUPPORT_MARKET_DOES_NOT_EXIST, UNSUPPORT_MARKET_IN_USE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return uint256(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED, UTILIZATION_ABOVE_MAX } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_IONIC_FEES_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, NEW_UTILIZATION_RATE_ABOVE_MAX, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, WITHDRAW_IONIC_FEES_ACCRUE_INTEREST_FAILED, WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE, WITHDRAW_IONIC_FEES_FRESH_CHECK, WITHDRAW_IONIC_FEES_VALIDATION, WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED, WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE, WITHDRAW_ADMIN_FEES_FRESH_CHECK, WITHDRAW_ADMIN_FEES_VALIDATION, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, TOGGLE_ADMIN_RIGHTS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED, SET_ADMIN_FEE_ADMIN_CHECK, SET_ADMIN_FEE_FRESH_CHECK, SET_ADMIN_FEE_BOUNDS_CHECK, SET_IONIC_FEE_ACCRUE_INTEREST_FAILED, SET_IONIC_FEE_FRESH_CHECK, SET_IONIC_FEE_BOUNDS_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint256 error, uint256 info, uint256 detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque( Error err, FailureInfo info, uint256 opaqueError ) internal returns (uint256) { emit Failure(uint256(err), uint256(info), opaqueError); return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint256(err); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: rational })); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({ mantissa: result })); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: scaledMantissa })); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return (MathError.NO_ERROR, Exp({ mantissa: descaledMantissa })); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint256 numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({ mantissa: 0 })); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({ mantissa: 0 })); } (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({ mantissa: product })); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) { return mulExp(Exp({ mantissa: a }), Exp({ mantissa: b })); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({ mantissa: add_(a.mantissa, b.mantissa) }); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({ mantissa: add_(a.mantissa, b.mantissa) }); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({ mantissa: sub_(a.mantissa, b.mantissa) }); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({ mantissa: sub_(a.mantissa, b.mantissa) }); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({ mantissa: mul_(a.mantissa, b.mantissa) / expScale }); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({ mantissa: mul_(a.mantissa, b) }); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({ mantissa: mul_(a.mantissa, b.mantissa) / doubleScale }); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({ mantissa: mul_(a.mantissa, b) }); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({ mantissa: div_(mul_(a.mantissa, expScale), b.mantissa) }); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({ mantissa: div_(a.mantissa, b) }); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({ mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa) }); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({ mantissa: div_(a.mantissa, b) }); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({ mantissa: div_(mul_(a, doubleScale), b) }); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "../ionic/AuthoritiesRegistry.sol"; interface IFeeDistributor { function minBorrowEth() external view returns (uint256); function maxUtilizationRate() external view returns (uint256); function interestFeeRate() external view returns (uint256); function latestComptrollerImplementation(address oldImplementation) external view returns (address); function latestCErc20Delegate(uint8 delegateType) external view returns (address cErc20Delegate, bytes memory becomeImplementationData); function latestPluginImplementation(address oldImplementation) external view returns (address); function getComptrollerExtensions(address comptroller) external view returns (address[] memory); function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (address[] memory); function deployCErc20( uint8 delegateType, bytes calldata constructorData, bytes calldata becomeImplData ) external returns (address); function canCall( address pool, address user, address target, bytes4 functionSig ) external view returns (bool); function authoritiesRegistry() external view returns (AuthoritiesRegistry); fallback() external payable; receive() external payable; }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /** * @title Compound's InterestRateModel Interface * @author Compound */ abstract contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) public view virtual returns (uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) public view virtual returns (uint256); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; import "./Comptroller.sol"; import { DiamondExtension, DiamondBase, LibDiamond } from "../ionic/DiamondExtension.sol"; /** * @title Unitroller * @dev Storage for the comptroller is at this address, while execution is delegated via the Diamond Extensions * CTokens should reference this contract as their comptroller. */ contract Unitroller is ComptrollerV3Storage, ComptrollerErrorReporter, DiamondBase { /** * @notice Event emitted when the admin rights are changed */ event AdminRightsToggled(bool hasRights); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor(address payable _ionicAdmin) { admin = msg.sender; ionicAdmin = _ionicAdmin; } /*** Admin Functions ***/ /** * @notice Toggles admin rights. * @param hasRights Boolean indicating if the admin is to have rights. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _toggleAdminRights(bool hasRights) external returns (uint256) { if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.TOGGLE_ADMIN_RIGHTS_OWNER_CHECK); } // Check that rights have not already been set to the desired value if (adminHasRights == hasRights) return uint256(Error.NO_ERROR); adminHasRights = hasRights; emit AdminRightsToggled(hasRights); return uint256(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint256) { if (!hasAdminRights()) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; admin = pendingAdmin; pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } function comptrollerImplementation() public view returns (address) { return LibDiamond.getExtensionForFunction(bytes4(keccak256(bytes("_deployMarket(uint8,bytes,bytes,uint256)")))); } /** * @dev upgrades the implementation if necessary */ function _upgrade() external { require(msg.sender == address(this) || hasAdminRights(), "!self || !admin"); address currentImplementation = comptrollerImplementation(); address latestComptrollerImplementation = IFeeDistributor(ionicAdmin).latestComptrollerImplementation( currentImplementation ); _updateExtensions(latestComptrollerImplementation); if (currentImplementation != latestComptrollerImplementation) { // reinitialize _functionCall(address(this), abi.encodeWithSignature("_becomeImplementation()"), "!become impl"); } } function _functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.call(data); if (!success) { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } return returndata; } function _updateExtensions(address currentComptroller) internal { address[] memory latestExtensions = IFeeDistributor(ionicAdmin).getComptrollerExtensions(currentComptroller); address[] memory currentExtensions = LibDiamond.listExtensions(); // removed the current (old) extensions for (uint256 i = 0; i < currentExtensions.length; i++) { LibDiamond.removeExtension(DiamondExtension(currentExtensions[i])); } // add the new extensions for (uint256 i = 0; i < latestExtensions.length; i++) { LibDiamond.addExtension(DiamondExtension(latestExtensions[i])); } } /** * @dev register a logic extension * @param extensionToAdd the extension whose functions are to be added * @param extensionToReplace the extension whose functions are to be removed/replaced */ function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external override { require(hasAdminRights(), "!unauthorized"); LibDiamond.registerExtension(extensionToAdd, extensionToReplace); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#flash /// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface interface IUniswapV3FlashCallback { /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash. /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// @param fee0 The fee amount in token0 due to the pool by the end of the flash /// @param fee1 The fee amount in token1 due to the pool by the end of the flash /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call function uniswapV3FlashCallback( uint256 fee0, uint256 fee1, bytes calldata data ) external; }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.8.0; import "./IUniswapV3PoolActions.sol"; interface IUniswapV3Pool is IUniswapV3PoolActions { function token0() external view returns (address); function token1() external view returns (address); function fee() external view returns (uint24); function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); function liquidity() external view returns (uint128); function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives); function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 liquidityCumulative, bool initialized ); function tickBitmap(int16 wordPosition) external view returns (uint256); function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IUniswapV3Quoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import { SafeOwnableUpgradeable } from "../ionic/SafeOwnableUpgradeable.sol"; /** * @title AddressesProvider * @notice The Addresses Provider serves as a central storage of system internal and external * contract addresses that change between deploys and across chains * @author Veliko Minkov <[email protected]> */ contract AddressesProvider is SafeOwnableUpgradeable { mapping(string => address) private _addresses; mapping(address => Contract) public plugins; mapping(address => Contract) public flywheelRewards; mapping(address => RedemptionStrategy) public redemptionStrategiesConfig; mapping(address => FundingStrategy) public fundingStrategiesConfig; JarvisPool[] public jarvisPoolsConfig; CurveSwapPool[] public curveSwapPoolsConfig; mapping(address => mapping(address => address)) public balancerPoolForTokens; /// @dev Initializer to set the admin that can set and change contracts addresses function initialize(address owner) public initializer { __SafeOwnable_init(owner); } /** * @dev The contract address and a string that uniquely identifies the contract's interface */ struct Contract { address addr; string contractInterface; } struct RedemptionStrategy { address addr; string contractInterface; address outputToken; } struct FundingStrategy { address addr; string contractInterface; address inputToken; } struct JarvisPool { address syntheticToken; address collateralToken; address liquidityPool; uint256 expirationTime; } struct CurveSwapPool { address poolAddress; address[] coins; } /** * @dev sets the address and contract interface ID of the flywheel for the reward token * @param rewardToken the reward token address * @param flywheelRewardsModule the flywheel rewards module address * @param contractInterface a string that uniquely identifies the contract's interface */ function setFlywheelRewards( address rewardToken, address flywheelRewardsModule, string calldata contractInterface ) public onlyOwner { flywheelRewards[rewardToken] = Contract(flywheelRewardsModule, contractInterface); } /** * @dev sets the address and contract interface ID of the ERC4626 plugin for the asset * @param asset the asset address * @param plugin the ERC4626 plugin address * @param contractInterface a string that uniquely identifies the contract's interface */ function setPlugin( address asset, address plugin, string calldata contractInterface ) public onlyOwner { plugins[asset] = Contract(plugin, contractInterface); } /** * @dev sets the address and contract interface ID of the redemption strategy for the asset * @param asset the asset address * @param strategy redemption strategy address * @param contractInterface a string that uniquely identifies the contract's interface */ function setRedemptionStrategy( address asset, address strategy, string calldata contractInterface, address outputToken ) public onlyOwner { redemptionStrategiesConfig[asset] = RedemptionStrategy(strategy, contractInterface, outputToken); } function getRedemptionStrategy(address asset) public view returns (RedemptionStrategy memory) { return redemptionStrategiesConfig[asset]; } /** * @dev sets the address and contract interface ID of the funding strategy for the asset * @param asset the asset address * @param strategy funding strategy address * @param contractInterface a string that uniquely identifies the contract's interface */ function setFundingStrategy( address asset, address strategy, string calldata contractInterface, address inputToken ) public onlyOwner { fundingStrategiesConfig[asset] = FundingStrategy(strategy, contractInterface, inputToken); } function getFundingStrategy(address asset) public view returns (FundingStrategy memory) { return fundingStrategiesConfig[asset]; } /** * @dev configures the Jarvis pool of a Jarvis synthetic token * @param syntheticToken the synthetic token address * @param collateralToken the collateral token address * @param liquidityPool the liquidity pool address * @param expirationTime the operation expiration time */ function setJarvisPool( address syntheticToken, address collateralToken, address liquidityPool, uint256 expirationTime ) public onlyOwner { jarvisPoolsConfig.push(JarvisPool(syntheticToken, collateralToken, liquidityPool, expirationTime)); } function setCurveSwapPool(address poolAddress, address[] calldata coins) public onlyOwner { curveSwapPoolsConfig.push(CurveSwapPool(poolAddress, coins)); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * @param id The id * @param newAddress The address to set */ function setAddress(string calldata id, address newAddress) external onlyOwner { _addresses[id] = newAddress; } /** * @dev Returns an address by id * @return The address */ function getAddress(string calldata id) public view returns (address) { return _addresses[id]; } function getCurveSwapPools() public view returns (CurveSwapPool[] memory) { return curveSwapPoolsConfig; } function getJarvisPools() public view returns (JarvisPool[] memory) { return jarvisPoolsConfig; } function setBalancerPoolForTokens( address inputToken, address outputToken, address pool ) external onlyOwner { balancerPoolForTokens[inputToken][outputToken] = pool; } function getBalancerPoolForTokens(address inputToken, address outputToken) external view returns (address) { return balancerPoolForTokens[inputToken][outputToken]; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { PoolRolesAuthority } from "../ionic/PoolRolesAuthority.sol"; import { SafeOwnableUpgradeable } from "../ionic/SafeOwnableUpgradeable.sol"; import { IonicComptroller } from "../compound/ComptrollerInterface.sol"; import { TransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; contract AuthoritiesRegistry is SafeOwnableUpgradeable { mapping(address => PoolRolesAuthority) public poolsAuthorities; PoolRolesAuthority public poolAuthLogic; address public leveredPositionsFactory; bool public noAuthRequired; function initialize(address _leveredPositionsFactory) public initializer { __SafeOwnable_init(msg.sender); leveredPositionsFactory = _leveredPositionsFactory; poolAuthLogic = new PoolRolesAuthority(); } function reinitialize(address _leveredPositionsFactory) public onlyOwnerOrAdmin { leveredPositionsFactory = _leveredPositionsFactory; poolAuthLogic = new PoolRolesAuthority(); // for Neon the auth is not required noAuthRequired = block.chainid == 245022934; } function createPoolAuthority(address pool) public onlyOwner returns (PoolRolesAuthority auth) { require(address(poolsAuthorities[pool]) == address(0), "already created"); TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(poolAuthLogic), _getProxyAdmin(), ""); auth = PoolRolesAuthority(address(proxy)); auth.initialize(address(this)); poolsAuthorities[pool] = auth; auth.openPoolSupplierCapabilities(IonicComptroller(pool)); auth.setUserRole(address(this), auth.REGISTRY_ROLE(), true); // sets the registry owner as the auth owner reconfigureAuthority(pool); } function reconfigureAuthority(address poolAddress) public { IonicComptroller pool = IonicComptroller(poolAddress); PoolRolesAuthority auth = poolsAuthorities[address(pool)]; if (msg.sender != poolAddress || address(auth) != address(0)) { require(address(auth) != address(0), "no such authority"); require(msg.sender == owner() || msg.sender == poolAddress, "not owner or pool"); auth.configureRegistryCapabilities(); auth.configurePoolSupplierCapabilities(pool); auth.configurePoolBorrowerCapabilities(pool); // everyone can be a liquidator auth.configureOpenPoolLiquidatorCapabilities(pool); auth.configureLeveredPositionCapabilities(pool); if (auth.owner() != owner()) { auth.setOwner(owner()); } } } function canCall( address pool, address user, address target, bytes4 functionSig ) external view returns (bool) { PoolRolesAuthority authorityForPool = poolsAuthorities[pool]; if (address(authorityForPool) == address(0)) { return noAuthRequired; } else { // allow only if an auth exists and it allows the action return authorityForPool.canCall(user, target, functionSig); } } function setUserRole( address pool, address user, uint8 role, bool enabled ) external { PoolRolesAuthority poolAuth = poolsAuthorities[pool]; require(address(poolAuth) != address(0), "auth does not exist"); require(msg.sender == owner() || msg.sender == leveredPositionsFactory, "not owner or factory"); require(msg.sender != leveredPositionsFactory || role == poolAuth.LEVERED_POSITION_ROLE(), "only lev pos role"); poolAuth.setUserRole(user, role, enabled); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; /** * @notice a base contract for logic extensions that use the diamond pattern storage * to map the functions when looking up the extension contract to delegate to. */ abstract contract DiamondExtension { /** * @return a list of all the function selectors that this logic extension exposes */ function _getExtensionFunctions() external pure virtual returns (bytes4[] memory); } // When no function exists for function called error FunctionNotFound(bytes4 _functionSelector); // When no extension exists for function called error ExtensionNotFound(bytes4 _functionSelector); // When the function is already added error FunctionAlreadyAdded(bytes4 _functionSelector, address _currentImpl); abstract contract DiamondBase { /** * @dev register a logic extension * @param extensionToAdd the extension whose functions are to be added * @param extensionToReplace the extension whose functions are to be removed/replaced */ function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external virtual; function _listExtensions() public view returns (address[] memory) { return LibDiamond.listExtensions(); } fallback() external { address extension = LibDiamond.getExtensionForFunction(msg.sig); if (extension == address(0)) revert FunctionNotFound(msg.sig); // Execute external function from extension using delegatecall and return any value. assembly { // copy function selector and any arguments calldatacopy(0, 0, calldatasize()) // execute function call using the extension let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } /** * @notice a library to use in a contract, whose logic is extended with diamond extension */ library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.extensions.diamond.storage"); struct Function { address extension; bytes4 selector; } struct LogicStorage { Function[] functions; address[] extensions; } function getExtensionForFunction(bytes4 msgSig) internal view returns (address) { return getExtensionForSelector(msgSig, diamondStorage()); } function diamondStorage() internal pure returns (LogicStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } function listExtensions() internal view returns (address[] memory) { return diamondStorage().extensions; } function registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) internal { if (address(extensionToReplace) != address(0)) { removeExtension(extensionToReplace); } addExtension(extensionToAdd); } function removeExtension(DiamondExtension extension) internal { LogicStorage storage ds = diamondStorage(); // remove all functions of the extension to replace removeExtensionFunctions(extension); for (uint8 i = 0; i < ds.extensions.length; i++) { if (ds.extensions[i] == address(extension)) { ds.extensions[i] = ds.extensions[ds.extensions.length - 1]; ds.extensions.pop(); } } } function addExtension(DiamondExtension extension) internal { LogicStorage storage ds = diamondStorage(); for (uint8 i = 0; i < ds.extensions.length; i++) { require(ds.extensions[i] != address(extension), "extension already added"); } addExtensionFunctions(extension); ds.extensions.push(address(extension)); } function removeExtensionFunctions(DiamondExtension extension) internal { bytes4[] memory fnsToRemove = extension._getExtensionFunctions(); LogicStorage storage ds = diamondStorage(); for (uint16 i = 0; i < fnsToRemove.length; i++) { bytes4 selectorToRemove = fnsToRemove[i]; // must never fail assert(address(extension) == getExtensionForSelector(selectorToRemove, ds)); // swap with the last element in the selectorAtIndex array and remove the last element uint16 indexToKeep = getIndexForSelector(selectorToRemove, ds); ds.functions[indexToKeep] = ds.functions[ds.functions.length - 1]; ds.functions.pop(); } } function addExtensionFunctions(DiamondExtension extension) internal { bytes4[] memory fnsToAdd = extension._getExtensionFunctions(); LogicStorage storage ds = diamondStorage(); uint16 functionsCount = uint16(ds.functions.length); for (uint256 functionsIndex = 0; functionsIndex < fnsToAdd.length; functionsIndex++) { bytes4 selector = fnsToAdd[functionsIndex]; address oldImplementation = getExtensionForSelector(selector, ds); if (oldImplementation != address(0)) revert FunctionAlreadyAdded(selector, oldImplementation); ds.functions.push(Function(address(extension), selector)); functionsCount++; } } function getExtensionForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (address) { uint256 fnsLen = ds.functions.length; for (uint256 i = 0; i < fnsLen; i++) { if (ds.functions[i].selector == selector) return ds.functions[i].extension; } return address(0); } function getIndexForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (uint16) { uint16 fnsLen = uint16(ds.functions.length); for (uint16 i = 0; i < fnsLen; i++) { if (ds.functions[i].selector == selector) return i; } return type(uint16).max; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { IonicComptroller, ComptrollerInterface } from "../compound/ComptrollerInterface.sol"; import { ICErc20, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface } from "../compound/CTokenInterfaces.sol"; import { RolesAuthority, Authority } from "solmate/auth/authorities/RolesAuthority.sol"; import "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; contract PoolRolesAuthority is RolesAuthority, Initializable { constructor() RolesAuthority(address(0), Authority(address(0))) { _disableInitializers(); } function initialize(address _owner) public initializer { owner = _owner; authority = this; } // up to 256 roles uint8 public constant REGISTRY_ROLE = 0; uint8 public constant SUPPLIER_ROLE = 1; uint8 public constant BORROWER_ROLE = 2; uint8 public constant LIQUIDATOR_ROLE = 3; uint8 public constant LEVERED_POSITION_ROLE = 4; function configureRegistryCapabilities() external requiresAuth { setRoleCapability(REGISTRY_ROLE, address(this), PoolRolesAuthority.configureRegistryCapabilities.selector, true); setRoleCapability( REGISTRY_ROLE, address(this), PoolRolesAuthority.configurePoolSupplierCapabilities.selector, true ); setRoleCapability( REGISTRY_ROLE, address(this), PoolRolesAuthority.configurePoolBorrowerCapabilities.selector, true ); setRoleCapability( REGISTRY_ROLE, address(this), PoolRolesAuthority.configureClosedPoolLiquidatorCapabilities.selector, true ); setRoleCapability( REGISTRY_ROLE, address(this), PoolRolesAuthority.configureOpenPoolLiquidatorCapabilities.selector, true ); setRoleCapability( REGISTRY_ROLE, address(this), PoolRolesAuthority.configureLeveredPositionCapabilities.selector, true ); setRoleCapability(REGISTRY_ROLE, address(this), RolesAuthority.setUserRole.selector, true); } function openPoolSupplierCapabilities(IonicComptroller pool) external requiresAuth { _setPublicPoolSupplierCapabilities(pool, true); } function closePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth { _setPublicPoolSupplierCapabilities(pool, false); } function _setPublicPoolSupplierCapabilities(IonicComptroller pool, bool setPublic) internal { setPublicCapability(address(pool), pool.enterMarkets.selector, setPublic); setPublicCapability(address(pool), pool.exitMarket.selector, setPublic); ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { bytes4[] memory selectors = getSupplierMarketSelectors(); for (uint256 j = 0; j < selectors.length; j++) { setPublicCapability(address(allMarkets[i]), selectors[j], setPublic); } } } function configurePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth { _configurePoolSupplierCapabilities(pool, SUPPLIER_ROLE); } function getSupplierMarketSelectors() internal pure returns (bytes4[] memory selectors) { uint8 fnsCount = 6; selectors = new bytes4[](fnsCount); selectors[--fnsCount] = CTokenSecondExtensionInterface.mint.selector; selectors[--fnsCount] = CTokenSecondExtensionInterface.redeem.selector; selectors[--fnsCount] = CTokenSecondExtensionInterface.redeemUnderlying.selector; selectors[--fnsCount] = CTokenFirstExtensionInterface.transfer.selector; selectors[--fnsCount] = CTokenFirstExtensionInterface.transferFrom.selector; selectors[--fnsCount] = CTokenFirstExtensionInterface.approve.selector; require(fnsCount == 0, "use the correct array length"); return selectors; } function _configurePoolSupplierCapabilities(IonicComptroller pool, uint8 role) internal { setRoleCapability(role, address(pool), pool.enterMarkets.selector, true); setRoleCapability(role, address(pool), pool.exitMarket.selector, true); ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { bytes4[] memory selectors = getSupplierMarketSelectors(); for (uint256 j = 0; j < selectors.length; j++) { setRoleCapability(role, address(allMarkets[i]), selectors[j], true); } } } function openPoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth { _setPublicPoolBorrowerCapabilities(pool, true); } function closePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth { _setPublicPoolBorrowerCapabilities(pool, false); } function _setPublicPoolBorrowerCapabilities(IonicComptroller pool, bool setPublic) internal { ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { setPublicCapability(address(allMarkets[i]), allMarkets[i].borrow.selector, setPublic); setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrow.selector, setPublic); setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, setPublic); setPublicCapability(address(allMarkets[i]), allMarkets[i].flash.selector, setPublic); } } function configurePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth { // borrowers have the SUPPLIER_ROLE capabilities by default _configurePoolSupplierCapabilities(pool, BORROWER_ROLE); ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true); setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true); setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, true); setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true); } } function configureClosedPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth { ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, false); setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true); setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true); } } function configureOpenPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth { ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true); // TODO this leaves redeeming open for everyone setPublicCapability(address(allMarkets[i]), allMarkets[i].redeem.selector, true); } } function configureLeveredPositionCapabilities(IonicComptroller pool) external requiresAuth { setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.enterMarkets.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.exitMarket.selector, true); ICErc20[] memory allMarkets = pool.getAllMarkets(); for (uint256 i = 0; i < allMarkets.length; i++) { setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].mint.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeemUnderlying.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true); setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true); } } }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol"; /** * @dev Ownable extension that requires a two-step process of setting the pending owner and the owner accepting it. * @notice Existing OwnableUpgradeable contracts cannot be upgraded due to the extra storage variable * that will shift the other. */ abstract contract SafeOwnableUpgradeable is OwnableUpgradeable { /** * @notice Pending owner of this contract */ address public pendingOwner; function __SafeOwnable_init(address owner_) internal onlyInitializing { __Ownable_init(); _transferOwnership(owner_); } struct AddressSlot { address value; } modifier onlyOwnerOrAdmin() { bool isOwner = owner() == _msgSender(); if (!isOwner) { address admin = _getProxyAdmin(); bool isAdmin = admin == _msgSender(); require(isAdmin, "Ownable: caller is neither the owner nor the admin"); } _; } /** * @notice Emitted when pendingOwner is changed */ event NewPendingOwner(address oldPendingOwner, address newPendingOwner); /** * @notice Emitted when pendingOwner is accepted, which means owner is updated */ event NewOwner(address oldOwner, address newOwner); /** * @notice Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer. * @dev Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address newPendingOwner) public onlyOwner { // Save current value, if any, for inclusion in log address oldPendingOwner = pendingOwner; // Store pendingOwner with value newPendingOwner pendingOwner = newPendingOwner; // Emit NewPendingOwner(oldPendingOwner, newPendingOwner) emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @notice Accepts transfer of owner rights. msg.sender must be pendingOwner * @dev Owner function for pending owner to accept role and update owner */ function _acceptOwner() public { // Check caller is pendingOwner and pendingOwner ≠ address(0) require(msg.sender == pendingOwner, "not the pending owner"); // Save current values for inclusion in log address oldOwner = owner(); address oldPendingOwner = pendingOwner; // Store owner with value pendingOwner _transferOwnership(pendingOwner); // Clear the pending value pendingOwner = address(0); emit NewOwner(oldOwner, pendingOwner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } function renounceOwnership() public override onlyOwner { // do not remove this overriding fn revert("not used anymore"); } function transferOwnership(address newOwner) public override onlyOwner { emit NewPendingOwner(pendingOwner, newOwner); pendingOwner = newOwner; } function _getProxyAdmin() internal view returns (address admin) { bytes32 _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; AddressSlot storage adminSlot; assembly { adminSlot.slot := _ADMIN_SLOT } admin = adminSlot.value; } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.10; import { ERC20 } from "solmate/tokens/ERC20.sol"; interface IIonicFlywheel { function isRewardsDistributor() external returns (bool); function isFlywheel() external returns (bool); function flywheelPreSupplierAction(address market, address supplier) external; function flywheelPreBorrowerAction(address market, address borrower) external; function flywheelPreTransferAction(address market, address src, address dst) external; function compAccrued(address user) external view returns (uint256); function addMarketForRewards(ERC20 strategy) external; function marketState(ERC20 strategy) external view returns (uint224 index, uint32 lastUpdatedTimestamp); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "./IRedemptionStrategy.sol"; import "openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol"; interface IFundsConversionStrategy is IRedemptionStrategy { function convert( IERC20Upgradeable inputToken, uint256 inputAmount, bytes memory strategyData ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount); function estimateInputAmount(uint256 outputAmount, bytes memory strategyData) external view returns (IERC20Upgradeable inputToken, uint256 inputAmount); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol"; /** * @title IRedemptionStrategy * @notice Redeems seized wrapped token collateral for an underlying token for use as a step in a liquidation. * @author David Lucid <[email protected]> (https://github.com/davidlucid) */ interface IRedemptionStrategy { /** * @notice Redeems custom collateral `token` for an underlying token. * @param inputToken The input wrapped token to be redeemed for an underlying token. * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token. * @param strategyData The ABI-encoded data to be used in the redemption strategy logic. * @return outputToken The underlying ERC20 token outputted. * @return outputAmount The quantity of underlying tokens outputted. */ function redeem( IERC20Upgradeable inputToken, uint256 inputAmount, bytes memory strategyData ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount); function name() external view returns (string memory); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "../compound/CTokenInterfaces.sol"; /** * @title BasePriceOracle * @notice Returns prices of underlying tokens directly without the caller having to specify a cToken address. * @dev Implements the `PriceOracle` interface. * @author David Lucid <[email protected]> (https://github.com/davidlucid) */ interface BasePriceOracle { /** * @notice Get the price of an underlying asset. * @param underlying The underlying asset to get the price of. * @return The underlying asset price in ETH as a mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function price(address underlying) external view returns (uint256); /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(ICErc20 cToken) external view returns (uint256); }
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol"; import { ICErc20 } from "../compound/CTokenInterfaces.sol"; import { BasePriceOracle } from "./BasePriceOracle.sol"; /** * @title MasterPriceOracle * @notice Use a combination of price oracles. * @dev Implements `PriceOracle`. * @author David Lucid <[email protected]> (https://github.com/davidlucid) */ contract MasterPriceOracle is Initializable, BasePriceOracle { /** * @dev Maps underlying token addresses to `PriceOracle` contracts (can be `BasePriceOracle` contracts too). */ mapping(address => BasePriceOracle) public oracles; /** * @dev Default/fallback `PriceOracle`. */ BasePriceOracle public defaultOracle; /** * @dev The administrator of this `MasterPriceOracle`. */ address public admin; /** * @dev Controls if `admin` can overwrite existing assignments of oracles to underlying tokens. */ bool internal noAdminOverwrite; /** * @dev The Wrapped native asset address. */ address public wtoken; /** * @dev Maps underlying token addresses to `PriceOracle` contracts (can be `BasePriceOracle` contracts too). */ mapping(address => BasePriceOracle) public fallbackOracles; /** * @dev Returns a boolean indicating if `admin` can overwrite existing assignments of oracles to underlying tokens. */ function canAdminOverwrite() external view returns (bool) { return !noAdminOverwrite; } /** * @dev Event emitted when `admin` is changed. */ event NewAdmin(address oldAdmin, address newAdmin); /** * @dev Event emitted when the default oracle is changed. */ event NewDefaultOracle(address oldOracle, address newOracle); /** * @dev Event emitted when an underlying token's oracle is changed. */ event NewOracle(address underlying, address oldOracle, address newOracle); /** * @dev Initialize state variables. * @param underlyings The underlying ERC20 token addresses to link to `_oracles`. * @param _oracles The `PriceOracle` contracts to be assigned to `underlyings`. * @param _defaultOracle The default `PriceOracle` contract to use. * @param _admin The admin who can assign oracles to underlying tokens. * @param _canAdminOverwrite Controls if `admin` can overwrite existing assignments of oracles to underlying tokens. * @param _wtoken The Wrapped native asset address */ function initialize( address[] memory underlyings, BasePriceOracle[] memory _oracles, BasePriceOracle _defaultOracle, address _admin, bool _canAdminOverwrite, address _wtoken ) external initializer { // Input validation require(underlyings.length == _oracles.length, "Lengths of both arrays must be equal."); // Initialize state variables for (uint256 i = 0; i < underlyings.length; i++) { address underlying = underlyings[i]; BasePriceOracle newOracle = _oracles[i]; oracles[underlying] = newOracle; emit NewOracle(underlying, address(0), address(newOracle)); } defaultOracle = _defaultOracle; admin = _admin; noAdminOverwrite = !_canAdminOverwrite; wtoken = _wtoken; } /** * @dev Sets `_oracles` for `underlyings`. */ function add(address[] calldata underlyings, BasePriceOracle[] calldata _oracles) external onlyAdmin { // Input validation require( underlyings.length > 0 && underlyings.length == _oracles.length, "Lengths of both arrays must be equal and greater than 0." ); // Assign oracles to underlying tokens for (uint256 i = 0; i < underlyings.length; i++) { address underlying = underlyings[i]; address oldOracle = address(oracles[underlying]); if (noAdminOverwrite) require( oldOracle == address(0), "Admin cannot overwrite existing assignments of oracles to underlying tokens." ); BasePriceOracle newOracle = _oracles[i]; oracles[underlying] = newOracle; emit NewOracle(underlying, oldOracle, address(newOracle)); } } /** * @dev Sets `_oracles` for `underlyings`. */ function addFallbacks(address[] calldata underlyings, BasePriceOracle[] calldata _oracles) external onlyAdmin { // Input validation require( underlyings.length > 0 && underlyings.length == _oracles.length, "Lengths of both arrays must be equal and greater than 0." ); // Assign oracles to underlying tokens for (uint256 i = 0; i < underlyings.length; i++) { address underlying = underlyings[i]; address oldOracle = address(fallbackOracles[underlying]); if (noAdminOverwrite) require( oldOracle == address(0), "Admin cannot overwrite existing assignments of oracles to underlying tokens." ); BasePriceOracle newOracle = _oracles[i]; fallbackOracles[underlying] = newOracle; emit NewOracle(underlying, oldOracle, address(newOracle)); } } /** * @dev Changes the default price oracle */ function setDefaultOracle(BasePriceOracle newOracle) external onlyAdmin { BasePriceOracle oldOracle = defaultOracle; defaultOracle = newOracle; emit NewDefaultOracle(address(oldOracle), address(newOracle)); } /** * @dev Changes the admin and emits an event. */ function changeAdmin(address newAdmin) external onlyAdmin { address oldAdmin = admin; admin = newAdmin; emit NewAdmin(oldAdmin, newAdmin); } /** * @dev Modifier that checks if `msg.sender == admin`. */ modifier onlyAdmin() { require(msg.sender == admin, "Sender is not the admin."); _; } /** * @notice Returns the price in ETH of the token underlying `cToken`. * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2). * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`. */ function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) { // Get underlying ERC20 token address address underlying = address(ICErc20(address(cToken)).underlying()); if (underlying == wtoken) return 1e18; BasePriceOracle oracle = oracles[underlying]; BasePriceOracle fallbackOracle = fallbackOracles[underlying]; if (address(oracle) != address(0)) { try oracle.getUnderlyingPrice(cToken) returns (uint256 underlyingPrice) { if (underlyingPrice == 0) { if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken); } else { return underlyingPrice; } } catch { if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken); } } else { if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken); } revert("Price oracle not found for this underlying token address."); } /** * @dev Attempts to return the price in ETH of `underlying` (implements `BasePriceOracle`). */ function price(address underlying) public view override returns (uint256) { // Return 1e18 for WETH if (underlying == wtoken) return 1e18; // Get underlying price from assigned oracle BasePriceOracle oracle = oracles[underlying]; BasePriceOracle fallbackOracle = fallbackOracles[underlying]; if (address(oracle) != address(0)) { try oracle.price(underlying) returns (uint256 underlyingPrice) { if (underlyingPrice == 0) { if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying); } else { return underlyingPrice; } } catch { if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying); } } else { if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying); } revert("Price oracle not found for this underlying token address."); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Internal function that returns the initialized version. Returns `_initialized` */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Internal function that returns the initialized version. Returns `_initializing` */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../extensions/draft-IERC20PermitUpgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20PermitUpgradeable token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Create2.sol) pragma solidity ^0.8.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2Upgradeable { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy( uint256 amount, bytes32 salt, bytes memory bytecode ) internal returns (address addr) { require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); /// @solidity memory-safe-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress( bytes32 salt, bytes32 bytecodeHash, address deployer ) internal pure returns (address addr) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) // Get free memory pointer // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... | // |-------------------|---------------------------------------------------------------------------| // | bytecodeHash | CCCCCCCCCCCCC...CC | // | salt | BBBBBBBBBBBBB...BB | // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA | // | 0xFF | FF | // |-------------------|---------------------------------------------------------------------------| // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC | // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ | mstore(add(ptr, 0x40), bytecodeHash) mstore(add(ptr, 0x20), salt) mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff mstore8(start, 0xff) addr := keccak256(start, 85) } } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) abstract contract Auth { event OwnerUpdated(address indexed user, address indexed newOwner); event AuthorityUpdated(address indexed user, Authority indexed newAuthority); address public owner; Authority public authority; constructor(address _owner, Authority _authority) { owner = _owner; authority = _authority; emit OwnerUpdated(msg.sender, _owner); emit AuthorityUpdated(msg.sender, _authority); } modifier requiresAuth() virtual { require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED"); _; } function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) { Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas. // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be // aware that this makes protected functions uncallable even to the owner if the authority is out of order. return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner; } function setAuthority(Authority newAuthority) public virtual { // We check if the caller is the owner first because we want to ensure they can // always swap out the authority even if it's reverting or using up a lot of gas. require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig)); authority = newAuthority; emit AuthorityUpdated(msg.sender, newAuthority); } function setOwner(address newOwner) public virtual requiresAuth { owner = newOwner; emit OwnerUpdated(msg.sender, newOwner); } } /// @notice A generic interface for a contract which provides authorization data to an Auth instance. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol) interface Authority { function canCall( address user, address target, bytes4 functionSig ) external view returns (bool); }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {Auth, Authority} from "../Auth.sol"; /// @notice Role based Authority that supports up to 256 roles. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/authorities/RolesAuthority.sol) /// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol) contract RolesAuthority is Auth, Authority { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled); event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled); event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled); /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(address _owner, Authority _authority) Auth(_owner, _authority) {} /*////////////////////////////////////////////////////////////// ROLE/USER STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => bytes32) public getUserRoles; mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic; mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability; function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) { return (uint256(getUserRoles[user]) >> role) & 1 != 0; } function doesRoleHaveCapability( uint8 role, address target, bytes4 functionSig ) public view virtual returns (bool) { return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0; } /*////////////////////////////////////////////////////////////// AUTHORIZATION LOGIC //////////////////////////////////////////////////////////////*/ function canCall( address user, address target, bytes4 functionSig ) public view virtual override returns (bool) { return isCapabilityPublic[target][functionSig] || bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig]; } /*////////////////////////////////////////////////////////////// ROLE CAPABILITY CONFIGURATION LOGIC //////////////////////////////////////////////////////////////*/ function setPublicCapability( address target, bytes4 functionSig, bool enabled ) public virtual requiresAuth { isCapabilityPublic[target][functionSig] = enabled; emit PublicCapabilityUpdated(target, functionSig, enabled); } function setRoleCapability( uint8 role, address target, bytes4 functionSig, bool enabled ) public virtual requiresAuth { if (enabled) { getRolesWithCapability[target][functionSig] |= bytes32(1 << role); } else { getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role); } emit RoleCapabilityUpdated(role, target, functionSig, enabled); } /*////////////////////////////////////////////////////////////// USER ROLE ASSIGNMENT LOGIC //////////////////////////////////////////////////////////////*/ function setUserRole( address user, uint8 role, bool enabled ) public virtual requiresAuth { if (enabled) { getUserRoles[user] |= bytes32(1 << role); } else { getUserRoles[user] &= ~bytes32(1 << role); } emit UserRoleUpdated(user, role, enabled); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ), v, r, s ); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
{ "evmVersion": "london", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"cashPrior","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"interestAccumulated","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"borrowIndex","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"AccrueInterest","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"borrowAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"accountBorrows","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"error","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"info","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"detail","type":"uint256"}],"name":"Failure","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"repayAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"cTokenCollateral","type":"address"},{"indexed":false,"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"LiquidateBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"minter","type":"address"},{"indexed":false,"internalType":"uint256","name":"mintAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"mintTokens","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldAdminFeeMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newAdminFeeMantissa","type":"uint256"}],"name":"NewAdminFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldIonicFeeMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newIonicFeeMantissa","type":"uint256"}],"name":"NewIonicFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract InterestRateModel","name":"oldInterestRateModel","type":"address"},{"indexed":false,"internalType":"contract InterestRateModel","name":"newInterestRateModel","type":"address"}],"name":"NewMarketInterestRateModel","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldReserveFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newReserveFactorMantissa","type":"uint256"}],"name":"NewReserveFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"redeemer","type":"address"},{"indexed":false,"internalType":"uint256","name":"redeemAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"address","name":"borrower","type":"address"},{"indexed":false,"internalType":"uint256","name":"repayAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"accountBorrows","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBorrows","type":"uint256"}],"name":"RepayBorrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"benefactor","type":"address"},{"indexed":false,"internalType":"uint256","name":"addAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"},{"indexed":false,"internalType":"uint256","name":"reduceAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesReduced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"bytes","name":"","type":"bytes"}],"name":"_becomeImplementation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"_getExtensionFunctions","outputs":[{"internalType":"bytes4[]","name":"functionSelectors","type":"bytes4[]"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"withdrawAmount","type":"uint256"}],"name":"_withdrawAdminFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"withdrawAmount","type":"uint256"}],"name":"_withdrawIonicFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accrualBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"adminFeeMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ap","outputs":[{"internalType":"contract AddressesProvider","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"comptroller","outputs":[{"internalType":"contract IonicComptroller","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractType","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"delegateType","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"feeSeizeShareMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCash","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"interestRateModel","outputs":[{"internalType":"contract InterestRateModel","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ionicAdmin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ionicFeeMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"address","name":"cTokenCollateral","type":"address"}],"name":"liquidateBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"mintAmount","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolSeizeShareMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"redeemAmount","type":"uint256"}],"name":"redeemUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrowBehalf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"reserveFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"selfTransferIn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"selfTransferOut","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAdminFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalBorrows","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalIonicFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b506146a3806100206000396000f3fe608060405234801561001057600080fd5b50600436106102275760003560e01c8063852a12e311610130578063b0d58e49116100b8578063c91a424f1161007c578063c91a424f1461043f578063cb2ef6f714610452578063db006a751461047c578063f3fdb15a1461048f578063f5e3c462146104a257600080fd5b8063b0d58e49146103ee578063b2a02ff114610401578063be99f11914610414578063c3bf11cd14610423578063c5ebeaec1461042c57600080fd5b806395d89b41116100ff57806395d89b41146103ae5780639826394b146103b6578063a0712d68146103bf578063a7b820df146103d2578063aa5af0fd146103e557600080fd5b8063852a12e31461037457806389f8132e146103875780638d02d9a11461039c5780638f840ddd146103a557600080fd5b80633b1d21a2116101b35780635fe3b567116101825780635fe3b5671461032957806361feacff146103415780636752e7021461034a5780636c540baf146103585780636f307dc31461036157600080fd5b80633b1d21a2146102da5780633c4f743c146102e257806347bd37181461030d57806356e677281461031657600080fd5b8063173b9904116101fa578063173b99041461029357806318160ddd1461029c5780632608f818146102a55780632c436e5b146102b8578063313ce567146102cd57600080fd5b8063067db1b31461022c57806306fdde03146102415780630e7527021461025f578063135f133414610280575b600080fd5b61023f61023a3660046141bf565b6104b5565b005b6102496104ff565b6040516102569190614217565b60405180910390f35b61027261026d36600461424a565b61058d565b604051908152602001610256565b61027261028e3660046141bf565b61064a565b61027260085481565b610272600f5481565b6102726102b33660046141bf565b610696565b60015b60405160ff9091168152602001610256565b6003546102bb9060ff1681565b610272610755565b6014546102f5906001600160a01b031681565b6040516001600160a01b039091168152602001610256565b610272600b5481565b61023f610324366004614279565b610764565b6003546102f59061010090046001600160a01b031681565b610272600d5481565b610272666379da05b6000081565b61027260095481565b6013546102f5906001600160a01b031681565b61027261038236600461424a565b6107b6565b61038f610869565b604051610256919061432a565b61027260065481565b610272600c5481565b610249610a71565b610272600e5481565b6102726103cd36600461424a565b610a7e565b6102726103e036600461424a565b610b33565b610272600a5481565b6102726103fc36600461424a565b610c91565b61027261040f366004614378565b610d84565b61027267016345785d8a000081565b61027260075481565b61027261043a36600461424a565b610da8565b6000546102f5906001600160a01b031681565b60408051808201909152600e81526d43457263323044656c656761746560901b6020820152610249565b61027261048a36600461424a565b610e5b565b6004546102f5906001600160a01b031681565b6102726104b03660046143b9565b610f0e565b3330146104f15760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b60448201526064015b60405180910390fd5b6104fb828261126f565b5050565b6001805461050c906143fb565b80601f0160208091040260200160405190810160405280929190818152602001828054610538906143fb565b80156105855780601f1061055a57610100808354040283529160200191610585565b820191906000526020600020905b81548152906001019060200180831161056857829003601f168201915b505050505081565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926105da9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa1580156105f7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061061b9190614463565b6106375760405162461bcd60e51b81526004016104e890614485565b6000610642836112f0565b509392505050565b60003330146106835760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b60448201526064016104e8565b61068d8383611381565b90505b92915050565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926106e39261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107249190614463565b6107405760405162461bcd60e51b81526004016104e890614485565b600061074c8484611554565b50949350505050565b600061075f6115e7565b905090565b333014806107755750610775611654565b6107b35760405162461bcd60e51b815260206004820152600f60248201526e10b9b2b633103e3e1010b0b236b4b760891b60448201526064016104e8565b50565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926108039261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610820573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108449190614463565b6108605760405162461bcd60e51b81526004016104e890614485565b610690826117d1565b60606003600061087761184e565b90508160ff16815161088991906144c3565b67ffffffffffffffff8111156108a1576108a1614263565b6040519080825280602002602001820160405280156108ca578160200160208202803683370190505b50925060005b8151811015610930578181815181106108eb576108eb6144db565b6020026020010151848281518110610905576109056144db565b6001600160e01b03199092166020928302919091019091015280610928816144f1565b9150506108d0565b50805163cb2ef6f760e01b9084906109478561450c565b94506109569060ff86166144c3565b81518110610966576109666144db565b6001600160e01b0319909216602092830291909101909101528051632c436e5b60e01b9084906109958561450c565b94506109a49060ff86166144c3565b815181106109b4576109b46144db565b6001600160e01b0319909216602092830291909101909101528051630adccee560e31b9084906109e38561450c565b94506109f29060ff86166144c3565b81518110610a0257610a026144db565b6001600160e01b03199092166020928302919091019091015260ff821615610a6c5760405162461bcd60e51b815260206004820152601c60248201527f7573652074686520636f7272656374206172726179206c656e6774680000000060448201526064016104e8565b505090565b6002805461050c906143fb565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610acb9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610ae8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b0c9190614463565b610b285760405162461bcd60e51b81526004016104e890614485565b600061064283611c16565b600080610b3f81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ba39190614529565b504360095414610bc057610bb9600a6039611d57565b9150610c82565b82610bc96115e7565b1015610bdb57610bb9600e6038611d57565b600d54831115610bf157610bb96002603a611d57565b82600d54610bff9190614542565b600d55600354604080516303e1469160e61b81529051610c7c9261010090046001600160a01b03169163f851a4409160048083019260209291908290030181865afa158015610c52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c769190614559565b8461126f565b60005b91505b610c8b81611dd0565b50919050565b600080610c9d81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610cdd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d019190614529565b504360095414610d1757610bb9600a6035611d57565b82610d206115e7565b1015610d3257610bb9600e6034611d57565b600e54831115610d4857610bb960026036611d57565b600083600e54610d589190614542565b600e819055600054909150610d76906001600160a01b03168561126f565b6000925050610c8b81611dd0565b60006001610d9181611c93565b610d9d33868686611e53565b915061064281611dd0565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610df59261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610e12573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e369190614463565b610e525760405162461bcd60e51b81526004016104e890614485565b6106908261233e565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610ea89261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610ec5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee99190614463565b610f055760405162461bcd60e51b81526004016104e890614485565b610690826123b9565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610f5b9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610f78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f9c9190614463565b610fb85760405162461bcd60e51b81526004016104e890614485565b60145460405163bf40fac160e01b8152602060048201526008602482015267506f6f6c4c656e7360c01b604482015285916000916001600160a01b039091169063bf40fac190606401602060405180830381865afa15801561101e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110429190614559565b6014805460405163bf40fac160e01b81526020600482015260248101929092527324b7b734b1aab734ab19a634b8bab4b230ba37b960611b60448301529192506000916001600160a01b03169063bf40fac190606401602060405180830381865afa1580156110b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110d99190614559565b9050806001600160a01b0316632c89aa2e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611119573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061113d9190614529565b6003546040516357c89a7d60e01b81526001600160a01b03868116600483015261010090920482166024820152908416906357c89a7d90604401602060405180830381865afa158015611194573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b89190614529565b111561125357336001600160a01b0382161461123c5760405162461bcd60e51b815260206004820152603e60248201527f4865616c746820666163746f72206e6f74206c6f7720656e6f75676820666f7260448201527f206e6f6e2d7065726d697373696f6e6564206c69717569646174696f6e73000060648201526084016104e8565b6000611249888888612436565b5094506112659050565b6000611260888888612436565b509450505b5050509392505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091018252602080820180516001600160e01b031663a9059cbb60e01b1790528251808401909352601983527f544f4b454e5f5452414e534645525f4f55545f4641494c454400000000000000908301526104fb91612530565b60008060006112fe81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561133e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113629190614529565b5061136e33338661258e565b9250925061137b81611dd0565b50915091565b6013546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa1580156113ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113f29190614529565b90506114826323b872dd60e01b8530866040516024016114149392919061458c565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050506040518060400160405280601881526020017f544f4b454e5f5452414e534645525f494e5f4641494c45440000000000000000815250612530565b6013546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa1580156114cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114ef9190614529565b9050818110156115415760405162461bcd60e51b815260206004820152601a60248201527f544f4b454e5f5452414e534645525f494e5f4f564552464c4f5700000000000060448201526064016104e8565b61154b8282614542565b95945050505050565b600080600061156281611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af11580156115a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115c69190614529565b506115d233868661258e565b925092506115df81611dd0565b509250929050565b6013546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611630573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075f9190614529565b600080600360019054906101000a90046001600160a01b03169050806001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d19190614559565b6001600160a01b0316336001600160a01b031614801561174e5750806001600160a01b0316630a755ec26040518163ffffffff1660e01b8152600401602060405180830381865afa15801561172a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061174e9190614463565b806117cb57506000546001600160a01b0316331480156117cb5750806001600160a01b031663cf6bfd2d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117cb9190614463565b91505090565b6000806117dd81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561181d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118419190614529565b50610c7f3360008561299d565b60408051600d8082526101c082019092526060919060009082602082016101a08036833701905050905063140e25ad60e31b8161188a8461450c565b93508360ff16815181106118a0576118a06144db565b6001600160e01b03199092166020928302919091019091015263db006a7560e01b816118cb8461450c565b93508360ff16815181106118e1576118e16144db565b6001600160e01b03199092166020928302919091019091015263852a12e360e01b8161190c8461450c565b93508360ff1681518110611922576119226144db565b6001600160e01b03199092166020928302919091019091015263317afabb60e21b8161194d8461450c565b93508360ff1681518110611963576119636144db565b6001600160e01b03199092166020928302919091019091015263073a938160e11b8161198e8461450c565b93508360ff16815181106119a4576119a46144db565b6001600160e01b0319909216602092830291909101909101526304c11f0360e31b816119cf8461450c565b93508360ff16815181106119e5576119e56144db565b6001600160e01b031990921660209283029190910190910152637af1e23160e11b81611a108461450c565b93508360ff1681518110611a2657611a266144db565b6001600160e01b031990921660209283029190910190910152631d8e90d160e11b81611a518461450c565b93508360ff1681518110611a6757611a676144db565b6001600160e01b03199092166020928302919091019091015263b2a02ff160e01b81611a928461450c565b93508360ff1681518110611aa857611aa86144db565b6001600160e01b03199092166020928302919091019091015263067db1b360e01b81611ad38461450c565b93508360ff1681518110611ae957611ae96144db565b6001600160e01b0319909216602092830291909101909101526304d7c4cd60e21b81611b148461450c565b93508360ff1681518110611b2a57611b2a6144db565b6001600160e01b03199092166020928302919091019091015263b0d58e4960e01b81611b558461450c565b93508360ff1681518110611b6b57611b6b6144db565b6001600160e01b03199092166020928302919091019091015263a7b820df60e01b81611b968461450c565b93508360ff1681518110611bac57611bac6144db565b6001600160e01b03199092166020928302919091019091015260ff8216156106905760405162461bcd60e51b815260206004820152601c60248201527f7573652074686520636f7272656374206172726179206c656e6774680000000060448201526064016104e8565b6000806000611c2481611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015611c64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c889190614529565b5061136e3385612fe7565b600054600160a01b900460ff16611cd95760405162461bcd60e51b815260206004820152600a6024820152691c994b595b9d195c995960b21b60448201526064016104e8565b80611d4757600360019054906101000a90046001600160a01b03166001600160a01b031663c90c20b16040518163ffffffff1660e01b8152600401600060405180830381600087803b158015611d2e57600080fd5b505af1158015611d42573d6000803e3d6000fd5b505050505b506000805460ff60a01b19169055565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836011811115611d8c57611d8c614576565b836061811115611d9e57611d9e614576565b60408051928352602083019190915260009082015260600160405180910390a182601181111561068d5761068d614576565b6000805460ff60a01b1916600160a01b179055806107b357600360019054906101000a90046001600160a01b03166001600160a01b031663632e51426040518163ffffffff1660e01b8152600401600060405180830381600087803b158015611e3857600080fd5b505af1158015611e4c573d6000803e3d6000fd5b5050505050565b60035460405163d02f735160e01b81523060048201526001600160a01b038681166024830152858116604483015284811660648301526084820184905260009283926101009091049091169063d02f73519060a4016020604051808303816000875af1158015611ec7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eeb9190614529565b90508015611f0857611f006003601d836133f2565b915050612336565b846001600160a01b0316846001600160a01b03161415611f2e57611f006006601e611d57565b611f93604080516101808101909152806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6001600160a01b038516600090815260106020526040902054611fb69085613494565b6020830181905282826003811115611fd057611fd0614576565b6003811115611fe157611fe1614576565b9052506000905081516003811115611ffb57611ffb614576565b1461202b576120226009601c8360000151600381111561201d5761201d614576565b6133f2565b92505050612336565b61204a846040518060200160405280666379da05b600008152506134bf565b6080820152604080516020810190915267016345785d8a000081526120709085906134bf565b610140820181905260808201516120879086614542565b6120919190614542565b6060820152306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120f89190614529565b60c08201908152604080516020810190915290518152608082015161211d91906134e2565b60a0820152604080516020810190915260c0820151815261014082015161214491906134e2565b61016082015260a0810151600c5461215c91906144c3565b60e08201526101408101516080820151600f546121799190614542565b6121839190614542565b610120820152610160810151600e5461219c91906144c3565b6101008201526001600160a01b03861660009081526010602052604090205460608201516121ca91906134fa565b60408301819052828260038111156121e4576121e4614576565b60038111156121f5576121f5614576565b905250600090508151600381111561220f5761220f614576565b14612231576120226009601b8360000151600381111561201d5761201d614576565b60e0810151600c55610120810151600f55610100810151600e556020808201516001600160a01b0387811660008181526010855260408082209490945583860151928b168082529084902092909255606085015192519283529092909160008051602061464e833981519152910160405180910390a3306001600160a01b0316856001600160a01b031660008051602061464e83398151915283608001516040516122de91815260200190565b60405180910390a360a081015160e08201516040805130815260208101939093528201527fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc59060600160405180910390a16000925050505b949350505050565b60008061234a81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561238a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123ae9190614529565b50610c7f3384613520565b6000806123c581611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015612405573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124299190614529565b50610c7f3384600061299d565b600080600061244481611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015612484573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a89190614529565b50836001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af11580156124e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061250d9190614529565b5061251a338787876138bb565b9250925061252781611dd0565b50935093915050565b60135460009061254a906001600160a01b03168484613d78565b80519091501561258957808060200190518101906125689190614463565b82906125875760405162461bcd60e51b81526004016104e89190614217565b505b505050565b600354604051631200453160e11b81523060048201526001600160a01b03858116602483015284811660448301526064820184905260009283928392610100909204909116906324008a62906084016020604051808303816000875af11580156125fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126209190614529565b905080156126415761263560036043836133f2565b60009250925050612995565b436009541461265657612635600a6044611d57565b61269f6040805161010081019091528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6001600160a01b0386166000908152601260205260409020600101546060820152306040516305eff7ef60e21b81526001600160a01b03888116600483015291909116906317bfdfbc90602401602060405180830381865afa158015612709573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061272d9190614529565b608082015260001985141561274b5760808101516040820152612753565b604081018590525b612761878260400151611381565b60e08201819052608082015161277691613494565b60a083018190526020830182600381111561279357612793614576565b60038111156127a4576127a4614576565b90525060009050816020015160038111156127c1576127c1614576565b146128345760405162461bcd60e51b815260206004820152603a60248201527f52455041595f424f52524f575f4e45575f4143434f554e545f424f52524f575f60448201527f42414c414e43455f43414c43554c4154494f4e5f4641494c454400000000000060648201526084016104e8565b612844600b548260e00151613494565b60c083018190526020830182600381111561286157612861614576565b600381111561287257612872614576565b905250600090508160200151600381111561288f5761288f614576565b146128f65760405162461bcd60e51b815260206004820152603160248201527f52455041595f424f52524f575f4e45575f544f54414c5f42414c414e43455f43604482015270105310d55310551253d397d19052531151607a1b60648201526084016104e8565b60a081810180516001600160a01b03898116600081815260126020908152604091829020948555600a5460019095019490945560c0870151600b81905560e088015195518251948f16855294840192909252820193909352606081019190915260808101919091527f1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a1910160405180910390a160e00151600093509150505b935093915050565b60008215806129aa575081155b6129f65760405162461bcd60e51b815260206004820152601860248201527f2172656465656d20746f6b656e73206f7220616d6f756e74000000000000000060448201526064016104e8565b612a376040805160e0810190915280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a999190614529565b60408201528315612b5c5761138884600f54612ab59190614542565b1015612ac157600f5493505b6060810184905260408051602081018252908201518152612ae29085613e0b565b6080830181905260208301826003811115612aff57612aff614576565b6003811115612b1057612b10614576565b9052506000905081602001516003811115612b2d57612b2d614576565b14612b5757612b4f6009602c8360200151600381111561201d5761201d614576565b915050612fe0565b612ca4565b600019831415612bea57600354604051630cbb414760e11b81526001600160a01b0387811660048301523060248301526000604483015261010090920490911690631976828e90606401602060405180830381865afa158015612bc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612be79190614529565b92505b6000306001600160a01b0316634aeb3d9a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c4e9190614529565b90506103e8612c5d8583614542565b1015612c67578093505b612c75848360400151613e5d565b60608301819052600f546103e891612c8c91614542565b1015612c9b57600f5460608301525b50608081018390525b600354606082015160405163eabe7d9160e01b815260009261010090046001600160a01b03169163eabe7d9191612ce29130918b919060040161458c565b6020604051808303816000875af1158015612d01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d259190614529565b90508015612d4357612d3a6003602b836133f2565b92505050612fe0565b4360095414612d5857612d3a600a602f611d57565b612d68600f548360600151613494565b60a0840181905260208401826003811115612d8557612d85614576565b6003811115612d9657612d96614576565b9052506000905082602001516003811115612db357612db3614576565b14612dd557612d3a600960318460200151600381111561201d5761201d614576565b6001600160a01b0386166000908152601060205260409020546060830151612dfd9190613494565b60c0840181905260208401826003811115612e1a57612e1a614576565b6003811115612e2b57612e2b614576565b9052506000905082602001516003811115612e4857612e48614576565b14612e6a57612d3a600960308460200151600381111561201d5761201d614576565b8160800151612e776115e7565b1015612e8957612d3a600e6032611d57565b60a0820151600f5560c08201516001600160a01b0387166000908152601060205260409020556080820151612ebf90879061126f565b306001600160a01b0316866001600160a01b031660008051602061464e8339815191528460600151604051612ef691815260200190565b60405180910390a36080820151606080840151604080516001600160a01b038b16815260208101949094528301527fe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a929910160405180910390a1600354608083015160608401516040516351dff98960e01b81523060048201526001600160a01b038a811660248301526044820193909352606481019190915261010090920416906351dff98990608401600060405180830381600087803b158015612fba57600080fd5b505af1158015612fce573d6000803e3d6000fd5b5060009250612fdb915050565b925050505b9392505050565b600354604051634ef4c3e160e01b81526000918291829161010090046001600160a01b031690634ef4c3e1906130259030908990899060040161458c565b6020604051808303816000875af1158015613044573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130689190614529565b905080156130895761307d60036021836133f2565b600092509250506133eb565b436009541461309e5761307d600a6024611d57565b6130df6040805160e0810190915280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561311d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131419190614529565b60408201526131508686611381565b60c08201819052604080516020810182529083015181526131719190613e98565b606083018190526020830182600381111561318e5761318e614576565b600381111561319f5761319f614576565b90525060009050816020015160038111156131bc576131bc614576565b146132095760405162461bcd60e51b815260206004820181905260248201527f4d494e545f45584348414e47455f43414c43554c4154494f4e5f4641494c454460448201526064016104e8565b600081606001511161325d5760405162461bcd60e51b815260206004820152601a60248201527f4d494e545f5a45524f5f43544f4b454e535f52454a454354454400000000000060448201526064016104e8565b8060600151600f5461326f91906144c3565b608082015260608101516001600160a01b03871660009081526010602052604090205461329c91906144c3565b60a082018190526080820151600f556001600160a01b0387166000818152601060209081526040918290209390935560c0840151606080860151835194855294840191909152908201929092527f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f910160405180910390a1856001600160a01b0316306001600160a01b031660008051602061464e833981519152836060015160405161334b91815260200190565b60405180910390a360035460c082015160608301516040516341c728b960e01b81523060048201526001600160a01b038a811660248301526044820193909352606481019190915261010090920416906341c728b990608401600060405180830381600087803b1580156133be57600080fd5b505af11580156133d2573d6000803e3d6000fd5b50600092506133df915050565b8160c001519350935050505b9250929050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa084601181111561342757613427614576565b84606181111561343957613439614576565b604080519283526020830191909152810184905260600160405180910390a1600384601181111561346c5761346c614576565b146134885783601181111561348357613483614576565b612336565b612336826103e86144c3565b6000808383116134b35760006134aa8486614542565b915091506133eb565b506003905060006133eb565b6000670de0b6b3a76400006134d8848460000151613ea8565b61068d91906145c6565b6000806134ef8484613eea565b905061233681613f1b565b600080838301848110613512576000925090506133eb565b6002600092509250506133eb565b60035460405163368f515360e21b815260009182916101009091046001600160a01b03169063da3d454c9061355d9030908890889060040161458c565b6020604051808303816000875af115801561357c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135a09190614529565b905080156135bd576135b560036010836133f2565b915050610690565b43600954146135d2576135b5600a600c611d57565b60006135dc6115e7565b9050838110156135fb576135f2600e600b611d57565b92505050610690565b613627604080516080810190915280600081526020016000815260200160008152602001600081525090565b306040516305eff7ef60e21b81526001600160a01b03888116600483015291909116906317bfdfbc90602401602060405180830381865afa158015613670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136949190614529565b602082018190526136a590866134fa565b60408301819052828260038111156136bf576136bf614576565b60038111156136d0576136d0614576565b90525060009050815160038111156136ea576136ea614576565b146137165761370c6009600e8360000151600381111561201d5761201d614576565b9350505050610690565b6003546040828101519051631de6c8a560e21b815230600482015260248101919091526101009091046001600160a01b03169063779b229490604401602060405180830381865afa15801561376f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137939190614529565b925082156137a85761370c60036010856133f2565b6137b4600b54866134fa565b60608301819052828260038111156137ce576137ce614576565b60038111156137df576137df614576565b90525060009050815160038111156137f9576137f9614576565b1461381b5761370c6009600d8360000151600381111561201d5761201d614576565b6040808201516001600160a01b0388166000908152601260205291909120908155600a546001909101556060810151600b55613857868661126f565b60408082015160608084015183516001600160a01b038b168152602081018a9052938401929092528201527f13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab809060800160405180910390a160009695505050505050565b600354604051632fe3f38f60e11b81523060048201526001600160a01b03838116602483015286811660448301528581166064830152608482018590526000928392839261010090920490911690635fc7e71e9060a4016020604051808303816000875af1158015613931573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139559190614529565b905080156139765761396a60036014836133f2565b60009250925050613d6f565b436009541461398b5761396a600a6018611d57565b43846001600160a01b0316636c540baf6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156139ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139ee9190614529565b146139ff5761396a600a6013611d57565b866001600160a01b0316866001600160a01b03161415613a255761396a60066019611d57565b84613a365761396a60076017611d57565b600019851415613a4c5761396a60076016611d57565b600080613a5a89898961258e565b90925090508115613a8f57613a81826011811115613a7a57613a7a614576565b601a611d57565b600094509450505050613d6f565b60035460405163c488847b60e01b815260009182916101009091046001600160a01b03169063c488847b90613acc9030908c90889060040161458c565b6040805180830381865afa158015613ae8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b0c91906145da565b90925090508115613b7b5760405162461bcd60e51b815260206004820152603360248201527f4c49515549444154455f434f4d5054524f4c4c45525f43414c43554c4154455f604482015272105353d5539517d4d152569157d19052531151606a1b60648201526084016104e8565b6040516370a0823160e01b81526001600160a01b038b811660048301528291908a16906370a0823190602401602060405180830381865afa158015613bc4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613be89190614529565b1015613c365760405162461bcd60e51b815260206004820152601860248201527f4c49515549444154455f5345495a455f544f4f5f4d554348000000000000000060448201526064016104e8565b60006001600160a01b038916301415613c5c57613c55308d8d85611e53565b9050613cd2565b60405163b2a02ff160e01b81526001600160a01b038a169063b2a02ff190613c8c908f908f90879060040161458c565b6020604051808303816000875af1158015613cab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ccf9190614529565b90505b8015613d095760405162461bcd60e51b8152602060048201526006602482015265217365697a6560d01b60448201526064016104e8565b604080516001600160a01b038e811682528d811660208301528183018790528b1660608201526080810184905290517f298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb529181900360a00190a16000975092955050505050505b94509492505050565b6060600080856001600160a01b031685604051613d9591906145fe565b6000604051808303816000865af19150503d8060008114613dd2576040519150601f19603f3d011682016040523d82523d6000602084013e613dd7565b606091505b50915091508161154b57805115613df15780518082602001fd5b8360405162461bcd60e51b81526004016104e89190614217565b600080600080613e1b8686613f33565b90925090506000826003811115613e3457613e34614576565b14613e4557509150600090506133eb565b6000613e5082613f1b565b9350935050509250929050565b600081613e7284670de0b6b3a764000061461a565b613e7c91906145c6565b9050613e888284614639565b156106905761068d6001826144c3565b600080600080613e1b8686613faf565b600061068d83836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f77000000000000000000815250614022565b6040805160208101909152600081526040518060200160405280613f12856000015185613ea8565b90529392505050565b805160009061069090670de0b6b3a7640000906145c6565b6000613f4b6040518060200160405280600081525090565b600080613f5c866000015186614075565b90925090506000826003811115613f7557613f75614576565b14613f94575060408051602081019091526000815290925090506133eb565b60408051602081019091529081526000969095509350505050565b6000613fc76040518060200160405280600081525090565b600080613fdc670de0b6b3a764000087614075565b90925090506000826003811115613ff557613ff5614576565b14614014575060408051602081019091526000815290925090506133eb565b613e508186600001516140b4565b600083158061402f575082155b1561403c57506000612fe0565b6000614048848661461a565b90508361405586836145c6565b14839061074c5760405162461bcd60e51b81526004016104e89190614217565b60008083614088575060009050806133eb565b8383028361409686836145c6565b146140a9576002600092509250506133eb565b6000925090506133eb565b60006140cc6040518060200160405280600081525090565b6000806140e186670de0b6b3a7640000614075565b909250905060008260038111156140fa576140fa614576565b14614119575060408051602081019091526000815290925090506133eb565b600080614126838861417f565b9092509050600082600381111561413f5761413f614576565b1461416257816040518060200160405280600081525095509550505050506133eb565b604080516020810190915290815260009890975095505050505050565b6000808261419357506001905060006133eb565b600061419f84866145c6565b915091509250929050565b6001600160a01b03811681146107b357600080fd5b600080604083850312156141d257600080fd5b82356141dd816141aa565b946020939093013593505050565b60005b838110156142065781810151838201526020016141ee565b838111156125875750506000910152565b60208152600082518060208401526142368160408501602087016141eb565b601f01601f19169190910160400192915050565b60006020828403121561425c57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561428b57600080fd5b813567ffffffffffffffff808211156142a357600080fd5b818401915084601f8301126142b757600080fd5b8135818111156142c9576142c9614263565b604051601f8201601f19908116603f011681019083821181831017156142f1576142f1614263565b8160405282815287602084870101111561430a57600080fd5b826020860160208301376000928101602001929092525095945050505050565b6020808252825182820181905260009190848201906040850190845b8181101561436c5783516001600160e01b03191683529284019291840191600101614346565b50909695505050505050565b60008060006060848603121561438d57600080fd5b8335614398816141aa565b925060208401356143a8816141aa565b929592945050506040919091013590565b6000806000606084860312156143ce57600080fd5b83356143d9816141aa565b92506020840135915060408401356143f0816141aa565b809150509250925092565b600181811c9082168061440f57607f821691505b60208210811415610c8b57634e487b7160e01b600052602260045260246000fd5b6001600160a01b0394851681529284166020840152921660408201526001600160e01b0319909116606082015260800190565b60006020828403121561447557600080fd5b81518015158114612fe057600080fd5b6020808252600e908201526d1b9bdd08185d5d1a1bdc9a5e995960921b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600082198211156144d6576144d66144ad565b500190565b634e487b7160e01b600052603260045260246000fd5b6000600019821415614505576145056144ad565b5060010190565b600060ff82168061451f5761451f6144ad565b6000190192915050565b60006020828403121561453b57600080fd5b5051919050565b600082821015614554576145546144ad565b500390565b60006020828403121561456b57600080fd5b8151612fe0816141aa565b634e487b7160e01b600052602160045260246000fd5b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b600052601260045260246000fd5b6000826145d5576145d56145b0565b500490565b600080604083850312156145ed57600080fd5b505080516020909101519092909150565b600082516146108184602087016141eb565b9190910192915050565b6000816000190483118215151615614634576146346144ad565b500290565b600082614648576146486145b0565b50069056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa26469706673582212208b32021b19b9d43f735b49a7f1e6353d0659170525e0bf1400c6f3801842de0464736f6c634300080a0033
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106102275760003560e01c8063852a12e311610130578063b0d58e49116100b8578063c91a424f1161007c578063c91a424f1461043f578063cb2ef6f714610452578063db006a751461047c578063f3fdb15a1461048f578063f5e3c462146104a257600080fd5b8063b0d58e49146103ee578063b2a02ff114610401578063be99f11914610414578063c3bf11cd14610423578063c5ebeaec1461042c57600080fd5b806395d89b41116100ff57806395d89b41146103ae5780639826394b146103b6578063a0712d68146103bf578063a7b820df146103d2578063aa5af0fd146103e557600080fd5b8063852a12e31461037457806389f8132e146103875780638d02d9a11461039c5780638f840ddd146103a557600080fd5b80633b1d21a2116101b35780635fe3b567116101825780635fe3b5671461032957806361feacff146103415780636752e7021461034a5780636c540baf146103585780636f307dc31461036157600080fd5b80633b1d21a2146102da5780633c4f743c146102e257806347bd37181461030d57806356e677281461031657600080fd5b8063173b9904116101fa578063173b99041461029357806318160ddd1461029c5780632608f818146102a55780632c436e5b146102b8578063313ce567146102cd57600080fd5b8063067db1b31461022c57806306fdde03146102415780630e7527021461025f578063135f133414610280575b600080fd5b61023f61023a3660046141bf565b6104b5565b005b6102496104ff565b6040516102569190614217565b60405180910390f35b61027261026d36600461424a565b61058d565b604051908152602001610256565b61027261028e3660046141bf565b61064a565b61027260085481565b610272600f5481565b6102726102b33660046141bf565b610696565b60015b60405160ff9091168152602001610256565b6003546102bb9060ff1681565b610272610755565b6014546102f5906001600160a01b031681565b6040516001600160a01b039091168152602001610256565b610272600b5481565b61023f610324366004614279565b610764565b6003546102f59061010090046001600160a01b031681565b610272600d5481565b610272666379da05b6000081565b61027260095481565b6013546102f5906001600160a01b031681565b61027261038236600461424a565b6107b6565b61038f610869565b604051610256919061432a565b61027260065481565b610272600c5481565b610249610a71565b610272600e5481565b6102726103cd36600461424a565b610a7e565b6102726103e036600461424a565b610b33565b610272600a5481565b6102726103fc36600461424a565b610c91565b61027261040f366004614378565b610d84565b61027267016345785d8a000081565b61027260075481565b61027261043a36600461424a565b610da8565b6000546102f5906001600160a01b031681565b60408051808201909152600e81526d43457263323044656c656761746560901b6020820152610249565b61027261048a36600461424a565b610e5b565b6004546102f5906001600160a01b031681565b6102726104b03660046143b9565b610f0e565b3330146104f15760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b60448201526064015b60405180910390fd5b6104fb828261126f565b5050565b6001805461050c906143fb565b80601f0160208091040260200160405190810160405280929190818152602001828054610538906143fb565b80156105855780601f1061055a57610100808354040283529160200191610585565b820191906000526020600020905b81548152906001019060200180831161056857829003601f168201915b505050505081565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926105da9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa1580156105f7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061061b9190614463565b6106375760405162461bcd60e51b81526004016104e890614485565b6000610642836112f0565b509392505050565b60003330146106835760405162461bcd60e51b815260206004820152600560248201526410b9b2b63360d91b60448201526064016104e8565b61068d8383611381565b90505b92915050565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926106e39261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107249190614463565b6107405760405162461bcd60e51b81526004016104e890614485565b600061074c8484611554565b50949350505050565b600061075f6115e7565b905090565b333014806107755750610775611654565b6107b35760405162461bcd60e51b815260206004820152600f60248201526e10b9b2b633103e3e1010b0b236b4b760891b60448201526064016104e8565b50565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb8926108039261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610820573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108449190614463565b6108605760405162461bcd60e51b81526004016104e890614485565b610690826117d1565b60606003600061087761184e565b90508160ff16815161088991906144c3565b67ffffffffffffffff8111156108a1576108a1614263565b6040519080825280602002602001820160405280156108ca578160200160208202803683370190505b50925060005b8151811015610930578181815181106108eb576108eb6144db565b6020026020010151848281518110610905576109056144db565b6001600160e01b03199092166020928302919091019091015280610928816144f1565b9150506108d0565b50805163cb2ef6f760e01b9084906109478561450c565b94506109569060ff86166144c3565b81518110610966576109666144db565b6001600160e01b0319909216602092830291909101909101528051632c436e5b60e01b9084906109958561450c565b94506109a49060ff86166144c3565b815181106109b4576109b46144db565b6001600160e01b0319909216602092830291909101909101528051630adccee560e31b9084906109e38561450c565b94506109f29060ff86166144c3565b81518110610a0257610a026144db565b6001600160e01b03199092166020928302919091019091015260ff821615610a6c5760405162461bcd60e51b815260206004820152601c60248201527f7573652074686520636f7272656374206172726179206c656e6774680000000060448201526064016104e8565b505090565b6002805461050c906143fb565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610acb9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610ae8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b0c9190614463565b610b285760405162461bcd60e51b81526004016104e890614485565b600061064283611c16565b600080610b3f81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ba39190614529565b504360095414610bc057610bb9600a6039611d57565b9150610c82565b82610bc96115e7565b1015610bdb57610bb9600e6038611d57565b600d54831115610bf157610bb96002603a611d57565b82600d54610bff9190614542565b600d55600354604080516303e1469160e61b81529051610c7c9261010090046001600160a01b03169163f851a4409160048083019260209291908290030181865afa158015610c52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c769190614559565b8461126f565b60005b91505b610c8b81611dd0565b50919050565b600080610c9d81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610cdd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d019190614529565b504360095414610d1757610bb9600a6035611d57565b82610d206115e7565b1015610d3257610bb9600e6034611d57565b600e54831115610d4857610bb960026036611d57565b600083600e54610d589190614542565b600e819055600054909150610d76906001600160a01b03168561126f565b6000925050610c8b81611dd0565b60006001610d9181611c93565b610d9d33868686611e53565b915061064281611dd0565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610df59261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610e12573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e369190614463565b610e525760405162461bcd60e51b81526004016104e890614485565b6106908261233e565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610ea89261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610ec5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee99190614463565b610f055760405162461bcd60e51b81526004016104e890614485565b610690826123b9565b60008054600354604051631beb2b9760e31b81526001600160a01b039283169263df595cb892610f5b9261010090910490911690339030906001600160e01b031988351690600401614430565b602060405180830381865afa158015610f78573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f9c9190614463565b610fb85760405162461bcd60e51b81526004016104e890614485565b60145460405163bf40fac160e01b8152602060048201526008602482015267506f6f6c4c656e7360c01b604482015285916000916001600160a01b039091169063bf40fac190606401602060405180830381865afa15801561101e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110429190614559565b6014805460405163bf40fac160e01b81526020600482015260248101929092527324b7b734b1aab734ab19a634b8bab4b230ba37b960611b60448301529192506000916001600160a01b03169063bf40fac190606401602060405180830381865afa1580156110b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110d99190614559565b9050806001600160a01b0316632c89aa2e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611119573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061113d9190614529565b6003546040516357c89a7d60e01b81526001600160a01b03868116600483015261010090920482166024820152908416906357c89a7d90604401602060405180830381865afa158015611194573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b89190614529565b111561125357336001600160a01b0382161461123c5760405162461bcd60e51b815260206004820152603e60248201527f4865616c746820666163746f72206e6f74206c6f7720656e6f75676820666f7260448201527f206e6f6e2d7065726d697373696f6e6564206c69717569646174696f6e73000060648201526084016104e8565b6000611249888888612436565b5094506112659050565b6000611260888888612436565b509450505b5050509392505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091018252602080820180516001600160e01b031663a9059cbb60e01b1790528251808401909352601983527f544f4b454e5f5452414e534645525f4f55545f4641494c454400000000000000908301526104fb91612530565b60008060006112fe81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561133e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113629190614529565b5061136e33338661258e565b9250925061137b81611dd0565b50915091565b6013546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa1580156113ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113f29190614529565b90506114826323b872dd60e01b8530866040516024016114149392919061458c565b604051602081830303815290604052906001600160e01b0319166020820180516001600160e01b0383818316178352505050506040518060400160405280601881526020017f544f4b454e5f5452414e534645525f494e5f4641494c45440000000000000000815250612530565b6013546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa1580156114cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114ef9190614529565b9050818110156115415760405162461bcd60e51b815260206004820152601a60248201527f544f4b454e5f5452414e534645525f494e5f4f564552464c4f5700000000000060448201526064016104e8565b61154b8282614542565b95945050505050565b600080600061156281611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af11580156115a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115c69190614529565b506115d233868661258e565b925092506115df81611dd0565b509250929050565b6013546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015611630573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075f9190614529565b600080600360019054906101000a90046001600160a01b03169050806001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d19190614559565b6001600160a01b0316336001600160a01b031614801561174e5750806001600160a01b0316630a755ec26040518163ffffffff1660e01b8152600401602060405180830381865afa15801561172a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061174e9190614463565b806117cb57506000546001600160a01b0316331480156117cb5750806001600160a01b031663cf6bfd2d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117cb9190614463565b91505090565b6000806117dd81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561181d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118419190614529565b50610c7f3360008561299d565b60408051600d8082526101c082019092526060919060009082602082016101a08036833701905050905063140e25ad60e31b8161188a8461450c565b93508360ff16815181106118a0576118a06144db565b6001600160e01b03199092166020928302919091019091015263db006a7560e01b816118cb8461450c565b93508360ff16815181106118e1576118e16144db565b6001600160e01b03199092166020928302919091019091015263852a12e360e01b8161190c8461450c565b93508360ff1681518110611922576119226144db565b6001600160e01b03199092166020928302919091019091015263317afabb60e21b8161194d8461450c565b93508360ff1681518110611963576119636144db565b6001600160e01b03199092166020928302919091019091015263073a938160e11b8161198e8461450c565b93508360ff16815181106119a4576119a46144db565b6001600160e01b0319909216602092830291909101909101526304c11f0360e31b816119cf8461450c565b93508360ff16815181106119e5576119e56144db565b6001600160e01b031990921660209283029190910190910152637af1e23160e11b81611a108461450c565b93508360ff1681518110611a2657611a266144db565b6001600160e01b031990921660209283029190910190910152631d8e90d160e11b81611a518461450c565b93508360ff1681518110611a6757611a676144db565b6001600160e01b03199092166020928302919091019091015263b2a02ff160e01b81611a928461450c565b93508360ff1681518110611aa857611aa86144db565b6001600160e01b03199092166020928302919091019091015263067db1b360e01b81611ad38461450c565b93508360ff1681518110611ae957611ae96144db565b6001600160e01b0319909216602092830291909101909101526304d7c4cd60e21b81611b148461450c565b93508360ff1681518110611b2a57611b2a6144db565b6001600160e01b03199092166020928302919091019091015263b0d58e4960e01b81611b558461450c565b93508360ff1681518110611b6b57611b6b6144db565b6001600160e01b03199092166020928302919091019091015263a7b820df60e01b81611b968461450c565b93508360ff1681518110611bac57611bac6144db565b6001600160e01b03199092166020928302919091019091015260ff8216156106905760405162461bcd60e51b815260206004820152601c60248201527f7573652074686520636f7272656374206172726179206c656e6774680000000060448201526064016104e8565b6000806000611c2481611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015611c64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c889190614529565b5061136e3385612fe7565b600054600160a01b900460ff16611cd95760405162461bcd60e51b815260206004820152600a6024820152691c994b595b9d195c995960b21b60448201526064016104e8565b80611d4757600360019054906101000a90046001600160a01b03166001600160a01b031663c90c20b16040518163ffffffff1660e01b8152600401600060405180830381600087803b158015611d2e57600080fd5b505af1158015611d42573d6000803e3d6000fd5b505050505b506000805460ff60a01b19169055565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836011811115611d8c57611d8c614576565b836061811115611d9e57611d9e614576565b60408051928352602083019190915260009082015260600160405180910390a182601181111561068d5761068d614576565b6000805460ff60a01b1916600160a01b179055806107b357600360019054906101000a90046001600160a01b03166001600160a01b031663632e51426040518163ffffffff1660e01b8152600401600060405180830381600087803b158015611e3857600080fd5b505af1158015611e4c573d6000803e3d6000fd5b5050505050565b60035460405163d02f735160e01b81523060048201526001600160a01b038681166024830152858116604483015284811660648301526084820184905260009283926101009091049091169063d02f73519060a4016020604051808303816000875af1158015611ec7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eeb9190614529565b90508015611f0857611f006003601d836133f2565b915050612336565b846001600160a01b0316846001600160a01b03161415611f2e57611f006006601e611d57565b611f93604080516101808101909152806000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6001600160a01b038516600090815260106020526040902054611fb69085613494565b6020830181905282826003811115611fd057611fd0614576565b6003811115611fe157611fe1614576565b9052506000905081516003811115611ffb57611ffb614576565b1461202b576120226009601c8360000151600381111561201d5761201d614576565b6133f2565b92505050612336565b61204a846040518060200160405280666379da05b600008152506134bf565b6080820152604080516020810190915267016345785d8a000081526120709085906134bf565b610140820181905260808201516120879086614542565b6120919190614542565b6060820152306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120f89190614529565b60c08201908152604080516020810190915290518152608082015161211d91906134e2565b60a0820152604080516020810190915260c0820151815261014082015161214491906134e2565b61016082015260a0810151600c5461215c91906144c3565b60e08201526101408101516080820151600f546121799190614542565b6121839190614542565b610120820152610160810151600e5461219c91906144c3565b6101008201526001600160a01b03861660009081526010602052604090205460608201516121ca91906134fa565b60408301819052828260038111156121e4576121e4614576565b60038111156121f5576121f5614576565b905250600090508151600381111561220f5761220f614576565b14612231576120226009601b8360000151600381111561201d5761201d614576565b60e0810151600c55610120810151600f55610100810151600e556020808201516001600160a01b0387811660008181526010855260408082209490945583860151928b168082529084902092909255606085015192519283529092909160008051602061464e833981519152910160405180910390a3306001600160a01b0316856001600160a01b031660008051602061464e83398151915283608001516040516122de91815260200190565b60405180910390a360a081015160e08201516040805130815260208101939093528201527fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc59060600160405180910390a16000925050505b949350505050565b60008061234a81611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af115801561238a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123ae9190614529565b50610c7f3384613520565b6000806123c581611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015612405573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124299190614529565b50610c7f3384600061299d565b600080600061244481611c93565b306001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af1158015612484573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a89190614529565b50836001600160a01b031663a6afed956040518163ffffffff1660e01b81526004016020604051808303816000875af11580156124e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061250d9190614529565b5061251a338787876138bb565b9250925061252781611dd0565b50935093915050565b60135460009061254a906001600160a01b03168484613d78565b80519091501561258957808060200190518101906125689190614463565b82906125875760405162461bcd60e51b81526004016104e89190614217565b505b505050565b600354604051631200453160e11b81523060048201526001600160a01b03858116602483015284811660448301526064820184905260009283928392610100909204909116906324008a62906084016020604051808303816000875af11580156125fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126209190614529565b905080156126415761263560036043836133f2565b60009250925050612995565b436009541461265657612635600a6044611d57565b61269f6040805161010081019091528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b6001600160a01b0386166000908152601260205260409020600101546060820152306040516305eff7ef60e21b81526001600160a01b03888116600483015291909116906317bfdfbc90602401602060405180830381865afa158015612709573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061272d9190614529565b608082015260001985141561274b5760808101516040820152612753565b604081018590525b612761878260400151611381565b60e08201819052608082015161277691613494565b60a083018190526020830182600381111561279357612793614576565b60038111156127a4576127a4614576565b90525060009050816020015160038111156127c1576127c1614576565b146128345760405162461bcd60e51b815260206004820152603a60248201527f52455041595f424f52524f575f4e45575f4143434f554e545f424f52524f575f60448201527f42414c414e43455f43414c43554c4154494f4e5f4641494c454400000000000060648201526084016104e8565b612844600b548260e00151613494565b60c083018190526020830182600381111561286157612861614576565b600381111561287257612872614576565b905250600090508160200151600381111561288f5761288f614576565b146128f65760405162461bcd60e51b815260206004820152603160248201527f52455041595f424f52524f575f4e45575f544f54414c5f42414c414e43455f43604482015270105310d55310551253d397d19052531151607a1b60648201526084016104e8565b60a081810180516001600160a01b03898116600081815260126020908152604091829020948555600a5460019095019490945560c0870151600b81905560e088015195518251948f16855294840192909252820193909352606081019190915260808101919091527f1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a1910160405180910390a160e00151600093509150505b935093915050565b60008215806129aa575081155b6129f65760405162461bcd60e51b815260206004820152601860248201527f2172656465656d20746f6b656e73206f7220616d6f756e74000000000000000060448201526064016104e8565b612a376040805160e0810190915280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612a75573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a999190614529565b60408201528315612b5c5761138884600f54612ab59190614542565b1015612ac157600f5493505b6060810184905260408051602081018252908201518152612ae29085613e0b565b6080830181905260208301826003811115612aff57612aff614576565b6003811115612b1057612b10614576565b9052506000905081602001516003811115612b2d57612b2d614576565b14612b5757612b4f6009602c8360200151600381111561201d5761201d614576565b915050612fe0565b612ca4565b600019831415612bea57600354604051630cbb414760e11b81526001600160a01b0387811660048301523060248301526000604483015261010090920490911690631976828e90606401602060405180830381865afa158015612bc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612be79190614529565b92505b6000306001600160a01b0316634aeb3d9a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c4e9190614529565b90506103e8612c5d8583614542565b1015612c67578093505b612c75848360400151613e5d565b60608301819052600f546103e891612c8c91614542565b1015612c9b57600f5460608301525b50608081018390525b600354606082015160405163eabe7d9160e01b815260009261010090046001600160a01b03169163eabe7d9191612ce29130918b919060040161458c565b6020604051808303816000875af1158015612d01573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d259190614529565b90508015612d4357612d3a6003602b836133f2565b92505050612fe0565b4360095414612d5857612d3a600a602f611d57565b612d68600f548360600151613494565b60a0840181905260208401826003811115612d8557612d85614576565b6003811115612d9657612d96614576565b9052506000905082602001516003811115612db357612db3614576565b14612dd557612d3a600960318460200151600381111561201d5761201d614576565b6001600160a01b0386166000908152601060205260409020546060830151612dfd9190613494565b60c0840181905260208401826003811115612e1a57612e1a614576565b6003811115612e2b57612e2b614576565b9052506000905082602001516003811115612e4857612e48614576565b14612e6a57612d3a600960308460200151600381111561201d5761201d614576565b8160800151612e776115e7565b1015612e8957612d3a600e6032611d57565b60a0820151600f5560c08201516001600160a01b0387166000908152601060205260409020556080820151612ebf90879061126f565b306001600160a01b0316866001600160a01b031660008051602061464e8339815191528460600151604051612ef691815260200190565b60405180910390a36080820151606080840151604080516001600160a01b038b16815260208101949094528301527fe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a929910160405180910390a1600354608083015160608401516040516351dff98960e01b81523060048201526001600160a01b038a811660248301526044820193909352606481019190915261010090920416906351dff98990608401600060405180830381600087803b158015612fba57600080fd5b505af1158015612fce573d6000803e3d6000fd5b5060009250612fdb915050565b925050505b9392505050565b600354604051634ef4c3e160e01b81526000918291829161010090046001600160a01b031690634ef4c3e1906130259030908990899060040161458c565b6020604051808303816000875af1158015613044573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130689190614529565b905080156130895761307d60036021836133f2565b600092509250506133eb565b436009541461309e5761307d600a6024611d57565b6130df6040805160e0810190915280600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081525090565b306001600160a01b031663bd6d894d6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561311d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131419190614529565b60408201526131508686611381565b60c08201819052604080516020810182529083015181526131719190613e98565b606083018190526020830182600381111561318e5761318e614576565b600381111561319f5761319f614576565b90525060009050816020015160038111156131bc576131bc614576565b146132095760405162461bcd60e51b815260206004820181905260248201527f4d494e545f45584348414e47455f43414c43554c4154494f4e5f4641494c454460448201526064016104e8565b600081606001511161325d5760405162461bcd60e51b815260206004820152601a60248201527f4d494e545f5a45524f5f43544f4b454e535f52454a454354454400000000000060448201526064016104e8565b8060600151600f5461326f91906144c3565b608082015260608101516001600160a01b03871660009081526010602052604090205461329c91906144c3565b60a082018190526080820151600f556001600160a01b0387166000818152601060209081526040918290209390935560c0840151606080860151835194855294840191909152908201929092527f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f910160405180910390a1856001600160a01b0316306001600160a01b031660008051602061464e833981519152836060015160405161334b91815260200190565b60405180910390a360035460c082015160608301516040516341c728b960e01b81523060048201526001600160a01b038a811660248301526044820193909352606481019190915261010090920416906341c728b990608401600060405180830381600087803b1580156133be57600080fd5b505af11580156133d2573d6000803e3d6000fd5b50600092506133df915050565b8160c001519350935050505b9250929050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa084601181111561342757613427614576565b84606181111561343957613439614576565b604080519283526020830191909152810184905260600160405180910390a1600384601181111561346c5761346c614576565b146134885783601181111561348357613483614576565b612336565b612336826103e86144c3565b6000808383116134b35760006134aa8486614542565b915091506133eb565b506003905060006133eb565b6000670de0b6b3a76400006134d8848460000151613ea8565b61068d91906145c6565b6000806134ef8484613eea565b905061233681613f1b565b600080838301848110613512576000925090506133eb565b6002600092509250506133eb565b60035460405163368f515360e21b815260009182916101009091046001600160a01b03169063da3d454c9061355d9030908890889060040161458c565b6020604051808303816000875af115801561357c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135a09190614529565b905080156135bd576135b560036010836133f2565b915050610690565b43600954146135d2576135b5600a600c611d57565b60006135dc6115e7565b9050838110156135fb576135f2600e600b611d57565b92505050610690565b613627604080516080810190915280600081526020016000815260200160008152602001600081525090565b306040516305eff7ef60e21b81526001600160a01b03888116600483015291909116906317bfdfbc90602401602060405180830381865afa158015613670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136949190614529565b602082018190526136a590866134fa565b60408301819052828260038111156136bf576136bf614576565b60038111156136d0576136d0614576565b90525060009050815160038111156136ea576136ea614576565b146137165761370c6009600e8360000151600381111561201d5761201d614576565b9350505050610690565b6003546040828101519051631de6c8a560e21b815230600482015260248101919091526101009091046001600160a01b03169063779b229490604401602060405180830381865afa15801561376f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137939190614529565b925082156137a85761370c60036010856133f2565b6137b4600b54866134fa565b60608301819052828260038111156137ce576137ce614576565b60038111156137df576137df614576565b90525060009050815160038111156137f9576137f9614576565b1461381b5761370c6009600d8360000151600381111561201d5761201d614576565b6040808201516001600160a01b0388166000908152601260205291909120908155600a546001909101556060810151600b55613857868661126f565b60408082015160608084015183516001600160a01b038b168152602081018a9052938401929092528201527f13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab809060800160405180910390a160009695505050505050565b600354604051632fe3f38f60e11b81523060048201526001600160a01b03838116602483015286811660448301528581166064830152608482018590526000928392839261010090920490911690635fc7e71e9060a4016020604051808303816000875af1158015613931573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139559190614529565b905080156139765761396a60036014836133f2565b60009250925050613d6f565b436009541461398b5761396a600a6018611d57565b43846001600160a01b0316636c540baf6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156139ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139ee9190614529565b146139ff5761396a600a6013611d57565b866001600160a01b0316866001600160a01b03161415613a255761396a60066019611d57565b84613a365761396a60076017611d57565b600019851415613a4c5761396a60076016611d57565b600080613a5a89898961258e565b90925090508115613a8f57613a81826011811115613a7a57613a7a614576565b601a611d57565b600094509450505050613d6f565b60035460405163c488847b60e01b815260009182916101009091046001600160a01b03169063c488847b90613acc9030908c90889060040161458c565b6040805180830381865afa158015613ae8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613b0c91906145da565b90925090508115613b7b5760405162461bcd60e51b815260206004820152603360248201527f4c49515549444154455f434f4d5054524f4c4c45525f43414c43554c4154455f604482015272105353d5539517d4d152569157d19052531151606a1b60648201526084016104e8565b6040516370a0823160e01b81526001600160a01b038b811660048301528291908a16906370a0823190602401602060405180830381865afa158015613bc4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613be89190614529565b1015613c365760405162461bcd60e51b815260206004820152601860248201527f4c49515549444154455f5345495a455f544f4f5f4d554348000000000000000060448201526064016104e8565b60006001600160a01b038916301415613c5c57613c55308d8d85611e53565b9050613cd2565b60405163b2a02ff160e01b81526001600160a01b038a169063b2a02ff190613c8c908f908f90879060040161458c565b6020604051808303816000875af1158015613cab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ccf9190614529565b90505b8015613d095760405162461bcd60e51b8152602060048201526006602482015265217365697a6560d01b60448201526064016104e8565b604080516001600160a01b038e811682528d811660208301528183018790528b1660608201526080810184905290517f298637f684da70674f26509b10f07ec2fbc77a335ab1e7d6215a4b2484d8bb529181900360a00190a16000975092955050505050505b94509492505050565b6060600080856001600160a01b031685604051613d9591906145fe565b6000604051808303816000865af19150503d8060008114613dd2576040519150601f19603f3d011682016040523d82523d6000602084013e613dd7565b606091505b50915091508161154b57805115613df15780518082602001fd5b8360405162461bcd60e51b81526004016104e89190614217565b600080600080613e1b8686613f33565b90925090506000826003811115613e3457613e34614576565b14613e4557509150600090506133eb565b6000613e5082613f1b565b9350935050509250929050565b600081613e7284670de0b6b3a764000061461a565b613e7c91906145c6565b9050613e888284614639565b156106905761068d6001826144c3565b600080600080613e1b8686613faf565b600061068d83836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f77000000000000000000815250614022565b6040805160208101909152600081526040518060200160405280613f12856000015185613ea8565b90529392505050565b805160009061069090670de0b6b3a7640000906145c6565b6000613f4b6040518060200160405280600081525090565b600080613f5c866000015186614075565b90925090506000826003811115613f7557613f75614576565b14613f94575060408051602081019091526000815290925090506133eb565b60408051602081019091529081526000969095509350505050565b6000613fc76040518060200160405280600081525090565b600080613fdc670de0b6b3a764000087614075565b90925090506000826003811115613ff557613ff5614576565b14614014575060408051602081019091526000815290925090506133eb565b613e508186600001516140b4565b600083158061402f575082155b1561403c57506000612fe0565b6000614048848661461a565b90508361405586836145c6565b14839061074c5760405162461bcd60e51b81526004016104e89190614217565b60008083614088575060009050806133eb565b8383028361409686836145c6565b146140a9576002600092509250506133eb565b6000925090506133eb565b60006140cc6040518060200160405280600081525090565b6000806140e186670de0b6b3a7640000614075565b909250905060008260038111156140fa576140fa614576565b14614119575060408051602081019091526000815290925090506133eb565b600080614126838861417f565b9092509050600082600381111561413f5761413f614576565b1461416257816040518060200160405280600081525095509550505050506133eb565b604080516020810190915290815260009890975095505050505050565b6000808261419357506001905060006133eb565b600061419f84866145c6565b915091509250929050565b6001600160a01b03811681146107b357600080fd5b600080604083850312156141d257600080fd5b82356141dd816141aa565b946020939093013593505050565b60005b838110156142065781810151838201526020016141ee565b838111156125875750506000910152565b60208152600082518060208401526142368160408501602087016141eb565b601f01601f19169190910160400192915050565b60006020828403121561425c57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561428b57600080fd5b813567ffffffffffffffff808211156142a357600080fd5b818401915084601f8301126142b757600080fd5b8135818111156142c9576142c9614263565b604051601f8201601f19908116603f011681019083821181831017156142f1576142f1614263565b8160405282815287602084870101111561430a57600080fd5b826020860160208301376000928101602001929092525095945050505050565b6020808252825182820181905260009190848201906040850190845b8181101561436c5783516001600160e01b03191683529284019291840191600101614346565b50909695505050505050565b60008060006060848603121561438d57600080fd5b8335614398816141aa565b925060208401356143a8816141aa565b929592945050506040919091013590565b6000806000606084860312156143ce57600080fd5b83356143d9816141aa565b92506020840135915060408401356143f0816141aa565b809150509250925092565b600181811c9082168061440f57607f821691505b60208210811415610c8b57634e487b7160e01b600052602260045260246000fd5b6001600160a01b0394851681529284166020840152921660408201526001600160e01b0319909116606082015260800190565b60006020828403121561447557600080fd5b81518015158114612fe057600080fd5b6020808252600e908201526d1b9bdd08185d5d1a1bdc9a5e995960921b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600082198211156144d6576144d66144ad565b500190565b634e487b7160e01b600052603260045260246000fd5b6000600019821415614505576145056144ad565b5060010190565b600060ff82168061451f5761451f6144ad565b6000190192915050565b60006020828403121561453b57600080fd5b5051919050565b600082821015614554576145546144ad565b500390565b60006020828403121561456b57600080fd5b8151612fe0816141aa565b634e487b7160e01b600052602160045260246000fd5b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b600052601260045260246000fd5b6000826145d5576145d56145b0565b500490565b600080604083850312156145ed57600080fd5b505080516020909101519092909150565b600082516146108184602087016141eb565b9190910192915050565b6000816000190483118215151615614634576146346144ad565b500290565b600082614648576146486145b0565b50069056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa26469706673582212208b32021b19b9d43f735b49a7f1e6353d0659170525e0bf1400c6f3801842de0464736f6c634300080a0033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.