false
false
0
The new Blockscout UI is now open source! Learn how to deploy it here

Contract Address Details

0xB9d66383298921bb5910e6182Ee79F2696546FE6

Contract Name
MToken_Taiko
Creator
0x66f850–36be7e at 0xeb89c2–6ec988
Balance
0 ETH
Tokens
Fetching tokens...
Transactions
0 Transactions
Transfers
0 Transfers
Gas Used
Fetching gas used...
Last Balance Update
486877
Contract is not verified. However, we found a verified contract with the same bytecode in Blockscout DB 0x0d17662a9e8682b5eb6a30011eb962c63eb6c66a.
All metadata displayed below is from that contract. In order to verify current contract, click Verify & Publish button
Verify & Publish
Contract name:
MToken_Taiko




Optimization enabled
true
Compiler version
v0.8.17+commit.8df45f5f




Optimization runs
200
Verified at
2024-06-02T10:15:57.110750Z

contracts/multichain/taiko/MToken_Taiko.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "../../MToken.sol";
import "./libraries/TaikoContracts.sol";
import "./interfaces/ITaikoL2_L1BlockNumber.sol";

/**
 * @title Minterest MToken Contract
 * @notice Abstract base for MTokens
 * @author Minterest
 */
contract MToken_Taiko is MToken {
    /// @dev Returns block number from L1 network.
    ///      Note! Block number from L1 returns with the delay
    function getBlockNumber() internal view virtual override returns (uint256) {
        return ITaikoL2_L1BlockNumber(TaikoContracts.TaikoL2).lastSyncedBlock();
    }
}
        

@openzeppelin/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}
          

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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 Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
          

contracts/interfaces/ISupervisor.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/access/IAccessControl.sol";
import "./IMToken.sol";
import "./IBuyback.sol";
import "./IRewardsHub.sol";
import "./ILinkageLeaf.sol";
import "./IWhitelist.sol";

/**
 * @title Minterest Supervisor Contract
 * @author Minterest
 */
interface ISupervisor is IAccessControl, ILinkageLeaf {
    /**
     * @notice Emitted when an admin supports a market
     */
    event MarketListed(IMToken mToken);

    /**
     * @notice Emitted when an account enable a market
     */
    event MarketEnabledAsCollateral(IMToken mToken, address account);

    /**
     * @notice Emitted when an account disable a market
     */
    event MarketDisabledAsCollateral(IMToken mToken, address account);

    /**
     * @notice Emitted when a utilisation factor is changed by admin
     */
    event NewUtilisationFactor(
        IMToken mToken,
        uint256 oldUtilisationFactorMantissa,
        uint256 newUtilisationFactorMantissa
    );

    /**
     * @notice Emitted when liquidation fee is changed by admin
     */
    event NewLiquidationFee(IMToken marketAddress, uint256 oldLiquidationFee, uint256 newLiquidationFee);

    /**
     * @notice Emitted when borrow cap for a mToken is changed
     */
    event NewBorrowCap(IMToken indexed mToken, uint256 newBorrowCap);

    /**
     * @notice Per-account mapping of "assets you are in"
     */
    function accountAssets(address, uint256) external view returns (IMToken);

    /**
     * @notice Collection of states of supported markets
     * @dev Types containing (nested) mappings could not be parameters or return of external methods
     */
    function markets(IMToken)
        external
        view
        returns (
            bool isListed,
            uint256 utilisationFactorMantissa,
            uint256 liquidationFeeMantissa
        );

    /**
     * @notice get A list of all markets
     */
    function allMarkets(uint256) external view returns (IMToken);

    /**
     * @notice get Borrow caps enforced by beforeBorrow for each mToken address.
     */
    function borrowCaps(IMToken) external view returns (uint256);

    /**
     * @notice get keccak-256 hash of gatekeeper role
     */
    function GATEKEEPER() external view returns (bytes32);

    /**
     * @notice get keccak-256 hash of timelock
     */
    function TIMELOCK() external view returns (bytes32);

    /**
     * @notice Returns the assets an account has enabled as collateral
     * @param account The address of the account to pull assets for
     * @return A dynamic list with the assets the account has enabled as collateral
     */
    function getAccountAssets(address account) external view returns (IMToken[] memory);

    /**
     * @notice Returns whether the given account is enabled as collateral in the given asset
     * @param account The address of the account to check
     * @param mToken The mToken to check
     * @return True if the account is in the asset, otherwise false.
     */
    function checkMembership(address account, IMToken mToken) external view returns (bool);

    /**
     * @notice Add assets to be included in account liquidity calculation
     * @param mTokens The list of addresses of the mToken markets to be enabled as collateral
     */
    function enableAsCollateral(IMToken[] memory mTokens) external;

    /**
     * @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 mTokenAddress The address of the asset to be removed
     */
    function disableAsCollateral(IMToken mTokenAddress) external;

    /**
     * @notice Makes checks if the account should be allowed to lend tokens in the given market
     * @param mToken The market to verify the lend against
     * @param lender The account which would get the lent tokens
     */
    function beforeLend(IMToken mToken, address lender) external;

    /**
     * @notice Checks if the account should be allowed to redeem tokens in the given market and triggers emission system
     * @param mToken The market to verify the redeem against
     * @param redeemer The account which would redeem the tokens
     * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
     * @param isAmlProcess Do we need to check the AML system or not
     */
    function beforeRedeem(
        IMToken mToken,
        address redeemer,
        uint256 redeemTokens,
        bool isAmlProcess
    ) external;

    /**
     * @notice Checks if the account should be allowed to borrow the underlying asset of the given market
     * @param mToken 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
     */
    function beforeBorrow(
        IMToken mToken,
        address borrower,
        uint256 borrowAmount
    ) external;

    /**
     * @notice Checks if the account should be allowed to repay a borrow in the given market
     * @param mToken The market to verify the repay against
     * @param borrower The account which would borrowed the asset
     */
    function beforeRepayBorrow(IMToken mToken, address borrower) external;

    /**
     * @notice Checks if the seizing of assets should be allowed to occur (auto liquidation process)
     * @param mToken Asset which was used as collateral and will be seized
     * @param liquidator_ The address of liquidator contract
     * @param borrower The address of the borrower
     */
    function beforeAutoLiquidationSeize(
        IMToken mToken,
        address liquidator_,
        address borrower
    ) external;

    /**
     * @notice Checks if the sender should be allowed to repay borrow in the given market (auto liquidation process)
     * @param liquidator_ The address of liquidator contract
     * @param borrower_ The account which borrowed the asset
     * @param mToken_ The market to verify the repay against
     */
    function beforeAutoLiquidationRepay(
        address liquidator_,
        address borrower_,
        IMToken mToken_
    ) external;

    /**
     * @notice Checks if the address is the Liquidation contract
     * @dev Used in liquidation process
     * @param liquidator_ Prospective address of the Liquidation contract
     */
    function isLiquidator(address liquidator_) external view;

    /**
     * @notice Checks if the account should be allowed to transfer tokens in the given market
     * @param mToken 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 mTokens to transfer
     */
    function beforeTransfer(
        IMToken mToken,
        address src,
        address dst,
        uint256 transferTokens
    ) external;

    /**
     * @notice Makes checks before flash loan in MToken
     * @param mToken The address of the token
     * receiver - The address of the loan receiver
     * amount - How much tokens to flash loan
     * fee - Flash loan fee
     */
    function beforeFlashLoan(
        IMToken mToken,
        address, /* receiver */
        uint256, /* amount */
        uint256 /* fee */
    ) external view;

    /**
     * @notice Calculate account liquidity in USD related to utilisation factors of underlying assets
     * @return (USD value above total utilisation requirements of all assets,
     *           USD value below total utilisation requirements of all assets)
     */
    function getAccountLiquidity(address account) external view returns (uint256, uint256);

    /**
     * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
     * @param mTokenModify 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 (hypothetical account liquidity in excess of collateral requirements,
     *          hypothetical account shortfall below collateral requirements)
     */
    function getHypotheticalAccountLiquidity(
        address account,
        IMToken mTokenModify,
        uint256 redeemTokens,
        uint256 borrowAmount
    ) external returns (uint256, uint256);

    /**
     * @notice Get liquidationFeeMantissa and utilisationFactorMantissa for market
     * @param market Market for which values are obtained
     * @return (liquidationFeeMantissa, utilisationFactorMantissa)
     */
    function getMarketData(IMToken market) external view returns (uint256, uint256);

    /**
     * @notice Validates redeem and reverts on rejection. May emit logs.
     * @param redeemAmount The amount of the underlying asset being redeemed
     * @param redeemTokens The number of tokens being redeemed
     */
    function redeemVerify(uint256 redeemAmount, uint256 redeemTokens) external view;

    /**
     * @notice Sets the utilisationFactor for a market
     * @dev Governance function to set per-market utilisationFactor
     * @param mToken The market to set the factor on
     * @param newUtilisationFactorMantissa The new utilisation factor, scaled by 1e18
     * @dev RESTRICTION: Timelock only.
     */
    function setUtilisationFactor(IMToken mToken, uint256 newUtilisationFactorMantissa) external;

    /**
     * @notice Sets the liquidationFee for a market
     * @dev Governance function to set per-market liquidationFee
     * @param mToken The market to set the fee on
     * @param newLiquidationFeeMantissa The new liquidation fee, scaled by 1e18
     * @dev RESTRICTION: Timelock only.
     */
    function setLiquidationFee(IMToken mToken, uint256 newLiquidationFeeMantissa) external;

    /**
     * @notice Add the market to the markets mapping and set it as listed, also initialize MNT market state.
     * @dev Admin function to set isListed and add support for the market
     * @param mToken The address of the market (token) to list
     * @dev RESTRICTION: Admin only.
     */
    function supportMarket(IMToken mToken) external;

    /**
     * @notice Set the given borrow caps for the given mToken markets.
     *         Borrowing that brings total borrows to or above borrow cap will revert.
     * @dev Admin or gateKeeper function to set the borrow caps.
     *      A borrow cap of 0 corresponds to unlimited borrowing.
     * @param mTokens The addresses of the markets (tokens) to change the borrow caps for
     * @param newBorrowCaps The new borrow cap values in underlying to be set.
     *                      A value of 0 corresponds to unlimited borrowing.
     * @dev RESTRICTION: Gatekeeper only.
     */
    function setMarketBorrowCaps(IMToken[] calldata mTokens, uint256[] calldata newBorrowCaps) external;

    /**
     * @notice Return all of the markets
     * @dev The automatic getter may be used to access an individual market.
     * @return The list of market addresses
     */
    function getAllMarkets() external view returns (IMToken[] memory);

    /**
     * @notice Returns true if market is listed in Supervisor
     */
    function isMarketListed(IMToken) external view returns (bool);

    /**
     * @notice Check that account is not in the black list and protocol operations are available.
     * @param account The address of the account to check
     */
    function isNotBlacklisted(address account) external view returns (bool);

    /**
     * @notice Check if transfer of MNT is allowed for accounts.
     * @param from The source account address to check
     * @param to The destination account address to check
     */
    function isMntTransferAllowed(address from, address to) external view returns (bool);

    /**
     * @notice Returns block number
     */
    function getBlockNumber() external view returns (uint256);
}
          

contracts/interfaces/ILinkageRoot.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

interface ILinkageRoot {
    /**
     * @notice Emitted when new root contract connected to all leafs
     */
    event LinkageRootSwitch(ILinkageRoot newRoot);

    /**
     * @notice Emitted when root interconnects its contracts
     */
    event LinkageRootInterconnected();

    /**
     * @notice Connects new root to all leafs contracts
     * @param newRoot New root contract address
     */
    function switchLinkageRoot(ILinkageRoot newRoot) external;

    /**
     * @notice Update root for all leaf contracts
     * @dev Should include only leaf contracts
     */
    function interconnect() external;
}
          

@openzeppelin/contracts/access/AccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}
          

contracts/interfaces/ILinkageLeaf.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "./ILinkageRoot.sol";

interface ILinkageLeaf {
    /**
     * @notice Emitted when root contract address is changed
     */
    event LinkageRootSwitched(ILinkageRoot newRoot, ILinkageRoot oldRoot);

    /**
     * @notice Connects new root contract address
     * @param newRoot New root contract address
     */
    function switchLinkageRoot(ILinkageRoot newRoot) external;
}
          

@openzeppelin/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.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]
 * ```solidity
 * 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) || (!Address.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 Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}
          

contracts/interfaces/IRewardsHubLight.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "./IMToken.sol";
import "./ILinkageLeaf.sol";

interface IRewardsHubLight is ILinkageLeaf {
    event DistributedSupplierMnt(IMToken mToken, address supplier, uint256 mntDelta, uint256 mntSupplyIndex);
    event DistributedBorrowerMnt(IMToken mToken, address borrower, uint256 mntDelta, uint256 mntBorrowIndex);
    event EmissionRewardAccrued(address account, uint256 amount);
    event RepresentativeRewardAccrued(address account, address provider, uint256 amount);
    event BuybackRewardAccrued(address account, uint256 amount);

    event Withdraw(address account, uint256 amount);
    event MntGranted(address recipient, uint256 amount);

    event MntSupplyEmissionRateUpdated(IMToken mToken, uint256 newSupplyEmissionRate);
    event MntBorrowEmissionRateUpdated(IMToken mToken, uint256 newBorrowEmissionRate);

    /**
     * @notice get keccak-256 hash of gatekeeper
     */
    function GATEKEEPER() external view returns (bytes32);

    /**
     * @notice get keccak-256 hash of timelock
     */
    function TIMELOCK() external view returns (bytes32);

    /**
     * @notice Gets the rate at which MNT is distributed to the corresponding supply market (per block)
     */
    function mntSupplyEmissionRate(IMToken) external view returns (uint256);

    /**
     * @notice Gets the rate at which MNT is distributed to the corresponding borrow market (per block)
     */
    function mntBorrowEmissionRate(IMToken) external view returns (uint256);

    /**
     * @notice Gets the MNT market supply state for each market
     */
    function mntSupplyState(IMToken) external view returns (uint224 index, uint32 blockN);

    /**
     * @notice Gets the MNT market borrow state for each market
     */
    function mntBorrowState(IMToken) external view returns (uint224 index, uint32 blockN);

    /**
     * @notice Gets the MNT supply index and block number for each market
     */
    function mntSupplierState(IMToken, address) external view returns (uint224 index, uint32 blockN);

    /**
     * @notice Gets the MNT borrow index and block number for each market
     */
    function mntBorrowerState(IMToken, address) external view returns (uint224 index, uint32 blockN);

    /**
     * @notice Gets amount of available balance of an account.
     */
    function totalBalanceOf(address account) external view returns (uint256);

    /**
     * @notice Gets amount of MNT that can be withdrawn from an account at this block.
     */
    function availableBalanceOf(address account) external view returns (uint256);

    /**
     * @notice Initializes market in RewardsHub. Should be called once from Supervisor.supportMarket
     * @dev RESTRICTION: Supervisor only
     */
    function initMarket(IMToken mToken) external;

    /**
     * @notice Accrues MNT to the market by updating the borrow and supply indexes
     * @dev This method doesn't update MNT index history in Minterest NFT.
     * @param market The market whose supply and borrow index to update
     * @return (MNT supply index, MNT borrow index)
     */
    function updateAndGetMntIndexes(IMToken market) external returns (uint224, uint224);

    /**
     * @notice Shorthand function to distribute MNT emissions from supplies of one market.
     */
    function distributeSupplierMnt(IMToken mToken, address account) external;

    /**
     * @notice Shorthand function to distribute MNT emissions from borrows of one market.
     */
    function distributeBorrowerMnt(IMToken mToken, address account) external;

    /**
     * @notice Updates market indexes and distributes tokens (if any) for holder
     * @dev Updates indexes and distributes only for those markets where the holder have a
     * non-zero supply or borrow balance.
     * @param account The address to distribute MNT for
     */
    function distributeAllMnt(address account) external;

    /**
     * @notice Distribute all MNT accrued by the accounts
     * @param accounts The addresses to distribute MNT for
     * @param mTokens The list of markets to distribute MNT in
     * @param borrowers Whether or not to distribute MNT earned by borrowing
     * @param suppliers Whether or not to distribute MNT earned by supplying
     */
    function distributeMnt(
        address[] memory accounts,
        IMToken[] memory mTokens,
        bool borrowers,
        bool suppliers
    ) external;

    /**
     * @notice Accrues buyback reward
     * @dev RESTRICTION: Buyback only
     */
    function accrueBuybackReward(address account, uint256 amount) external;

    /**
     * @notice Transfers available part of MNT rewards to the sender.
     * This will decrease accounts buyback and voting weights.
     */
    function withdraw(uint256 amount) external;

    /**
     * @notice Transfers
     * @dev RESTRICTION: Admin only
     */
    function grant(address recipient, uint256 amount) external;

    /**
     * @notice Set MNT borrow and supply emission rates for a single market
     * @param mToken The market whose MNT emission rate to update
     * @param newMntSupplyEmissionRate New supply MNT emission rate for market
     * @param newMntBorrowEmissionRate New borrow MNT emission rate for market
     * @dev RESTRICTION Timelock only
     */
    function setMntEmissionRates(
        IMToken mToken,
        uint256 newMntSupplyEmissionRate,
        uint256 newMntBorrowEmissionRate
    ) external;
}
          

@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol)

pragma solidity ^0.8.0;

import "./IERC3156FlashBorrower.sol";

/**
 * @dev Interface of the ERC3156 FlashLender, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashLender {
    /**
     * @dev The amount of currency available to be lended.
     * @param token The loan currency.
     * @return The amount of `token` that can be borrowed.
     */
    function maxFlashLoan(address token) external view returns (uint256);

    /**
     * @dev The fee to be charged for a given loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @return The amount of `token` to be charged for the loan, on top of the returned principal.
     */
    function flashFee(address token, uint256 amount) external view returns (uint256);

    /**
     * @dev Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
}
          

contracts/interfaces/IMToken.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "./IInterestRateModel.sol";

interface IMToken is IAccessControl, IERC20, IERC3156FlashLender, IERC165 {
    /**
     * @notice Event emitted when interest is accrued
     */
    event AccrueInterest(
        uint256 cashPrior,
        uint256 interestAccumulated,
        uint256 borrowIndex,
        uint256 totalBorrows,
        uint256 totalProtocolInterest
    );

    /**
     * @notice Event emitted when tokens are lended
     */
    event Lend(address lender, uint256 lendAmount, uint256 lendTokens, uint256 newTotalTokenSupply);

    /**
     * @notice Event emitted when tokens are redeemed
     */
    event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens, uint256 newTotalTokenSupply);

    /**
     * @notice Event emitted when underlying is borrowed
     */
    event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);

    /**
     * @notice Event emitted when tokens are seized
     */
    event Seize(
        address borrower,
        address receiver,
        uint256 seizeTokens,
        uint256 accountsTokens,
        uint256 totalSupply,
        uint256 seizeUnderlyingAmount
    );

    /**
     * @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 repaid during autoliquidation
     */
    event AutoLiquidationRepayBorrow(
        address borrower,
        uint256 repayAmount,
        uint256 accountBorrowsNew,
        uint256 totalBorrowsNew,
        uint256 TotalProtocolInterestNew
    );

    /**
     * @notice Event emitted when flash loan is executed
     */
    event FlashLoanExecuted(address receiver, uint256 amount, uint256 fee);

    /**
     * @notice Event emitted when interestRateModel is changed
     */
    event NewMarketInterestRateModel(IInterestRateModel oldInterestRateModel, IInterestRateModel newInterestRateModel);

    /**
     * @notice Event emitted when the protocol interest factor is changed
     */
    event NewProtocolInterestFactor(
        uint256 oldProtocolInterestFactorMantissa,
        uint256 newProtocolInterestFactorMantissa
    );

    /**
     * @notice Event emitted when the flash loan max share is changed
     */
    event NewFlashLoanMaxShare(uint256 oldMaxShare, uint256 newMaxShare);

    /**
     * @notice Event emitted when the flash loan fee is changed
     */
    event NewFlashLoanFee(uint256 oldFee, uint256 newFee);

    /**
     * @notice Event emitted when the protocol interest are added
     */
    event ProtocolInterestAdded(address benefactor, uint256 addAmount, uint256 newTotalProtocolInterest);

    /**
     * @notice Event emitted when the protocol interest reduced
     */
    event ProtocolInterestReduced(address admin, uint256 reduceAmount, uint256 newTotalProtocolInterest);

    /**
     * @notice Value is the Keccak-256 hash of "TIMELOCK"
     */
    function TIMELOCK() external view returns (bytes32);

    /**
     * @notice Underlying asset for this MToken
     */
    function underlying() external view returns (IERC20);

    /**
     * @notice EIP-20 token name for this token
     */
    function name() external view returns (string memory);

    /**
     * @notice EIP-20 token symbol for this token
     */
    function symbol() external view returns (string memory);

    /**
     * @notice EIP-20 token decimals for this token
     */
    function decimals() external view returns (uint8);

    /**
     * @notice Model which tells what the current interest rate should be
     */
    function interestRateModel() external view returns (IInterestRateModel);

    /**
     * @notice Initial exchange rate used when lending the first MTokens (used when totalTokenSupply = 0)
     */
    function initialExchangeRateMantissa() external view returns (uint256);

    /**
     * @notice Fraction of interest currently set aside for protocol interest
     */
    function protocolInterestFactorMantissa() external view returns (uint256);

    /**
     * @notice Block number that interest was last accrued at
     */
    function accrualBlockNumber() external view returns (uint256);

    /**
     * @notice Accumulator of the total earned interest rate since the opening of the market
     */
    function borrowIndex() external view returns (uint256);

    /**
     * @notice Total amount of outstanding borrows of the underlying in this market
     */
    function totalBorrows() external view returns (uint256);

    /**
     * @notice Total amount of protocol interest of the underlying held in this market
     */
    function totalProtocolInterest() external view returns (uint256);

    /**
     * @notice Share of market's current underlying token balance that can be used as flash loan (scaled by 1e18).
     */
    function maxFlashLoanShare() external view returns (uint256);

    /**
     * @notice Share of flash loan amount that would be taken as fee (scaled by 1e18).
     */
    function flashLoanFeeShare() external view returns (uint256);

    /**
     * @notice Returns total token supply
     */
    function totalSupply() external view returns (uint256);

    /**
     * @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 Whether or not the transfer succeeded
     */
    function transfer(address dst, uint256 amount) external returns (bool);

    /**
     * @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 Whether or not the transfer succeeded
     */
    function transferFrom(
        address src,
        address dst,
        uint256 amount
    ) external returns (bool);

    /**
     * @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 Whether or not the approval succeeded
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @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 The number of tokens allowed to be spent (-1 means infinite)
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @notice Get the token balance of the `owner`
     * @param owner The address of the account to query
     * @return The number of tokens owned by `owner`
     */
    function balanceOf(address owner) external view returns (uint256);

    /**
     * @notice Get the underlying balance of the `owner`
     * @dev This also accrues interest in a transaction
     * @param owner The address of the account to query
     * @return The amount of underlying owned by `owner`
     */
    function balanceOfUnderlying(address owner) external returns (uint256);

    /**
     * @notice Get a snapshot of the account's balances, and the cached exchange rate
     * @dev This is used by supervisor to more efficiently perform liquidity checks.
     * @param account Address of the account to snapshot
     * @return (token balance, borrow balance, exchange rate mantissa)
     */
    function getAccountSnapshot(address account)
        external
        view
        returns (
            uint256,
            uint256,
            uint256
        );

    /**
     * @notice Returns the current per-block borrow interest rate for this mToken
     * @return The borrow interest rate per block, scaled by 1e18
     */
    function borrowRatePerBlock() external view returns (uint256);

    /**
     * @notice Returns the current per-block supply interest rate for this mToken
     * @return The supply interest rate per block, scaled by 1e18
     */
    function supplyRatePerBlock() external view returns (uint256);

    /**
     * @notice Returns the current total borrows plus accrued interest
     * @return The total borrows with interest
     */
    function totalBorrowsCurrent() external returns (uint256);

    /**
     * @notice Accrue interest to updated borrowIndex and then calculate account's
     *         borrow balance using the updated borrowIndex
     * @param account The address whose balance should be calculated after updating borrowIndex
     * @return The calculated balance
     */
    function borrowBalanceCurrent(address account) external returns (uint256);

    /**
     * @notice Return the borrow balance of account based on stored data
     * @param account The address whose balance should be calculated
     * @return The calculated balance
     */
    function borrowBalanceStored(address account) external view returns (uint256);

    /**
     * @notice Accrue interest then return the up-to-date exchange rate
     * @return Calculated exchange rate scaled by 1e18
     */
    function exchangeRateCurrent() external returns (uint256);

    /**
     * @notice Calculates the exchange rate from the underlying to the MToken
     * @dev This function does not accrue interest before calculating the exchange rate
     * @return Calculated exchange rate scaled by 1e18
     */
    function exchangeRateStored() external view returns (uint256);

    /**
     * @notice Get cash balance of this mToken in the underlying asset
     * @return The quantity of underlying asset owned by this contract
     */
    function getCash() external view returns (uint256);

    /**
     * @notice Applies accrued interest to total borrows and protocol interest
     * @dev This calculates interest accrued from the last checkpointed block
     *   up to the current block and writes new checkpoint to storage.
     */
    function accrueInterest() external;

    /**
     * @notice Sender supplies assets into the market and receives mTokens in exchange
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param lendAmount The amount of the underlying asset to supply
     */
    function lend(uint256 lendAmount) external;

    /**
     * @notice Sender redeems mTokens in exchange for the underlying asset
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param redeemTokens The number of mTokens to redeem into underlying
     */
    function redeem(uint256 redeemTokens) external;

    /**
     * @notice Redeems all mTokens for account in exchange for the underlying asset.
     * Can only be called within the AML system!
     * @dev Accrues interest whether or not the operation succeeds, unless reverted
     * @param account An account that is potentially sanctioned by the AML system
     */
    function redeemByAmlDecision(address account) external;

    /**
     * @notice Sender redeems mTokens 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 mTokens
     */
    function redeemUnderlying(uint256 redeemAmount) external;

    /**
     * @notice Sender borrows assets from the protocol to their own address
     * @param borrowAmount The amount of the underlying asset to borrow
     */
    function borrow(uint256 borrowAmount) external;

    /**
     * @notice Sender repays their own borrow
     * @param repayAmount The amount to repay
     */
    function repayBorrow(uint256 repayAmount) external;

    /**
     * @notice Sender repays a borrow belonging to borrower
     * @param borrower the account with the debt being payed off
     * @param repayAmount The amount to repay
     */
    function repayBorrowBehalf(address borrower, uint256 repayAmount) external;

    /**
     * @notice Liquidator repays a borrow belonging to borrower
     * @param borrower_ the account with the debt being payed off
     * @param repayAmount_ the amount of underlying tokens being returned
     */
    function autoLiquidationRepayBorrow(address borrower_, uint256 repayAmount_) external;

    /**
     * @notice A public function to sweep accidental ERC-20 transfers to this contract.
     *         Tokens are sent to admin (timelock)
     * @param token The address of the ERC-20 token to sweep
     * @dev RESTRICTION: Admin only.
     */
    function sweepToken(IERC20 token, address admin_) external;

    /**
     * @notice Burns collateral tokens at the borrower's address, transfer underlying assets
     to the Liquidator address.
     * @dev Called only during an auto liquidation process, msg.sender must be the Liquidation contract.
     * @param borrower_ The account having collateral seized
     * @param seizeUnderlyingAmount_ The number of underlying assets to seize. The caller must ensure
     that the parameter is greater than zero.
     * @param isLoanInsignificant_ Marker for insignificant loan whose collateral must be credited to the
     protocolInterest
     * @param receiver_ Address that receives accounts collateral
     */
    function autoLiquidationSeize(
        address borrower_,
        uint256 seizeUnderlyingAmount_,
        bool isLoanInsignificant_,
        address receiver_
    ) external;

    /**
     * @notice The amount of currency available to be lent.
     * @param token The loan currency.
     * @return The amount of `token` that can be borrowed.
     */
    function maxFlashLoan(address token) external view returns (uint256);

    /**
     * @notice The fee to be charged for a given loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @return The amount of `token` to be charged for the loan, on top of the returned principal.
     */
    function flashFee(address token, uint256 amount) external view returns (uint256);

    /**
     * @notice Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);

    /**
     * @notice accrues interest and sets a new protocol interest factor for the protocol
     * @dev Admin function to accrue interest and set a new protocol interest factor
     * @dev RESTRICTION: Timelock only.
     */
    function setProtocolInterestFactor(uint256 newProtocolInterestFactorMantissa) external;

    /**
     * @notice Accrues interest and increase protocol interest by transferring from msg.sender
     * @param addAmount_ Amount of addition to protocol interest
     */
    function addProtocolInterest(uint256 addAmount_) external;

    /**
     * @notice Can only be called by liquidation contract. Increase protocol interest by transferring from payer.
     * @dev Calling code should make sure that accrueInterest() was called before.
     * @param payer_ The address from which the protocol interest will be transferred
     * @param addAmount_ Amount of addition to protocol interest
     */
    function addProtocolInterestBehalf(address payer_, uint256 addAmount_) external;

    /**
     * @notice Accrues interest and reduces protocol interest by transferring to admin
     * @param reduceAmount Amount of reduction to protocol interest
     * @dev RESTRICTION: Admin only.
     */
    function reduceProtocolInterest(uint256 reduceAmount, address admin_) external;

    /**
     * @notice accrues interest and updates the interest rate model using setInterestRateModelFresh
     * @dev Admin function to accrue interest and update the interest rate model
     * @param newInterestRateModel the new interest rate model to use
     * @dev RESTRICTION: Timelock only.
     */
    function setInterestRateModel(IInterestRateModel newInterestRateModel) external;

    /**
     * @notice Updates share of markets cash that can be used as maximum amount of flash loan.
     * @param newMax New max amount share
     * @dev RESTRICTION: Timelock only.
     */
    function setFlashLoanMaxShare(uint256 newMax) external;

    /**
     * @notice Updates fee of flash loan.
     * @param newFee New fee share of flash loan
     * @dev RESTRICTION: Timelock only.
     */
    function setFlashLoanFeeShare(uint256 newFee) external;
}
          

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
          

@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC3156 FlashBorrower, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 *
 * _Available since v4.1._
 */
interface IERC3156FlashBorrower {
    /**
     * @dev Receive a flash loan.
     * @param initiator The initiator of the loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param fee The additional amount of tokens to repay.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
     */
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}
          

contracts/interfaces/IInterestRateModel.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title Minterest InterestRateModel Interface
 * @author Minterest
 */
interface IInterestRateModel {
    /**
     * @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 protocolInterest The total amount of protocol interest the market has
     * @return The borrow rate per block (as a percentage, and scaled by 1e18)
     */
    function getBorrowRate(
        uint256 cash,
        uint256 borrows,
        uint256 protocolInterest
    ) external view 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 protocolInterest The total amount of protocol interest the market has
     * @param protocolInterestFactorMantissa The current protocol interest factor the market has
     * @return The supply rate per block (as a percentage, and scaled by 1e18)
     */
    function getSupplyRate(
        uint256 cash,
        uint256 borrows,
        uint256 protocolInterest,
        uint256 protocolInterestFactorMantissa
    ) external view returns (uint256);
}
          

@openzeppelin/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}
          

contracts/multichain/taiko/interfaces/ITaikoL2_L1BlockNumber.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

/**
 * @title ITaikoL2_L1BlockNumber
 */
interface ITaikoL2_L1BlockNumber {
    /********************
     * Public Functions *
     ********************/

    function lastSyncedBlock() external view returns (uint64);
}
          

contracts/multichain/taiko/libraries/TaikoContracts.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

// @dev Store the address of Taiko `TaikoL2` contract
library TaikoContracts {
    address internal constant TaikoL2 = 0x1670000000000000000000000000000000010001;
}
          

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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 IERC20Permit {
    /**
     * @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);
}
          

contracts/interfaces/IBuyback.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/access/IAccessControl.sol";
import "./ILinkageLeaf.sol";

interface IBuyback is IAccessControl, ILinkageLeaf {
    event Stake(address who, uint256 amount);
    event Unstake(address who, uint256 amount);
    event NewBuyback(uint256 amount, uint256 share);
    event ParticipateBuyback(address who);
    event LeaveBuyback(address who, uint256 currentStaked);
    event BuybackWeightChanged(address who, uint256 newWeight, uint256 oldWeight, uint256 newTotalWeight);
    event LoyaltyParametersChanged(uint256 newCoreFactor, uint32 newCoreResetPenalty);
    event LoyaltyStrataChanged();
    event LoyaltyGroupsChanged(uint256 newGroupCount);

    /**
     * @notice Gets info about account membership in Buyback
     */
    function getMemberInfo(address account)
        external
        view
        returns (
            bool participating,
            uint256 weight,
            uint256 lastIndex,
            uint256 stakeAmount
        );

    /**
     * @notice Gets info about accounts loyalty calculation
     */
    function getLoyaltyInfo(address account)
        external
        view
        returns (
            uint32 loyaltyStart,
            uint256 coreBalance,
            uint256 lastBalance
        );

    /**
     * @notice Gets if an account is participating in Buyback
     */
    function isParticipating(address account) external view returns (bool);

    /**
     * @notice Gets stake of the account
     */
    function getStakedAmount(address account) external view returns (uint256);

    /**
     * @notice Gets buyback weight of an account
     */
    function getWeight(address account) external view returns (uint256);

    /**
     * @notice Gets loyalty factor of an account with given balance.
     */
    function getLoyaltyFactorForBalance(address account, uint256 balance) external view returns (uint256);

    /**
     * @notice Gets total Buyback weight, which is the sum of weights of all accounts.
     */
    function getTotalWeight() external view returns (uint256);

    /**
     * @notice Gets current Buyback index.
     * Its the accumulated sum of MNTs shares that are given for each weight of an account.
     */
    function getBuybackIndex() external view returns (uint256);

    /**
     * @notice Gets all global loyalty parameters.
     */
    function getLoyaltyParameters()
        external
        view
        returns (
            uint256[24] memory loyaltyStrata,
            uint256[] memory groupThresholds,
            uint32[] memory groupStartStrata,
            uint256 coreFactor,
            uint32 coreResetPenalty
        );

    /**
     * @notice Stakes the specified amount of MNT and transfers them to this contract.
     * @notice This contract should be approved to transfer MNT from sender account
     * @param amount The amount of MNT to stake
     */
    function stake(uint256 amount) external;

    /**
     * @notice Unstakes the specified amount of MNT and transfers them back to sender if he participates
     *         in the Buyback system, otherwise just transfers MNT tokens to the sender.
     *         would not be greater than staked amount left. If `amount == MaxUint256` unstakes all staked tokens.
     * @param amount The amount of MNT to unstake
     */
    function unstake(uint256 amount) external;

    /**
     * @notice Claims buyback rewards, updates buyback weight and voting power.
     * Does nothing if account is not participating. Reverts if operation is paused.
     * @param account Address to update weights for
     */
    function updateBuybackAndVotingWeights(address account) external;

    /**
     * @notice Claims buyback rewards, updates buyback weight and voting power.
     * Does nothing if account is not participating or update is paused.
     * @param account Address to update weights for
     */
    function updateBuybackAndVotingWeightsRelaxed(address account) external;

    /**
     * @notice Does a buyback using the specified amount of MNT from sender's account
     * @param amount The amount of MNT to take and distribute as buyback
     * @dev RESTRICTION: Distributor only
     */
    function buyback(uint256 amount) external;

    /**
     * @notice Make account participating in the buyback.
     */
    function participate() external;

    /**
     * @notice Make accounts participate in buyback before its start.
     * @param accounts Address to make participate in buyback.
     * @dev RESTRICTION: Admin only
     */
    function participateOnBehalf(address[] memory accounts) external;

    /**
     * @notice Leave buyback participation, claim any MNTs rewarded by the buyback.
     * Leaving does not withdraw staked MNTs but reduces weight of the account to zero
     */
    function leave() external;

    /**
     * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and
     * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available
     * for their owner to be claimed
     * Can only be called if (timestamp > participantLastVoteTimestamp + maxNonVotingPeriod).
     * @param participant Address to leave for
     * @dev RESTRICTION: GATEKEEPER only
     */
    function leaveOnBehalf(address participant) external;

    /**
     * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and
     * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available
     * for their owner to be claimed.
     * @dev Function to leave sanctioned accounts from Buyback system
     * Can only be called if the participant is sanctioned by the AML system.
     * @param participant Address to leave for
     */
    function leaveByAmlDecision(address participant) external;

    /**
     * @notice Changes loyalty core factor and core reset penalty parameters.
     * @dev RESTRICTION: Admin only
     */
    function setLoyaltyParameters(uint256 newCoreFactor, uint32 newCoreResetPenalty) external;

    /**
     * @notice Sets new loyalty factors for all strata.
     * @dev RESTRICTION: Admin only
     */
    function setLoyaltyStrata(uint256[24] memory newLoyaltyStrata) external;

    /**
     * @notice Sets new groups and their parameters
     * @param newGroupThresholds New list of groups and their balance thresholds.
     * @param newGroupStartStrata Indexes of starting stratum of each group. First index MUST be zero.
     *        Length of array must be equal to the newGroupThresholds
     * @dev RESTRICTION: Admin only
     */
    function setLoyaltyGroups(uint256[] memory newGroupThresholds, uint32[] memory newGroupStartStrata) external;
}
          

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.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 SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 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(IERC20 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));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit 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(IERC20 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");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation 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).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // 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 cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}
          

contracts/libraries/ErrorCodes.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

library ErrorCodes {
    // Common
    string internal constant ADMIN_ONLY = "E101";
    string internal constant UNAUTHORIZED = "E102";
    string internal constant OPERATION_PAUSED = "E103";
    string internal constant WHITELISTED_ONLY = "E104";
    string internal constant ADDRESS_IS_NOT_IN_AML_SYSTEM = "E105";
    string internal constant ADDRESS_IS_BLACKLISTED = "E106";

    // Invalid input
    string internal constant ADMIN_ADDRESS_CANNOT_BE_ZERO = "E201";
    string internal constant INVALID_REDEEM = "E202";
    string internal constant REDEEM_TOO_MUCH = "E203";
    string internal constant MARKET_NOT_LISTED = "E204";
    string internal constant INSUFFICIENT_LIQUIDITY = "E205";
    string internal constant INVALID_SENDER = "E206";
    string internal constant BORROW_CAP_REACHED = "E207";
    string internal constant BALANCE_OWED = "E208";
    string internal constant UNRELIABLE_LIQUIDATOR = "E209";
    string internal constant INVALID_DESTINATION = "E210";
    string internal constant INSUFFICIENT_STAKE = "E211";
    string internal constant INVALID_DURATION = "E212";
    string internal constant INVALID_PERIOD_RATE = "E213";
    string internal constant EB_TIER_LIMIT_REACHED = "E214";
    string internal constant LQ_INCORRECT_REPAY_AMOUNT = "E215";
    string internal constant LQ_INSUFFICIENT_SEIZE_AMOUNT = "E216";
    string internal constant EB_TIER_DOES_NOT_EXIST = "E217";
    string internal constant EB_ZERO_TIER_CANNOT_BE_ENABLED = "E218";
    string internal constant EB_ALREADY_ACTIVATED_TIER = "E219";
    string internal constant EB_END_BLOCK_MUST_BE_LARGER_THAN_CURRENT = "E220";
    string internal constant EB_CANNOT_MINT_TOKEN_FOR_ACTIVATED_TIER = "E221";
    string internal constant EB_EMISSION_BOOST_IS_NOT_IN_RANGE = "E222";
    string internal constant TARGET_ADDRESS_CANNOT_BE_ZERO = "E223";
    string internal constant INSUFFICIENT_TOKEN_IN_VESTING_CONTRACT = "E224";
    string internal constant VESTING_SCHEDULE_ALREADY_EXISTS = "E225";
    string internal constant INSUFFICIENT_TOKENS_TO_CREATE_SCHEDULE = "E226";
    string internal constant NO_VESTING_SCHEDULE = "E227";
    string internal constant MNT_AMOUNT_IS_ZERO = "E230";
    string internal constant INCORRECT_AMOUNT = "E231";
    string internal constant MEMBERSHIP_LIMIT = "E232";
    string internal constant MEMBER_NOT_EXIST = "E233";
    string internal constant MEMBER_ALREADY_ADDED = "E234";
    string internal constant MEMBERSHIP_LIMIT_REACHED = "E235";
    string internal constant REPORTED_PRICE_SHOULD_BE_GREATER_THAN_ZERO = "E236";
    string internal constant MTOKEN_ADDRESS_CANNOT_BE_ZERO = "E237";
    string internal constant TOKEN_ADDRESS_CANNOT_BE_ZERO = "E238";
    string internal constant REDEEM_TOKENS_OR_REDEEM_AMOUNT_MUST_BE_ZERO = "E239";
    string internal constant FL_TOKEN_IS_NOT_UNDERLYING = "E240";
    string internal constant FL_AMOUNT_IS_TOO_LARGE = "E241";
    string internal constant FL_CALLBACK_FAILED = "E242";
    string internal constant EB_MARKET_INDEX_IS_LESS_THAN_USER_INDEX = "E254";
    string internal constant LQ_UNSUPPORTED_FULL_REPAY = "E255";
    string internal constant LQ_UNSUPPORTED_FULL_SEIZE = "E256";
    string internal constant LQ_UNSUPPORTED_MARKET_RECEIVED = "E257";
    string internal constant LQ_UNSUCCESSFUL_CALLBACK = "E258";
    string internal constant FL_UNAUTHORIZED_CALLBACK = "E270";
    string internal constant FL_INCORRECT_TOKEN_OUT_DEVIATION = "E271";
    string internal constant FL_SWAP_CALL_FAILS = "E272";
    string internal constant FL_INVALID_AMOUNT_TOKEN_IN_SPENT = "E273";
    string internal constant FL_INVALID_AMOUNT_TOKEN_OUT_RECEIVED = "E274";
    string internal constant FL_EXACT_IN_INCORRECT_ALLOWANCE_AFTER = "E275";
    string internal constant FL_RECEIVER_NOT_FOUND = "E276";

    // Protocol errors
    string internal constant INVALID_PRICE = "E301";
    string internal constant MARKET_NOT_FRESH = "E302";
    string internal constant BORROW_RATE_TOO_HIGH = "E303";
    string internal constant INSUFFICIENT_TOKEN_CASH = "E304";
    string internal constant INSUFFICIENT_TOKENS_FOR_RELEASE = "E305";
    string internal constant INSUFFICIENT_MNT_FOR_GRANT = "E306";
    string internal constant TOKEN_TRANSFER_IN_UNDERFLOW = "E307";
    string internal constant NOT_PARTICIPATING_IN_BUYBACK = "E308";
    string internal constant NOT_ENOUGH_PARTICIPATING_ACCOUNTS = "E309";
    string internal constant NOTHING_TO_DISTRIBUTE = "E310";
    string internal constant ALREADY_PARTICIPATING_IN_BUYBACK = "E311";
    string internal constant MNT_APPROVE_FAILS = "E312";
    string internal constant TOO_EARLY_TO_DRIP = "E313";
    string internal constant BB_UNSTAKE_TOO_EARLY = "E314";
    string internal constant INSUFFICIENT_SHORTFALL = "E315";
    string internal constant HEALTHY_FACTOR_NOT_IN_RANGE = "E316";
    string internal constant BUYBACK_DRIPS_ALREADY_HAPPENED = "E317";
    string internal constant EB_INDEX_SHOULD_BE_GREATER_THAN_INITIAL = "E318";
    string internal constant NO_VESTING_SCHEDULES = "E319";
    string internal constant INSUFFICIENT_UNRELEASED_TOKENS = "E320";
    string internal constant ORACLE_PRICE_EXPIRED = "E321";
    string internal constant TOKEN_NOT_FOUND = "E322";
    string internal constant RECEIVED_PRICE_HAS_INVALID_ROUND = "E323";
    string internal constant FL_PULL_AMOUNT_IS_TOO_LOW = "E324";
    string internal constant INSUFFICIENT_TOTAL_PROTOCOL_INTEREST = "E325";
    string internal constant BB_ACCOUNT_RECENTLY_VOTED = "E326";
    string internal constant PRICE_FEED_ID_NOT_FOUND = "E327";
    string internal constant INCORRECT_PRICE_MULTIPLIER = "E328";
    string internal constant LL_NEW_ROOT_CANNOT_BE_ZERO = "E329";
    string internal constant RH_PAYOUT_FROM_FUTURE = "E330";
    string internal constant RH_ACCRUE_WITHOUT_UNLOCK = "E331";
    string internal constant RH_LERP_DELTA_IS_GREATER_THAN_PERIOD = "E332";
    string internal constant PRICE_FEED_ADDRESS_NOT_FOUND = "E333";

    // Invalid input - Admin functions
    string internal constant ZERO_EXCHANGE_RATE = "E401";
    string internal constant SECOND_INITIALIZATION = "E402";
    string internal constant MARKET_ALREADY_LISTED = "E403";
    string internal constant IDENTICAL_VALUE = "E404";
    string internal constant ZERO_ADDRESS = "E405";
    string internal constant EC_INVALID_PROVIDER_REPRESENTATIVE = "E406";
    string internal constant EC_PROVIDER_CANT_BE_REPRESENTATIVE = "E407";
    string internal constant OR_ORACLE_ADDRESS_CANNOT_BE_ZERO = "E408";
    string internal constant OR_UNDERLYING_TOKENS_DECIMALS_SHOULD_BE_GREATER_THAN_ZERO = "E409";
    string internal constant OR_REPORTER_MULTIPLIER_SHOULD_BE_GREATER_THAN_ZERO = "E410";
    string internal constant INVALID_TOKEN = "E411";
    string internal constant INVALID_PROTOCOL_INTEREST_FACTOR_MANTISSA = "E412";
    string internal constant INVALID_REDUCE_AMOUNT = "E413";
    string internal constant LIQUIDATION_FEE_MANTISSA_SHOULD_BE_GREATER_THAN_ZERO = "E414";
    string internal constant INVALID_UTILISATION_FACTOR_MANTISSA = "E415";
    string internal constant INVALID_MTOKENS_OR_BORROW_CAPS = "E416";
    string internal constant FL_PARAM_IS_TOO_LARGE = "E417";
    string internal constant MNT_INVALID_NONVOTING_PERIOD = "E418";
    string internal constant INPUT_ARRAY_LENGTHS_ARE_NOT_EQUAL = "E419";
    string internal constant EC_INVALID_BOOSTS = "E420";
    string internal constant EC_ACCOUNT_IS_ALREADY_LIQUIDITY_PROVIDER = "E421";
    string internal constant EC_ACCOUNT_HAS_NO_AGREEMENT = "E422";
    string internal constant OR_TIMESTAMP_THRESHOLD_SHOULD_BE_GREATER_THAN_ZERO = "E423";
    string internal constant OR_UNDERLYING_TOKENS_DECIMALS_TOO_BIG = "E424";
    string internal constant OR_REPORTER_MULTIPLIER_TOO_BIG = "E425";
    string internal constant SHOULD_HAVE_REVOCABLE_SCHEDULE = "E426";
    string internal constant MEMBER_NOT_IN_DELAY_LIST = "E427";
    string internal constant DELAY_LIST_LIMIT = "E428";
    string internal constant NUMBER_IS_NOT_IN_SCALE = "E429";
    string internal constant BB_STRATUM_OF_FIRST_LOYALTY_GROUP_IS_NOT_ZERO = "E430";
    string internal constant INPUT_ARRAY_IS_EMPTY = "E431";
    string internal constant OR_INCORRECT_PRICE_FEED_ID = "E432";
    string internal constant OR_PRICE_AGE_CAN_NOT_BE_ZERO = "E433";
    string internal constant OR_INCORRECT_PRICE_FEED_ADDRESS = "E434";
    string internal constant OR_INCORRECT_SECONDARY_PRICE_FEED_ADDRESS = "E435";
    string internal constant RH_COOLDOWN_START_ALREADY_SET = "E436";
    string internal constant RH_INCORRECT_COOLDOWN_START = "E437";
    string internal constant RH_COOLDOWN_IS_FINISHED = "E438";
    string internal constant RH_INCORRECT_NUMBER_OF_CHARGES = "E439";
    string internal constant RH_INCORRECT_CHARGE_SHARE = "E440";
    string internal constant RH_COOLDOWN_START_NOT_SET = "E441";
}
          

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}
          

@openzeppelin/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
          

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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.8.0/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);
        }
    }
}
          

contracts/interfaces/IWhitelist.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";

interface IWhitelist is IAccessControl {
    /**
     * @notice The given member was added to the whitelist
     */
    event MemberAdded(address);

    /**
     * @notice The given member was removed from the whitelist
     */
    event MemberRemoved(address);

    /**
     * @notice Protocol operation mode switched
     */
    event WhitelistModeWasTurnedOff();

    /**
     * @notice Amount of maxMembers changed
     */
    event MaxMemberAmountChanged(uint256);

    /**
     * @notice get maximum number of members.
     *      When membership reaches this number, no new members may join.
     */
    function maxMembers() external view returns (uint256);

    /**
     * @notice get the total number of members stored in the map.
     */
    function memberCount() external view returns (uint256);

    /**
     * @notice get protocol operation mode.
     */
    function whitelistModeEnabled() external view returns (bool);

    /**
     * @notice get is account member of whitelist
     */
    function accountMembership(address) external view returns (bool);

    /**
     * @notice get keccak-256 hash of GATEKEEPER role
     */
    function GATEKEEPER() external view returns (bytes32);

    /**
     * @notice Add a new member to the whitelist.
     * @param newAccount The account that is being added to the whitelist.
     * @dev RESTRICTION: Gatekeeper only.
     */
    function addMember(address newAccount) external;

    /**
     * @notice Remove a member from the whitelist.
     * @param accountToRemove The account that is being removed from the whitelist.
     * @dev RESTRICTION: Gatekeeper only.
     */
    function removeMember(address accountToRemove) external;

    /**
     * @notice Disables whitelist mode and enables emission boost mode.
     * @dev RESTRICTION: Admin only.
     */
    function turnOffWhitelistMode() external;

    /**
     * @notice Set a new threshold of participants.
     * @param newThreshold New number of participants.
     * @dev RESTRICTION: Gatekeeper only.
     */
    function setMaxMembers(uint256 newThreshold) external;

    /**
     * @notice Check protocol operation mode. In whitelist mode, only members from whitelist and who have
     *         EmissionBooster can work with protocol.
     * @param who The address of the account to check for participation.
     */
    function isWhitelisted(address who) external view returns (bool);
}
          

@openzeppelin/contracts/token/ERC1155/IERC1155.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}
          

contracts/interfaces/IRewardsHub.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "./IRewardsHubLight.sol";

interface IRewardsHub is IRewardsHubLight {
    event RewardUnlocked(address account, uint256 amount);

    /**
     * @notice Gets summary amount of available and delayed balances of an account.
     */
    function totalBalanceOf(address account) external view override returns (uint256);

    /**
     * @notice Gets part of delayed rewards that is unlocked and have become available.
     */
    function getUnlockableRewards(address account) external view returns (uint256);
}
          

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
          

contracts/MTokenStorage.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IMToken.sol";
import "./interfaces/ISupervisor.sol";

abstract contract MTokenStorage is IMToken, Initializable, AccessControl, ReentrancyGuard {
    /**
     * @notice Container for borrow balance information
     * @param principal Total balance (with accrued interest), after applying the most recent balance-changing action
     * @param interestIndex Global borrowIndex as of the most recent balance-changing action
     */
    struct BorrowSnapshot {
        uint256 principal;
        uint256 interestIndex;
    }

    /// @dev Value is the Keccak-256 hash of "TIMELOCK"
    bytes32 public constant TIMELOCK = bytes32(0xaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371);

    uint256 internal constant EXP_SCALE = 1e18;
    bytes32 internal constant FLASH_LOAN_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");

    /**
     * @dev Maximum borrow rate that can ever be applied (.0005% / block)
     */
    uint256 internal constant borrowRateMaxMantissa = 0.0005e16;

    /**
     * @dev Maximum fraction of interest that can be set aside for protocol interest
     */
    uint256 internal constant protocolInterestFactorMaxMantissa = 1e18;

    /**
     * @notice Underlying asset for this MToken
     */
    IERC20 public underlying;

    /**
     * @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;

    /**
     * @notice Contract which oversees inter-mToken operations
     */
    ISupervisor public supervisor;

    /**
     * @notice Model which tells what the current interest rate should be
     */
    IInterestRateModel public interestRateModel;

    /**
     * @dev Initial exchange rate used when lending the first MTokens (used when totalTokenSupply = 0)
     */
    uint256 public initialExchangeRateMantissa;

    /**
     * @notice Fraction of interest currently set aside for protocol interest
     */
    uint256 public protocolInterestFactorMantissa;

    /**
     * @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 protocol interest of the underlying held in this market
     */
    uint256 public totalProtocolInterest;

    /**
     * @dev Total number of tokens in circulation
     */
    uint256 internal totalTokenSupply;

    /**
     * @dev Official record of token balances for each account
     */
    mapping(address => uint256) internal accountTokens;

    /**
     * @dev Approved token transfer amounts on behalf of others
     */
    mapping(address => mapping(address => uint256)) internal transferAllowances;

    /**
     * @dev Mapping of account addresses to outstanding borrow balances
     */
    mapping(address => BorrowSnapshot) internal accountBorrows;

    /// @dev Share of market's current underlying  token balance that can be used as flash loan (scaled by 1e18).
    uint256 public maxFlashLoanShare;

    /// @dev Share of flash loan amount that would be taken as fee (scaled by 1e18).
    uint256 public flashLoanFeeShare;
}
          

contracts/MToken.sol

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.17;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./MTokenStorage.sol";
import "./interfaces/IInterestRateModel.sol";
import "./libraries/ErrorCodes.sol";

/**
 * @title Minterest MToken Contract
 * @notice Abstract base for MTokens
 * @author Minterest
 */
contract MToken is MTokenStorage {
    using SafeERC20 for IERC20;
    using SafeCast for uint256;

    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initialize the money market
     * @param supervisor_ The address of the Supervisor
     * @param interestRateModel_ The address of the interest rate model
     * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
     * @param name_ EIP-20 name of this token
     * @param symbol_ EIP-20 symbol of this token
     * @param decimals_ EIP-20 decimal precision of this token
     * @param underlying_ The address of the underlying asset
     */
    function initialize(
        address admin_,
        ISupervisor supervisor_,
        IInterestRateModel interestRateModel_,
        uint256 initialExchangeRateMantissa_,
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        IERC20 underlying_
    ) public initializer {
        // Set initial exchange rate
        require(initialExchangeRateMantissa_ > 0, ErrorCodes.ZERO_EXCHANGE_RATE);
        initialExchangeRateMantissa = initialExchangeRateMantissa_;

        // Set the supervisor
        supervisor = supervisor_;

        // Initialize block number and borrow index (block number mocks depend on supervisor being set)
        accrualBlockNumber = getBlockNumber();
        borrowIndex = EXP_SCALE; // = 1e18

        // Set the interest rate model (depends on block number / borrow index)
        setInterestRateModelFresh(interestRateModel_);

        _grantRole(DEFAULT_ADMIN_ROLE, admin_);
        _grantRole(TIMELOCK, admin_);

        underlying = underlying_;
        name = name_;
        symbol = symbol_;
        decimals = decimals_;

        maxFlashLoanShare = 1.0e18; // 100%
        flashLoanFeeShare = 0.0009e18; // 0.09%
    }

    /// @inheritdoc IMToken
    function totalSupply() external view returns (uint256) {
        return totalTokenSupply;
    }

    /**
     * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
     * @dev Called by both `transfer` and `transferFrom` internally
     * @param spender The address of the account performing the transfer
     * @param src The address of the source account
     * @param dst The address of the destination account
     * @param tokens The number of tokens to transfer
     */
    function transferTokens(
        address spender,
        address src,
        address dst,
        uint256 tokens
    ) internal {
        /* Do not allow self-transfers */
        require(src != dst, ErrorCodes.INVALID_DESTINATION);

        // Reverts if transfer is not allowed
        // slither-disable-next-line reentrancy-benign,reentrancy-events
        supervisor.beforeTransfer(this, src, dst, tokens);

        /* Get the allowance, infinite for the account owner */
        uint256 startingAllowance = 0;
        if (spender == src) {
            startingAllowance = type(uint256).max;
        } else {
            startingAllowance = transferAllowances[src][spender];
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS

        accountTokens[src] -= tokens;
        accountTokens[dst] += tokens;

        if (startingAllowance != type(uint256).max) {
            transferAllowances[src][spender] = startingAllowance - tokens;
        }

        emit Transfer(src, dst, tokens);
    }

    /// @inheritdoc IMToken
    function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
        transferTokens(msg.sender, msg.sender, dst, amount);
        return true;
    }

    /// @inheritdoc IMToken
    function transferFrom(
        address src,
        address dst,
        uint256 amount
    ) external nonReentrant returns (bool) {
        transferTokens(msg.sender, src, dst, amount);
        return true;
    }

    /// @inheritdoc IMToken
    function approve(address spender, uint256 amount) external returns (bool) {
        address src = msg.sender;
        transferAllowances[src][spender] = amount;
        emit Approval(src, spender, amount);
        return true;
    }

    /// @inheritdoc IMToken
    function allowance(address owner, address spender) external view returns (uint256) {
        return transferAllowances[owner][spender];
    }

    /// @inheritdoc IMToken
    function balanceOf(address owner) external view returns (uint256) {
        return accountTokens[owner];
    }

    /// @inheritdoc IMToken
    function balanceOfUnderlying(address owner) external returns (uint256) {
        return (accountTokens[owner] * exchangeRateCurrent()) / EXP_SCALE;
    }

    /// @inheritdoc IMToken
    function getAccountSnapshot(address account)
        external
        view
        returns (
            uint256,
            uint256,
            uint256
        )
    {
        uint256 mTokenBalance = accountTokens[account];
        uint256 borrowBalance = borrowBalanceStoredInternal(account);
        uint256 exchangeRateMantissa = exchangeRateStoredInternal();
        return (mTokenBalance, borrowBalance, exchangeRateMantissa);
    }

    /**
     * @dev Function to simply retrieve block number
     *  This exists mainly for inheriting test contracts to stub this result.
     */
    function getBlockNumber() internal view virtual returns (uint256) {
        return block.number;
    }

    /// @inheritdoc IMToken
    function borrowRatePerBlock() external view returns (uint256) {
        return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalProtocolInterest);
    }

    /// @inheritdoc IMToken
    function supplyRatePerBlock() external view returns (uint256) {
        return
            interestRateModel.getSupplyRate(
                getCashPrior(),
                totalBorrows,
                totalProtocolInterest,
                protocolInterestFactorMantissa
            );
    }

    /// @inheritdoc IMToken
    function totalBorrowsCurrent() external nonReentrant returns (uint256) {
        accrueInterest();
        return totalBorrows;
    }

    /// @inheritdoc IMToken
    function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) {
        accrueInterest();
        return borrowBalanceStored(account);
    }

    /**
     * @notice Return the borrow balance of account based on stored data
     * @param account The address whose balance should be calculated
     * @return The calculated balance
     */
    function borrowBalanceStored(address account) public view returns (uint256) {
        return borrowBalanceStoredInternal(account);
    }

    /**
     * @notice Return the borrow balance of account based on stored data
     * @param account The address whose balance should be calculated
     * @return the calculated balance
     */
    function borrowBalanceStoredInternal(address account) internal view returns (uint256) {
        /* Get borrowBalance and borrowIndex */
        BorrowSnapshot storage borrowSnapshot = accountBorrows[account];

        /* If borrowBalance = 0 then borrowIndex is likely also 0.
         * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
         */
        if (borrowSnapshot.principal == 0) return 0;

        /* Calculate new borrow balance using the interest index:
         *  recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
         */
        return (borrowSnapshot.principal * borrowIndex) / borrowSnapshot.interestIndex;
    }

    /// @inheritdoc IMToken
    function exchangeRateCurrent() public nonReentrant returns (uint256) {
        accrueInterest();
        return exchangeRateStored();
    }

    /// @inheritdoc IMToken
    function exchangeRateStored() public view returns (uint256) {
        return exchangeRateStoredInternal();
    }

    /**
     * @notice Calculates the exchange rate from the underlying to the MToken
     * @dev This function does not accrue interest before calculating the exchange rate
     * @return calculated exchange rate scaled by 1e18
     */
    function exchangeRateStoredInternal() internal view virtual returns (uint256) {
        if (totalTokenSupply == 0) {
            /*
             * If there are no tokens lent:
             *  exchangeRate = initialExchangeRate
             */
            return initialExchangeRateMantissa;
        } else {
            /*
             * Otherwise:
             *  exchangeRate = (totalCash + totalBorrows - totalProtocolInterest) / totalTokenSupply
             */
            return ((getCashPrior() + totalBorrows - totalProtocolInterest) * EXP_SCALE) / totalTokenSupply;
        }
    }

    /// @inheritdoc IMToken
    function getCash() external view returns (uint256) {
        return getCashPrior();
    }

    /**
     * @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 getCashPrior() internal view virtual returns (uint256) {
        return underlying.balanceOf(address(this));
    }

    /// @inheritdoc IMToken
    function accrueInterest() public virtual {
        /* Remember the initial block number */
        uint256 currentBlockNumber = getBlockNumber();
        uint256 accrualBlockNumberPrior = accrualBlockNumber;

        /* Short-circuit accumulating 0 interest */
        if (accrualBlockNumberPrior == currentBlockNumber) return;

        /* Read the previous values out of storage */
        uint256 cashPrior = getCashPrior();
        uint256 borrowIndexPrior = borrowIndex;

        /* Calculate the current borrow interest rate */
        uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, totalBorrows, totalProtocolInterest);
        require(borrowRateMantissa <= borrowRateMaxMantissa, ErrorCodes.BORROW_RATE_TOO_HIGH);

        /* Calculate the number of blocks elapsed since the last accrual */
        uint256 blockDelta = currentBlockNumber - accrualBlockNumberPrior;

        /*
         * Calculate the interest accumulated into borrows and protocol interest and the new index:
         *  simpleInterestFactor = borrowRate * blockDelta
         *  interestAccumulated = simpleInterestFactor * totalBorrows
         *  totalBorrows += interestAccumulated
         *  totalProtocolInterest += interestAccumulated * protocolInterestFactor
         *  borrowIndex = simpleInterestFactor * borrowIndex + borrowIndex
         */
        uint256 simpleInterestFactor = borrowRateMantissa * blockDelta;
        uint256 interestAccumulated = (totalBorrows * simpleInterestFactor) / EXP_SCALE;
        totalBorrows += interestAccumulated;
        totalProtocolInterest += (interestAccumulated * protocolInterestFactorMantissa) / EXP_SCALE;
        borrowIndex = borrowIndexPrior + (borrowIndexPrior * simpleInterestFactor) / EXP_SCALE;

        accrualBlockNumber = currentBlockNumber;

        emit AccrueInterest(cashPrior, interestAccumulated, borrowIndex, totalBorrows, totalProtocolInterest);
    }

    /// @inheritdoc IMToken
    function lend(uint256 lendAmount) external {
        accrueInterest();
        lendFresh(msg.sender, lendAmount, true);
    }

    /**
     * @notice Account supplies assets into the market and receives mTokens in exchange
     * @dev Assumes interest has already been accrued up to the current block
     * @param lender The address of the account which is supplying the assets
     * @param lendAmount The amount of the underlying asset to supply
     * @return actualLendAmount actual lend amount
     */
    function lendFresh(
        address lender,
        uint256 lendAmount,
        bool isERC20based
    ) internal nonReentrant returns (uint256 actualLendAmount) {
        supervisor.beforeLend(this, lender);

        /* Verify market's block number equals current block number */
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);

        uint256 exchangeRateMantissa = exchangeRateStoredInternal();

        /*
         *  We call `doTransferIn` for the lender and the lendAmount.
         *  Note: The mToken must handle variations between ERC-20 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 mToken holds an additional `actualLendAmount`
         *  of cash.
         */
        if (isERC20based) {
            actualLendAmount = doTransferIn(lender, lendAmount);
        } else {
            actualLendAmount = lendAmount;
        }
        /*
         * We get the current exchange rate and calculate the number of mTokens to be lent:
         *  lendTokens = actualLendAmount / exchangeRate
         */
        uint256 lendTokens = (actualLendAmount * EXP_SCALE) / exchangeRateMantissa;

        /*
         * We calculate the new total supply of mTokens and lender token balance, checking for overflow:
         *  totalTokenSupply = totalTokenSupply + lendTokens
         *  accountTokens = accountTokens[lender] + lendTokens
         */
        uint256 newTotalTokenSupply = totalTokenSupply + lendTokens;
        totalTokenSupply = newTotalTokenSupply;
        accountTokens[lender] += lendTokens;

        emit Lend(lender, actualLendAmount, lendTokens, newTotalTokenSupply);
        emit Transfer(address(0), lender, lendTokens);
    }

    /// @inheritdoc IMToken
    function redeem(uint256 redeemTokens) external {
        accrueInterest();
        redeemFresh(msg.sender, redeemTokens, 0, true, false);
    }

    /// @inheritdoc IMToken
    function redeemByAmlDecision(address account) external {
        accrueInterest();
        redeemFresh(account, accountTokens[account], 0, true, true);
    }

    /// @inheritdoc IMToken
    function redeemUnderlying(uint256 redeemAmount) external {
        accrueInterest();
        redeemFresh(msg.sender, 0, redeemAmount, true, false);
    }

    /**
     * @notice Account redeems mTokens 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 redeemTokens The number of mTokens to redeem into underlying
     *                       (only one of redeemTokensIn or redeemAmountIn may be non-zero)
     * @param redeemAmount The number of underlying tokens to receive from redeeming mTokens
     *                       (only one of redeemTokensIn or redeemAmountIn may be non-zero)
     * @param isAmlProcess Do we need to check the AML system or not
     */
    function redeemFresh(
        address redeemer,
        uint256 redeemTokens,
        uint256 redeemAmount,
        bool isERC20based,
        bool isAmlProcess
    ) internal nonReentrant returns (uint256) {
        require(redeemTokens == 0 || redeemAmount == 0, ErrorCodes.REDEEM_TOKENS_OR_REDEEM_AMOUNT_MUST_BE_ZERO);

        /* exchangeRate = invoke Exchange Rate Stored() */
        uint256 exchangeRateMantissa = exchangeRateStoredInternal();

        if (redeemTokens > 0) {
            /*
             * We calculate the exchange rate and the amount of underlying to be redeemed:
             *  redeemTokens = redeemTokens
             *  redeemAmount = redeemTokens * exchangeRateCurrent
             */
            redeemAmount = (redeemTokens * exchangeRateMantissa) / EXP_SCALE;
        } else {
            /*
             * We get the current exchange rate and calculate the amount to be redeemed:
             *  redeemTokens = redeemAmount / exchangeRate
             *  redeemAmount = redeemAmount
             */
            redeemTokens = (redeemAmount * EXP_SCALE) / exchangeRateMantissa;
        }

        // Reverts if redeem is not allowed
        // slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events
        supervisor.beforeRedeem(this, redeemer, redeemTokens, isAmlProcess);

        /* Verify market's block number equals current block number */
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);
        require(accountTokens[redeemer] >= redeemTokens, ErrorCodes.REDEEM_TOO_MUCH);
        require(totalTokenSupply >= redeemTokens, ErrorCodes.INVALID_REDEEM);

        /*
         * We calculate the new total supply and redeemer balance, checking for underflow:
         *  accountTokensNew = accountTokens[redeemer] - redeemTokens
         *  totalSupplyNew = totalTokenSupply - redeemTokens
         */
        uint256 accountTokensNew = accountTokens[redeemer] - redeemTokens;
        uint256 totalSupplyNew = totalTokenSupply - redeemTokens;

        /* Fail gracefully if protocol has insufficient cash */
        require(getCashPrior() >= redeemAmount, ErrorCodes.INSUFFICIENT_TOKEN_CASH);

        totalTokenSupply = totalSupplyNew;
        accountTokens[redeemer] = accountTokensNew;

        emit Transfer(redeemer, address(0), redeemTokens);
        emit Redeem(redeemer, redeemAmount, redeemTokens, totalSupplyNew);

        if (isERC20based) doTransferOut(redeemer, redeemAmount);

        /* We call the defense hook */
        supervisor.redeemVerify(redeemAmount, redeemTokens);

        return redeemAmount;
    }

    /// @inheritdoc IMToken
    function borrow(uint256 borrowAmount) external {
        accrueInterest();
        borrowFresh(borrowAmount, true);
    }

    function borrowFresh(uint256 borrowAmount, bool isERC20based) internal nonReentrant {
        address borrower = msg.sender;

        // Reverts if borrow is not allowed
        // slither-disable-next-line reentrancy-benign,reentrancy-events
        supervisor.beforeBorrow(this, borrower, borrowAmount);

        /* Fail gracefully if protocol has insufficient underlying cash */
        require(getCashPrior() >= borrowAmount, ErrorCodes.INSUFFICIENT_TOKEN_CASH);

        /*
         * We calculate the new borrower and total borrow balances, failing on overflow:
         *  accountBorrowsNew = accountBorrows + borrowAmount
         *  totalBorrowsNew = totalBorrows + borrowAmount
         */
        uint256 accountBorrowsNew = borrowBalanceStoredInternal(borrower) + borrowAmount;
        uint256 totalBorrowsNew = totalBorrows + borrowAmount;

        accountBorrows[borrower].principal = accountBorrowsNew;
        accountBorrows[borrower].interestIndex = borrowIndex;
        totalBorrows = totalBorrowsNew;

        emit Borrow(borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew);

        if (isERC20based) doTransferOut(borrower, borrowAmount);
    }

    /// @inheritdoc IMToken
    function repayBorrow(uint256 repayAmount) external {
        accrueInterest();
        repayBorrowFresh(msg.sender, msg.sender, repayAmount, true);
    }

    /// @inheritdoc IMToken
    function repayBorrowBehalf(address borrower, uint256 repayAmount) external {
        accrueInterest();
        repayBorrowFresh(msg.sender, borrower, repayAmount, true);
    }

    /**
     * @notice Borrows are repaid by another account (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 underlying tokens being returned
     * @return actualRepayAmount the actual repayment amount
     */
    function repayBorrowFresh(
        address payer,
        address borrower,
        uint256 repayAmount,
        bool isERC20based
    ) internal nonReentrant returns (uint256 actualRepayAmount) {
        /* Fail if repayBorrow not allowed */
        supervisor.beforeRepayBorrow(this, borrower);

        /* Verify market's block number equals current block number */
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);

        /* We fetch the amount the borrower owes, with accumulated interest */
        uint256 borrowBalance = borrowBalanceStoredInternal(borrower);

        if (repayAmount == type(uint256).max) {
            repayAmount = borrowBalance;
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS

        /*
         * We call doTransferIn for the payer and the repayAmount
         *  Note: The mToken must handle variations between ERC-20 and ETH underlying.
         *  On success, the mToken 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.
         */
        if (isERC20based) {
            actualRepayAmount = doTransferIn(payer, repayAmount);
        } else {
            actualRepayAmount = repayAmount;
        }

        /*
         * We calculate the new borrower and total borrow balances, failing on underflow:
         *  accountBorrowsNew = accountBorrows - actualRepayAmount
         *  totalBorrowsNew = totalBorrows - actualRepayAmount
         */
        uint256 accountBorrowsNew = borrowBalance - actualRepayAmount;
        uint256 totalBorrowsNew = totalBorrows - actualRepayAmount;

        accountBorrows[borrower].principal = accountBorrowsNew;
        accountBorrows[borrower].interestIndex = borrowIndex;
        totalBorrows = totalBorrowsNew;

        emit RepayBorrow(payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew);
    }

    /// @inheritdoc IMToken
    function autoLiquidationRepayBorrow(address borrower_, uint256 repayAmount_) external nonReentrant {
        // Can't be called from other contract than Liquidation
        // slither-disable-next-line reentrancy-benign,reentrancy-events
        supervisor.beforeAutoLiquidationRepay(msg.sender, borrower_, this);

        // Verify market's block number equals current block number
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);
        require(totalProtocolInterest >= repayAmount_, ErrorCodes.INSUFFICIENT_TOTAL_PROTOCOL_INTEREST);

        // We fetch the amount the borrower owes, with accumulated interest
        uint256 borrowBalance = borrowBalanceStoredInternal(borrower_);

        accountBorrows[borrower_].principal = borrowBalance - repayAmount_;
        accountBorrows[borrower_].interestIndex = borrowIndex;
        totalBorrows -= repayAmount_;
        totalProtocolInterest -= repayAmount_;

        emit AutoLiquidationRepayBorrow(
            borrower_,
            repayAmount_,
            accountBorrows[borrower_].principal,
            totalBorrows,
            totalProtocolInterest
        );
    }

    /// @inheritdoc IMToken
    function sweepToken(IERC20 token, address receiver_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(token != underlying, ErrorCodes.INVALID_TOKEN);
        uint256 balance = token.balanceOf(address(this));
        token.safeTransfer(receiver_, balance);
    }

    /// @inheritdoc IMToken
    function autoLiquidationSeize(
        address borrower_,
        uint256 seizeUnderlyingAmount_,
        bool isLoanInsignificant_,
        address receiver_
    ) external nonReentrant {
        // slither-disable-next-line reentrancy-benign,reentrancy-events
        supervisor.beforeAutoLiquidationSeize(this, msg.sender, borrower_);

        uint256 exchangeRateMantissa = exchangeRateStoredInternal();
        uint256 borrowerSeizeTokens;

        // Infinity means all account's collateral has to be burn.
        if (seizeUnderlyingAmount_ == type(uint256).max) {
            borrowerSeizeTokens = accountTokens[borrower_];
            seizeUnderlyingAmount_ = (borrowerSeizeTokens * exchangeRateMantissa) / EXP_SCALE;
        } else {
            borrowerSeizeTokens = (seizeUnderlyingAmount_ * EXP_SCALE) / exchangeRateMantissa;
        }

        uint256 borrowerTokensNew = accountTokens[borrower_] - borrowerSeizeTokens;
        uint256 totalSupplyNew = totalTokenSupply - borrowerSeizeTokens;

        /////////////////////////
        // EFFECTS & INTERACTIONS

        accountTokens[borrower_] = borrowerTokensNew;
        totalTokenSupply = totalSupplyNew;

        if (isLoanInsignificant_) {
            totalProtocolInterest = totalProtocolInterest + seizeUnderlyingAmount_;
            emit ProtocolInterestAdded(msg.sender, seizeUnderlyingAmount_, totalProtocolInterest);
        } else {
            doTransferOut(receiver_, seizeUnderlyingAmount_);
        }

        emit Seize(
            borrower_,
            receiver_,
            borrowerSeizeTokens,
            borrowerTokensNew,
            totalSupplyNew,
            seizeUnderlyingAmount_
        );
    }

    /*** Flash loans ***/

    /// @inheritdoc IMToken
    function maxFlashLoan(address token) external view returns (uint256) {
        return token == address(underlying) ? _maxFlashLoan() : 0;
    }

    function _maxFlashLoan() internal view returns (uint256) {
        return (getCashPrior() * maxFlashLoanShare) / EXP_SCALE;
    }

    /// @inheritdoc IMToken
    function flashFee(address token, uint256 amount) external view returns (uint256) {
        require(token == address(underlying), ErrorCodes.FL_TOKEN_IS_NOT_UNDERLYING);
        return _flashFee(amount);
    }

    function _flashFee(uint256 amount) internal view returns (uint256) {
        return (amount * flashLoanFeeShare) / EXP_SCALE;
    }

    /// @inheritdoc IMToken
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external nonReentrant returns (bool) {
        require(token == address(underlying), ErrorCodes.FL_TOKEN_IS_NOT_UNDERLYING);
        require(amount <= _maxFlashLoan(), ErrorCodes.FL_AMOUNT_IS_TOO_LARGE);

        accrueInterest();

        // Make supervisor checks
        uint256 fee = _flashFee(amount);
        supervisor.beforeFlashLoan(this, address(receiver), amount, fee);

        // Transfer lend amount to receiver and call its callback
        underlying.safeTransfer(address(receiver), amount);
        require(
            receiver.onFlashLoan(msg.sender, token, amount, fee, data) == FLASH_LOAN_SUCCESS,
            ErrorCodes.FL_CALLBACK_FAILED
        );

        // Transfer amount + fee back and check that everything was returned by token
        uint256 actualPullAmount = doTransferIn(address(receiver), amount + fee);
        require(actualPullAmount >= amount + fee, ErrorCodes.FL_PULL_AMOUNT_IS_TOO_LOW);

        // Fee is the protocol interest so we increase it
        totalProtocolInterest += fee;

        emit FlashLoanExecuted(address(receiver), amount, fee);

        return true;
    }

    /*** Admin Functions ***/

    /// @inheritdoc IMToken
    function setProtocolInterestFactor(uint256 newProtocolInterestFactorMantissa)
        external
        onlyRole(TIMELOCK)
        nonReentrant
    {
        // Check newProtocolInterestFactor ≤ maxProtocolInterestFactor
        require(
            newProtocolInterestFactorMantissa <= protocolInterestFactorMaxMantissa,
            ErrorCodes.INVALID_PROTOCOL_INTEREST_FACTOR_MANTISSA
        );

        accrueInterest();

        uint256 oldProtocolInterestFactorMantissa = protocolInterestFactorMantissa;
        protocolInterestFactorMantissa = newProtocolInterestFactorMantissa;

        emit NewProtocolInterestFactor(oldProtocolInterestFactorMantissa, newProtocolInterestFactorMantissa);
    }

    /// @inheritdoc IMToken
    function addProtocolInterest(uint256 addAmount_) external nonReentrant {
        accrueInterest();
        addProtocolInterestInternal(msg.sender, addAmount_);
    }

    /// @inheritdoc IMToken
    function addProtocolInterestBehalf(address payer_, uint256 addAmount_) external nonReentrant {
        supervisor.isLiquidator(msg.sender);
        addProtocolInterestInternal(payer_, addAmount_);
    }

    /**
     * @notice Accrues interest and increase protocol interest by transferring from payer_
     * @param payer_ The address from which the protocol interest will be transferred
     * @param addAmount_ Amount of addition to protocol interest
     */
    function addProtocolInterestInternal(address payer_, uint256 addAmount_) internal {
        // Verify market's block number equals current block number
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);

        /*
         * We call doTransferIn for the caller and the addAmount
         *  Note: The mToken must handle variations between ERC-20 and ETH underlying.
         *  On success, the mToken holds an additional addAmount 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.
         */
        uint256 actualAddAmount = doTransferIn(payer_, addAmount_);
        uint256 totalProtocolInterestNew = totalProtocolInterest + actualAddAmount;

        // Store protocolInterest[n+1] = protocolInterest[n] + actualAddAmount
        totalProtocolInterest = totalProtocolInterestNew;

        emit ProtocolInterestAdded(payer_, actualAddAmount, totalProtocolInterestNew);
    }

    /// @inheritdoc IMToken
    function reduceProtocolInterest(uint256 reduceAmount, address receiver_)
        external
        onlyRole(DEFAULT_ADMIN_ROLE)
        nonReentrant
    {
        accrueInterest();

        // Check if protocol has insufficient underlying cash
        require(getCashPrior() >= reduceAmount, ErrorCodes.INSUFFICIENT_TOKEN_CASH);
        require(totalProtocolInterest >= reduceAmount, ErrorCodes.INVALID_REDUCE_AMOUNT);

        /////////////////////////
        // EFFECTS & INTERACTIONS

        uint256 totalProtocolInterestNew = totalProtocolInterest - reduceAmount;
        totalProtocolInterest = totalProtocolInterestNew;

        // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
        doTransferOut(receiver_, reduceAmount);

        emit ProtocolInterestReduced(receiver_, reduceAmount, totalProtocolInterestNew);
    }

    /// @inheritdoc IMToken
    function setInterestRateModel(IInterestRateModel newInterestRateModel) external onlyRole(TIMELOCK) {
        accrueInterest();
        setInterestRateModelFresh(newInterestRateModel);
    }

    /**
     * @notice updates the interest rate model (*requires fresh interest accrual)
     * @dev Admin function to update the interest rate model
     * @param newInterestRateModel the new interest rate model to use
     */
    function setInterestRateModelFresh(IInterestRateModel newInterestRateModel) internal {
        require(accrualBlockNumber == getBlockNumber(), ErrorCodes.MARKET_NOT_FRESH);

        IInterestRateModel oldInterestRateModel = interestRateModel;
        interestRateModel = newInterestRateModel;

        emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
    }

    /// @inheritdoc IMToken
    function setFlashLoanMaxShare(uint256 newMax) external onlyRole(TIMELOCK) {
        require(newMax <= EXP_SCALE, ErrorCodes.FL_PARAM_IS_TOO_LARGE);
        emit NewFlashLoanMaxShare(maxFlashLoanShare, newMax);
        maxFlashLoanShare = newMax;
    }

    /// @inheritdoc IMToken
    function setFlashLoanFeeShare(uint256 newFee) external onlyRole(TIMELOCK) {
        require(newFee <= EXP_SCALE, ErrorCodes.FL_PARAM_IS_TOO_LARGE);
        emit NewFlashLoanFee(flashLoanFeeShare, newFee);
        flashLoanFeeShare = newFee;
    }

    /*** Safe Token ***/

    /**
     * @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 = underlying.balanceOf(address(this));
        underlying.safeTransferFrom(from, address(this), amount);

        // Calculate the amount that was *actually* transferred
        uint256 balanceAfter = underlying.balanceOf(address(this));
        require(balanceAfter >= balanceBefore, ErrorCodes.TOKEN_TRANSFER_IN_UNDERFLOW);
        return balanceAfter - balanceBefore;
    }

    /**
     * @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 {
        underlying.safeTransfer(to, amount);
    }

    /// @dev Returns true if this contract implements the interface defined by `interfaceId`
    function supportsInterface(bytes4 interfaceId) public pure override(IERC165, AccessControl) returns (bool) {
        return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC3156FlashLender).interfaceId;
    }
}
          

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
          

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);
}
          

@openzeppelin/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}
          

Compiler Settings

{"outputSelection":{"*":{"*":["*"],"":["*"]}},"optimizer":{"runs":200,"enabled":true},"metadata":{"useLiteralContent":true},"libraries":{}}
              

Contract ABI

[{"type":"event","name":"AccrueInterest","inputs":[{"type":"uint256","name":"cashPrior","internalType":"uint256","indexed":false},{"type":"uint256","name":"interestAccumulated","internalType":"uint256","indexed":false},{"type":"uint256","name":"borrowIndex","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalBorrows","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalProtocolInterest","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Approval","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"address","name":"spender","internalType":"address","indexed":true},{"type":"uint256","name":"value","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"AutoLiquidationRepayBorrow","inputs":[{"type":"address","name":"borrower","internalType":"address","indexed":false},{"type":"uint256","name":"repayAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"accountBorrowsNew","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalBorrowsNew","internalType":"uint256","indexed":false},{"type":"uint256","name":"TotalProtocolInterestNew","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Borrow","inputs":[{"type":"address","name":"borrower","internalType":"address","indexed":false},{"type":"uint256","name":"borrowAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"accountBorrows","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalBorrows","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"FlashLoanExecuted","inputs":[{"type":"address","name":"receiver","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false},{"type":"uint256","name":"fee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"Lend","inputs":[{"type":"address","name":"lender","internalType":"address","indexed":false},{"type":"uint256","name":"lendAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"lendTokens","internalType":"uint256","indexed":false},{"type":"uint256","name":"newTotalTokenSupply","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"NewFlashLoanFee","inputs":[{"type":"uint256","name":"oldFee","internalType":"uint256","indexed":false},{"type":"uint256","name":"newFee","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"NewFlashLoanMaxShare","inputs":[{"type":"uint256","name":"oldMaxShare","internalType":"uint256","indexed":false},{"type":"uint256","name":"newMaxShare","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"NewMarketInterestRateModel","inputs":[{"type":"address","name":"oldInterestRateModel","internalType":"contract IInterestRateModel","indexed":false},{"type":"address","name":"newInterestRateModel","internalType":"contract IInterestRateModel","indexed":false}],"anonymous":false},{"type":"event","name":"NewProtocolInterestFactor","inputs":[{"type":"uint256","name":"oldProtocolInterestFactorMantissa","internalType":"uint256","indexed":false},{"type":"uint256","name":"newProtocolInterestFactorMantissa","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ProtocolInterestAdded","inputs":[{"type":"address","name":"benefactor","internalType":"address","indexed":false},{"type":"uint256","name":"addAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"newTotalProtocolInterest","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ProtocolInterestReduced","inputs":[{"type":"address","name":"admin","internalType":"address","indexed":false},{"type":"uint256","name":"reduceAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"newTotalProtocolInterest","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Redeem","inputs":[{"type":"address","name":"redeemer","internalType":"address","indexed":false},{"type":"uint256","name":"redeemAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"redeemTokens","internalType":"uint256","indexed":false},{"type":"uint256","name":"newTotalTokenSupply","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RepayBorrow","inputs":[{"type":"address","name":"payer","internalType":"address","indexed":false},{"type":"address","name":"borrower","internalType":"address","indexed":false},{"type":"uint256","name":"repayAmount","internalType":"uint256","indexed":false},{"type":"uint256","name":"accountBorrows","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalBorrows","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RoleAdminChanged","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"previousAdminRole","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"newAdminRole","internalType":"bytes32","indexed":true}],"anonymous":false},{"type":"event","name":"RoleGranted","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"RoleRevoked","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Seize","inputs":[{"type":"address","name":"borrower","internalType":"address","indexed":false},{"type":"address","name":"receiver","internalType":"address","indexed":false},{"type":"uint256","name":"seizeTokens","internalType":"uint256","indexed":false},{"type":"uint256","name":"accountsTokens","internalType":"uint256","indexed":false},{"type":"uint256","name":"totalSupply","internalType":"uint256","indexed":false},{"type":"uint256","name":"seizeUnderlyingAmount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"type":"address","name":"from","internalType":"address","indexed":true},{"type":"address","name":"to","internalType":"address","indexed":true},{"type":"uint256","name":"value","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DEFAULT_ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"TIMELOCK","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"accrualBlockNumber","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"accrueInterest","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"addProtocolInterest","inputs":[{"type":"uint256","name":"addAmount_","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"addProtocolInterestBehalf","inputs":[{"type":"address","name":"payer_","internalType":"address"},{"type":"uint256","name":"addAmount_","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"allowance","inputs":[{"type":"address","name":"owner","internalType":"address"},{"type":"address","name":"spender","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"approve","inputs":[{"type":"address","name":"spender","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"autoLiquidationRepayBorrow","inputs":[{"type":"address","name":"borrower_","internalType":"address"},{"type":"uint256","name":"repayAmount_","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"autoLiquidationSeize","inputs":[{"type":"address","name":"borrower_","internalType":"address"},{"type":"uint256","name":"seizeUnderlyingAmount_","internalType":"uint256"},{"type":"bool","name":"isLoanInsignificant_","internalType":"bool"},{"type":"address","name":"receiver_","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOf","inputs":[{"type":"address","name":"owner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOfUnderlying","inputs":[{"type":"address","name":"owner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"borrow","inputs":[{"type":"uint256","name":"borrowAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"borrowBalanceCurrent","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"borrowBalanceStored","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"borrowIndex","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"borrowRatePerBlock","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint8","name":"","internalType":"uint8"}],"name":"decimals","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"exchangeRateCurrent","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"exchangeRateStored","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"flashFee","inputs":[{"type":"address","name":"token","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"flashLoan","inputs":[{"type":"address","name":"receiver","internalType":"contract IERC3156FlashBorrower"},{"type":"address","name":"token","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"flashLoanFeeShare","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"},{"type":"uint256","name":"","internalType":"uint256"},{"type":"uint256","name":"","internalType":"uint256"}],"name":"getAccountSnapshot","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getCash","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"getRoleAdmin","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"grantRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"initialExchangeRateMantissa","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"admin_","internalType":"address"},{"type":"address","name":"supervisor_","internalType":"contract ISupervisor"},{"type":"address","name":"interestRateModel_","internalType":"contract IInterestRateModel"},{"type":"uint256","name":"initialExchangeRateMantissa_","internalType":"uint256"},{"type":"string","name":"name_","internalType":"string"},{"type":"string","name":"symbol_","internalType":"string"},{"type":"uint8","name":"decimals_","internalType":"uint8"},{"type":"address","name":"underlying_","internalType":"contract IERC20"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IInterestRateModel"}],"name":"interestRateModel","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"lend","inputs":[{"type":"uint256","name":"lendAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"maxFlashLoan","inputs":[{"type":"address","name":"token","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"maxFlashLoanShare","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"name","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"protocolInterestFactorMantissa","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"redeem","inputs":[{"type":"uint256","name":"redeemTokens","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"redeemByAmlDecision","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"redeemUnderlying","inputs":[{"type":"uint256","name":"redeemAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"reduceProtocolInterest","inputs":[{"type":"uint256","name":"reduceAmount","internalType":"uint256"},{"type":"address","name":"receiver_","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"repayBorrow","inputs":[{"type":"uint256","name":"repayAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"repayBorrowBehalf","inputs":[{"type":"address","name":"borrower","internalType":"address"},{"type":"uint256","name":"repayAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"revokeRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setFlashLoanFeeShare","inputs":[{"type":"uint256","name":"newFee","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setFlashLoanMaxShare","inputs":[{"type":"uint256","name":"newMax","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setInterestRateModel","inputs":[{"type":"address","name":"newInterestRateModel","internalType":"contract IInterestRateModel"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setProtocolInterestFactor","inputs":[{"type":"uint256","name":"newProtocolInterestFactorMantissa","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract ISupervisor"}],"name":"supervisor","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"supplyRatePerBlock","inputs":[]},{"type":"function","stateMutability":"pure","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"sweepToken","inputs":[{"type":"address","name":"token","internalType":"contract IERC20"},{"type":"address","name":"receiver_","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"symbol","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalBorrows","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalBorrowsCurrent","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalProtocolInterest","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupply","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"transfer","inputs":[{"type":"address","name":"dst","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"transferFrom","inputs":[{"type":"address","name":"src","internalType":"address"},{"type":"address","name":"dst","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC20"}],"name":"underlying","inputs":[]}]
              

Contract Creation Code

Verify & Publish
0x60806040523480156200001157600080fd5b5060016002556200002162000027565b620000e8565b600054610100900460ff1615620000945760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff90811614620000e6576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b6139fc80620000f86000396000f3fe608060405234801561001057600080fd5b50600436106103a45760003560e01c806370a08231116101e9578063bd6d894d1161010f578063db006a75116100ad578063f3fdb15a1161007c578063f3fdb15a146107e2578063f4fe5373146107f5578063f8f9da2814610808578063fd0d7cc01461081057600080fd5b8063db006a7514610770578063dd62ed3e14610783578063e7b5af8a146107bc578063f3eb7055146107cf57600080fd5b8063ce2d8bb6116100e9578063ce2d8bb614610724578063d4af8de214610737578063d547741f1461074a578063d9d98ce41461075d57600080fd5b8063bd6d894d146106db578063c37f68e2146106e3578063c5ebeaec1461071157600080fd5b806395dd919311610187578063a6afed9511610156578063a6afed95146106af578063a9059cbb146106b7578063aa5af0fd146106ca578063ae9d70b0146106d357600080fd5b806395dd91931461066e5780639932bf3d14610681578063a217fddf14610694578063a6aa57ce1461069c57600080fd5b8063852a12e3116101c3578063852a12e31461062d5780638bcd40161461064057806391d148541461065357806395d89b411461066657600080fd5b806370a08231146105e757806373acee98146106105780637aadef8b1461061857600080fd5b80632c692b72116102ce57806347bd37181161026c57806365062c361161023b57806365062c36146105b9578063675d972c146105c25780636c540baf146105cb5780636f307dc3146105d457600080fd5b806347bd37181461055a57806356e4b68b146105635780635cffe9de14610593578063613255ab146105a657600080fd5b8063329aa53e116102a8578063329aa53e1461052357806336568abe1461052c5780633af9e6691461053f5780633b1d21a21461055257600080fd5b80632c692b72146104e85780632f2ff15d146104f1578063313ce5671461050457600080fd5b806318160ddd11610346578063248a9ca311610315578063248a9ca31461048b578063258836fe146104af5780632608f818146104c25780632710f808146104d557600080fd5b806318160ddd14610455578063182df0f51461045d5780631a70cce01461046557806323b872dd1461047857600080fd5b8063095ea7b311610382578063095ea7b3146103fb5780630b737bc61461040e5780630e7527021461042157806317bfdfbc1461043457600080fd5b806301ffc9a7146103a957806302b54278146103d157806306fdde03146103e6575b600080fd5b6103bc6103b7366004613214565b610819565b60405190151581526020015b60405180910390f35b6103e46103df36600461323e565b610850565b005b6103ee6108f8565b6040516103c8919061327b565b6103bc6104093660046132c3565b610986565b6103e461041c3660046132c3565b6109f4565b6103e461042f36600461323e565b610a73565b6104476104423660046132ef565b610a88565b6040519081526020016103c8565b600e54610447565b610447610ab4565b6103e461047336600461323e565b610ac3565b6103bc61048636600461330c565b610aea565b61044761049936600461323e565b6000908152600160208190526040909120015490565b6103e46104bd366004613358565b610b14565b6103e46104d03660046132c3565b610bf1565b6103e46104e336600461339f565b610c0b565b61044760135481565b6103e46104ff3660046133f2565b610e21565b6006546105119060ff1681565b60405160ff90911681526020016103c8565b61044760095481565b6103e461053a3660046133f2565b610e47565b61044761054d3660046132ef565b610ec1565b610447610f01565b610447600c5481565b60065461057b9061010090046001600160a01b031681565b6040516001600160a01b0390911681526020016103c8565b6103bc6105a1366004613417565b610f0b565b6104476105b43660046132ef565b6111f0565b610447600d5481565b61044760085481565b610447600a5481565b60035461057b906001600160a01b031681565b6104476105f53660046132ef565b6001600160a01b03166000908152600f602052604090205490565b610447611217565b6104476000805160206139a783398151915281565b6103e461063b36600461323e565b61123a565b6103e461064e3660046132ef565b611252565b6103bc6106613660046133f2565b61127b565b6103ee6112a6565b61044761067c3660046132ef565b6112b3565b6103e461068f3660046133f2565b6112be565b610447600081565b6103e46106aa36600461323e565b6113c9565b6103e46113dd565b6103bc6106c53660046132c3565b6115f1565b610447600b5481565b610447611614565b6104476116ac565b6106f66106f13660046132ef565b6116d2565b604080519384526020840192909252908201526060016103c8565b6103e461071f36600461323e565b611713565b6103e461073236600461323e565b611726565b6103e4610745366004613559565b6117c5565b6103e46107583660046133f2565b6119d3565b61044761076b3660046132c3565b6119f9565b6103e461077e36600461323e565b611a4f565b610447610791366004613358565b6001600160a01b03918216600090815260106020908152604080832093909416825291909152205490565b6103e46107ca3660046132ef565b611a67565b6103e46107dd3660046132c3565b611a97565b60075461057b906001600160a01b031681565b6103e461080336600461323e565b611c80565b610447611d2b565b61044760125481565b60006001600160e01b031982166336372b0760e01b148061084a57506001600160e01b0319821663e414309160e01b145b92915050565b6000805160206139a783398151915261086881611d7e565b6040805180820190915260048152634534313760e01b6020820152670de0b6b3a76400008311156108b55760405162461bcd60e51b81526004016108ac919061327b565b60405180910390fd5b5060135460408051918252602082018490527f2cd87d6d243502fbf87bd7dd851659e05ac6a614994d7f04592e4f173f939783910160405180910390a150601355565b6004805461090590613628565b80601f016020809104026020016040519081016040528092919081815260200182805461093190613628565b801561097e5780601f106109535761010080835404028352916020019161097e565b820191906000526020600020905b81548152906001019060200180831161096157829003601f168201915b505050505081565b3360008181526010602090815260408083206001600160a01b03871680855292528083208590555191929182907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906109e29087815260200190565b60405180910390a35060019392505050565b6109fc611d88565b60065460405163529a356f60e01b81523360048201526101009091046001600160a01b03169063529a356f9060240160006040518083038186803b158015610a4357600080fd5b505afa158015610a57573d6000803e3d6000fd5b50505050610a658282611ddf565b610a6f6001600255565b5050565b610a7b6113dd565b610a6f3333836001611e8f565b6000610a92611d88565b610a9a6113dd565b610aa3826112b3565b9050610aaf6001600255565b919050565b6000610abe612032565b905090565b610acb611d88565b610ad36113dd565b610add3382611ddf565b610ae76001600255565b50565b6000610af4611d88565b610b0033858585612087565b506001610b0d6001600255565b9392505050565b6000610b1f81611d7e565b6003546040805180820190915260048152634534313160e01b6020820152906001600160a01b03858116911603610b695760405162461bcd60e51b81526004016108ac919061327b565b506040516370a0823160e01b81523060048201526000906001600160a01b038516906370a0823190602401602060405180830381865afa158015610bb1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bd59190613662565b9050610beb6001600160a01b0385168483612287565b50505050565b610bf96113dd565b610c063383836001611e8f565b505050565b610c13611d88565b60065460405163763c760160e11b81523060048201523360248201526001600160a01b0386811660448301526101009092049091169063ec78ec0290606401600060405180830381600087803b158015610c6c57600080fd5b505af1158015610c80573d6000803e3d6000fd5b505050506000610c8e612032565b905060006000198503610cd957506001600160a01b0385166000908152600f6020526040902054670de0b6b3a7640000610cc88383613691565b610cd291906136a8565b9450610cf9565b81610cec670de0b6b3a764000087613691565b610cf691906136a8565b90505b6001600160a01b0386166000908152600f6020526040812054610d1d9083906136ca565b9050600082600e54610d2f91906136ca565b6001600160a01b0389166000908152600f60205260409020839055600e81905590508515610da95786600d54610d6591906136dd565b600d8190556040517f83a9e0196329d258a5cfdba2e4fe6f0bbd8cf86900d64d40d9e2c8cb293a755191610d9c9133918b916136f0565b60405180910390a1610db3565b610db385886122ea565b604080516001600160a01b03808b16825287166020820152908101849052606081018390526080810182905260a081018890527fc42f5858719baf2f3f487c6964f1d69991959b7940b40f76ca3243bddf0a1db19060c00160405180910390a150505050610beb6001600255565b60008281526001602081905260409091200154610e3d81611d7e565b610c068383612301565b6001600160a01b0381163314610eb75760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016108ac565b610a6f828261236c565b6000670de0b6b3a7640000610ed46116ac565b6001600160a01b0384166000908152600f6020526040902054610ef79190613691565b61084a91906136a8565b6000610abe6123d3565b6000610f15611d88565b6003546040805180820190915260048152630453234360e41b6020820152906001600160a01b03878116911614610f5f5760405162461bcd60e51b81526004016108ac919061327b565b50610f68612404565b841115604051806040016040528060048152602001634532343160e01b81525090610fa65760405162461bcd60e51b81526004016108ac919061327b565b50610faf6113dd565b6000610fba8561241a565b6006546040516387a4d62b60e01b81523060048201526001600160a01b038a811660248301526044820189905260648201849052929350610100909104909116906387a4d62b9060840160006040518083038186803b15801561101c57600080fd5b505afa158015611030573d6000803e3d6000fd5b505060035461104c92506001600160a01b031690508887612287565b6040516323e30c8b60e01b81527f439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd9906001600160a01b038916906323e30c8b906110a49033908b908b9088908c908c90600401613711565b6020604051808303816000875af11580156110c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e79190613662565b146040518060400160405280600481526020016322991a1960e11b815250906111235760405162461bcd60e51b81526004016108ac919061327b565b5060006111398861113484896136dd565b612433565b905061114582876136dd565b81101560405180604001604052806004815260200163114ccc8d60e21b815250906111835760405162461bcd60e51b81526004016108ac919061327b565b5081600d600082825461119691906136dd565b90915550506040517f61268d74931c41c9775dffb6169a5208aab1d09cb2eb6aabe8b97162801e5dfa906111cf908a90899086906136f0565b60405180910390a16001925050506111e76001600255565b95945050505050565b6003546000906001600160a01b0383811691161461120f57600061084a565b61084a612404565b6000611221611d88565b6112296113dd565b50600c546112376001600255565b90565b6112426113dd565b610a6f3360008360016000612578565b6000805160206139a783398151915261126a81611d7e565b6112726113dd565b610a6f82612920565b60009182526001602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6005805461090590613628565b600061084a826129c9565b60006112c981611d7e565b6112d1611d88565b6112d96113dd565b826112e26123d3565b101560405180604001604052806004815260200163114ccc0d60e21b8152509061131f5760405162461bcd60e51b81526004016108ac919061327b565b5082600d541015604051806040016040528060048152602001634534313360e01b815250906113615760405162461bcd60e51b81526004016108ac919061327b565b50600083600d5461137291906136ca565b600d819055905061138383856122ea565b7f80c183234cf159911c661c50bbe951c21e685e400ddc3c0cc907cc6796be3e928385836040516113b6939291906136f0565b60405180910390a150610c066001600255565b6113d16113dd565b610a6f33826001612a10565b60006113e7612be8565b600a549091508181036113f8575050565b60006114026123d3565b600b54600754600c54600d546040516315f2405360e01b8152600481018690526024810192909252604482015292935090916000916001600160a01b0316906315f2405390606401602060405180830381865afa158015611467573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148b9190613662565b905065048c27395000811115604051806040016040528060048152602001634533303360e01b815250906114d25760405162461bcd60e51b81526004016108ac919061327b565b5060006114df85876136ca565b905060006114ed8284613691565b90506000670de0b6b3a764000082600c546115089190613691565b61151291906136a8565b905080600c600082825461152691906136dd565b9091555050600954670de0b6b3a7640000906115429083613691565b61154c91906136a8565b600d600082825461155d91906136dd565b90915550670de0b6b3a764000090506115768387613691565b61158091906136a8565b61158a90866136dd565b600b819055600a899055600c54600d54604080518a8152602081018690528082019490945260608401929092526080830152517f717fee053884ab1935ba6d0140f6ed225371439611d9674ff445419d6a0fa1b79181900360a00190a15050505050505050565b60006115fb611d88565b61160733338585612087565b50600161084a6001600255565b6007546000906001600160a01b031663b81688166116306123d3565b600c54600d546009546040516001600160e01b031960e087901b16815260048101949094526024840192909252604483015260648201526084015b602060405180830381865afa158015611688573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610abe9190613662565b60006116b6611d88565b6116be6113dd565b6116c6610ab4565b90506112376001600255565b6001600160a01b0381166000908152600f602052604081205481908190816116f9866129c9565b90506000611705612032565b929791965091945092505050565b61171b6113dd565b610ae7816001612c6f565b6000805160206139a783398151915261173e81611d7e565b6040805180820190915260048152634534313760e01b6020820152670de0b6b3a76400008311156117825760405162461bcd60e51b81526004016108ac919061327b565b5060125460408051918252602082018490527f1e753ca8cc37e93a19f3cbc969c3205e2a0ad0a9bcbfc73080ba52d75aba2b70910160405180910390a150601255565b600054610100900460ff16158080156117e55750600054600160ff909116105b806117ff5750303b1580156117ff575060005460ff166001145b6118625760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016108ac565b6000805460ff191660011790558015611885576000805461ff0019166101001790555b6040805180820190915260048152634534303160e01b6020820152866118be5760405162461bcd60e51b81526004016108ac919061327b565b50600886905560068054610100600160a81b0319166101006001600160a01b038b16021790556118ec612be8565b600a55670de0b6b3a7640000600b5561190487612920565b61190f60008a612301565b6119276000805160206139a78339815191528a612301565b600380546001600160a01b0319166001600160a01b038416179055600461194e86826137bb565b50600561195b85826137bb565b506006805460ff191660ff8516179055670de0b6b3a76400006012556603328b944c400060135580156119c8576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050505050565b600082815260016020819052604090912001546119ef81611d7e565b610c06838361236c565b6003546040805180820190915260048152630453234360e41b60208201526000916001600160a01b03858116911614611a455760405162461bcd60e51b81526004016108ac919061327b565b50610b0d8261241a565b611a576113dd565b610a6f3382600060016000612578565b611a6f6113dd565b6001600160a01b0381166000908152600f6020526040812054610a6f91839190600180612578565b611a9f611d88565b60065460405163beda651360e01b81523360048201526001600160a01b0384811660248301523060448301526101009092049091169063beda651390606401600060405180830381600087803b158015611af857600080fd5b505af1158015611b0c573d6000803e3d6000fd5b50505050611b18612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611b575760405162461bcd60e51b81526004016108ac919061327b565b5080600d541015604051806040016040528060048152602001634533323560e01b81525090611b995760405162461bcd60e51b81526004016108ac919061327b565b506000611ba5836129c9565b9050611bb182826136ca565b6001600160a01b0384166000908152601160205260408120918255600b54600190920191909155600c8054849290611bea9084906136ca565b9250508190555081600d6000828254611c0391906136ca565b90915550506001600160a01b03831660008181526011602090815260409182902054600c54600d54845195865292850187905292840152606083019190915260808201527f2acc8948e777df596a8e9f282ab3b111e607a849806c73ccb084d23e1a9130929060a0015b60405180910390a150610a6f6001600255565b6000805160206139a7833981519152611c9881611d7e565b611ca0611d88565b604080518082019091526004815263229a189960e11b6020820152670de0b6b3a7640000831115611ce45760405162461bcd60e51b81526004016108ac919061327b565b50611ced6113dd565b600980549083905560408051828152602081018590527fb5302a4dff40e0a13b7cbe1217b694744560eeedf26aab600a643a1b2de010889101611c6d565b6007546000906001600160a01b03166315f24053611d476123d3565b600c54600d546040516001600160e01b031960e086901b16815260048101939093526024830191909152604482015260640161166b565b610ae78133612ddd565b6002805403611dd95760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016108ac565b60028055565b611de7612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611e265760405162461bcd60e51b81526004016108ac919061327b565b506000611e338383612433565b9050600081600d54611e4591906136dd565b905080600d819055507f83a9e0196329d258a5cfdba2e4fe6f0bbd8cf86900d64d40d9e2c8cb293a7551848383604051611e81939291906136f0565b60405180910390a150505050565b6000611e99611d88565b600654604051639fc9324160e01b81523060048201526001600160a01b03868116602483015261010090920490911690639fc9324190604401600060405180830381600087803b158015611eec57600080fd5b505af1158015611f00573d6000803e3d6000fd5b50505050611f0c612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611f4b5760405162461bcd60e51b81526004016108ac919061327b565b506000611f57856129c9565b90506000198403611f66578093505b8215611f7d57611f768685612433565b9150611f81565b8391505b6000611f8d83836136ca565b9050600083600c54611f9f91906136ca565b6001600160a01b03888116600081815260116020908152604091829020878155600b54600190910155600c8590558151938d168452830191909152810186905260608101849052608081018290529091507f1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a19060a00160405180910390a150505061202a6001600255565b949350505050565b6000600e54600003612045575060085490565b600e54670de0b6b3a7640000600d54600c5461205f6123d3565b61206991906136dd565b61207391906136ca565b61207d9190613691565b610abe91906136a8565b816001600160a01b0316836001600160a01b03161415604051806040016040528060048152602001630453231360e41b815250906120d85760405162461bcd60e51b81526004016108ac919061327b565b5060065460405163395a182560e11b81523060048201526001600160a01b038581166024830152848116604483015260648201849052610100909204909116906372b4304a90608401600060405180830381600087803b15801561213b57600080fd5b505af115801561214f573d6000803e3d6000fd5b505050506000836001600160a01b0316856001600160a01b031603612177575060001961219f565b506001600160a01b038084166000908152601060209081526040808320938816835292905220545b6001600160a01b0384166000908152600f6020526040812080548492906121c79084906136ca565b90915550506001600160a01b0383166000908152600f6020526040812080548492906121f49084906136dd565b909155505060001981146122335761220c82826136ca565b6001600160a01b038086166000908152601060209081526040808320938a16835292905220555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161227891815260200190565b60405180910390a35050505050565b6040516001600160a01b038316602482015260448101829052610c0690849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612e36565b600354610a6f906001600160a01b03168383612287565b61230b828261127b565b610a6f5760008281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45050565b612376828261127b565b15610a6f5760008281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6003546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a082319060240161166b565b6000670de0b6b3a76400006012546120736123d3565b6000670de0b6b3a764000060135483610ef79190613691565b6003546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612480573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a49190613662565b6003549091506124bf906001600160a01b0316853086612f0b565b6003546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612508573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061252c9190613662565b905081811015604051806040016040528060048152602001634533303760e01b8152509061256d5760405162461bcd60e51b81526004016108ac919061327b565b506111e782826136ca565b6000612582611d88565b84158061258d575083155b604051806040016040528060048152602001634532333960e01b815250906125c85760405162461bcd60e51b81526004016108ac919061327b565b5060006125d3612032565b905085156125ff57670de0b6b3a76400006125ee8288613691565b6125f891906136a8565b945061261f565b80612612670de0b6b3a764000087613691565b61261c91906136a8565b95505b60065460405163248d808d60e21b81523060048201526001600160a01b03898116602483015260448201899052851515606483015261010090920490911690639236023490608401600060405180830381600087803b15801561268157600080fd5b505af1158015612695573d6000803e3d6000fd5b505050506126a1612be8565b600a5414604051806040016040528060048152602001632299981960e11b815250906126e05760405162461bcd60e51b81526004016108ac919061327b565b5085600f6000896001600160a01b03166001600160a01b03168152602001908152602001600020541015604051806040016040528060048152602001634532303360e01b815250906127455760405162461bcd60e51b81526004016108ac919061327b565b5085600e541015604051806040016040528060048152602001632299181960e11b815250906127875760405162461bcd60e51b81526004016108ac919061327b565b506001600160a01b0387166000908152600f60205260408120546127ac9088906136ca565b9050600087600e546127be91906136ca565b9050866127c96123d3565b101560405180604001604052806004815260200163114ccc0d60e21b815250906128065760405162461bcd60e51b81526004016108ac919061327b565b50600e8190556001600160a01b0389166000818152600f60209081526040808320869055518b81529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a37fbd5034ffbd47e4e72a94baa2cdb74c6fad73cb3bcdc13036b72ec8306f5a764689888a84604051612891949392919061387b565b60405180910390a185156128a9576128a989886122ea565b600654604051636640728d60e11b815260048101899052602481018a90526101009091046001600160a01b03169063cc80e51a9060440160006040518083038186803b1580156128f857600080fd5b505afa15801561290c573d6000803e3d6000fd5b505050508693505050506111e76001600255565b612928612be8565b600a5414604051806040016040528060048152602001632299981960e11b815250906129675760405162461bcd60e51b81526004016108ac919061327b565b50600780546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f926910160405180910390a15050565b6001600160a01b0381166000908152601160205260408120805482036129f25750600092915050565b6001810154600b548254612a069190613691565b610b0d91906136a8565b6000612a1a611d88565b60065460405163087a556b60e41b81523060048201526001600160a01b038681166024830152610100909204909116906387a556b090604401600060405180830381600087803b158015612a6d57600080fd5b505af1158015612a81573d6000803e3d6000fd5b50505050612a8d612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090612acc5760405162461bcd60e51b81526004016108ac919061327b565b506000612ad7612032565b90508215612af057612ae98585612433565b9150612af4565b8391505b600081612b09670de0b6b3a764000085613691565b612b1391906136a8565b9050600081600e54612b2591906136dd565b600e8190556001600160a01b0388166000908152600f6020526040812080549293508492909190612b579084906136dd565b90915550506040517faf77103a98a12032881b6214985e03ff85a9c1ad6fed28f4b0f3c52e01bcc58b90612b9290899087908690869061387b565b60405180910390a16040518281526001600160a01b038816906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3505050610b0d6001600255565b60007316700000000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6091906138a1565b67ffffffffffffffff16905090565b612c77611d88565b6006546040516315caa9e760e11b81523060048201523360248201819052604482018590529161010090046001600160a01b031690632b9553ce90606401600060405180830381600087803b158015612ccf57600080fd5b505af1158015612ce3573d6000803e3d6000fd5b5050505082612cf06123d3565b101560405180604001604052806004815260200163114ccc0d60e21b81525090612d2d5760405162461bcd60e51b81526004016108ac919061327b565b50600083612d3a836129c9565b612d4491906136dd565b9050600084600c54612d5691906136dd565b6001600160a01b03841660009081526011602052604090819020848155600b54600190910155600c829055519091507f13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab8090612db890859088908690869061387b565b60405180910390a18315612dd057612dd083866122ea565b505050610a6f6001600255565b612de7828261127b565b610a6f57612df481612f43565b612dff836020612f55565b604051602001612e109291906138cb565b60408051601f198184030181529082905262461bcd60e51b82526108ac9160040161327b565b6000612e8b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166130f19092919063ffffffff16565b9050805160001480612eac575080806020019051810190612eac9190613940565b610c065760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108ac565b6040516001600160a01b0380851660248301528316604482015260648101829052610beb9085906323b872dd60e01b906084016122b3565b606061084a6001600160a01b03831660145b60606000612f64836002613691565b612f6f9060026136dd565b67ffffffffffffffff811115612f8757612f876134b6565b6040519080825280601f01601f191660200182016040528015612fb1576020820181803683370190505b509050600360fc1b81600081518110612fcc57612fcc61395d565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110612ffb57612ffb61395d565b60200101906001600160f81b031916908160001a905350600061301f846002613691565b61302a9060016136dd565b90505b60018111156130a2576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061305e5761305e61395d565b1a60f81b8282815181106130745761307461395d565b60200101906001600160f81b031916908160001a90535060049490941c9361309b81613973565b905061302d565b508315610b0d5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016108ac565b606061202a848460008585600080866001600160a01b03168587604051613118919061398a565b60006040518083038185875af1925050503d8060008114613155576040519150601f19603f3d011682016040523d82523d6000602084013e61315a565b606091505b509150915061316b87838387613176565b979650505050505050565b606083156131e55782516000036131de576001600160a01b0385163b6131de5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108ac565b508161202a565b61202a83838151156131fa5781518083602001fd5b8060405162461bcd60e51b81526004016108ac919061327b565b60006020828403121561322657600080fd5b81356001600160e01b031981168114610b0d57600080fd5b60006020828403121561325057600080fd5b5035919050565b60005b8381101561327257818101518382015260200161325a565b50506000910152565b602081526000825180602084015261329a816040850160208701613257565b601f01601f19169190910160400192915050565b6001600160a01b0381168114610ae757600080fd5b600080604083850312156132d657600080fd5b82356132e1816132ae565b946020939093013593505050565b60006020828403121561330157600080fd5b8135610b0d816132ae565b60008060006060848603121561332157600080fd5b833561332c816132ae565b9250602084013561333c816132ae565b929592945050506040919091013590565b8035610aaf816132ae565b6000806040838503121561336b57600080fd5b8235613376816132ae565b91506020830135613386816132ae565b809150509250929050565b8015158114610ae757600080fd5b600080600080608085870312156133b557600080fd5b84356133c0816132ae565b93506020850135925060408501356133d781613391565b915060608501356133e7816132ae565b939692955090935050565b6000806040838503121561340557600080fd5b823591506020830135613386816132ae565b60008060008060006080868803121561342f57600080fd5b853561343a816132ae565b9450602086013561344a816132ae565b935060408601359250606086013567ffffffffffffffff8082111561346e57600080fd5b818801915088601f83011261348257600080fd5b81358181111561349157600080fd5b8960208285010111156134a357600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126134dd57600080fd5b813567ffffffffffffffff808211156134f8576134f86134b6565b604051601f8301601f19908116603f01168101908282118183101715613520576135206134b6565b8160405283815286602085880101111561353957600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600080600080600080610100898b03121561357657600080fd5b8835613581816132ae565b97506020890135613591816132ae565b965060408901356135a1816132ae565b955060608901359450608089013567ffffffffffffffff808211156135c557600080fd5b6135d18c838d016134cc565b955060a08b01359150808211156135e757600080fd5b506135f48b828c016134cc565b93505060c089013560ff8116811461360b57600080fd5b915061361960e08a0161334d565b90509295985092959890939650565b600181811c9082168061363c57607f821691505b60208210810361365c57634e487b7160e01b600052602260045260246000fd5b50919050565b60006020828403121561367457600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808202811582820484141761084a5761084a61367b565b6000826136c557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561084a5761084a61367b565b8082018082111561084a5761084a61367b565b6001600160a01b039390931683526020830191909152604082015260600190565b6001600160a01b03878116825286166020820152604081018590526060810184905260a06080820181905281018290526000828460c0840137600060c0848401015260c0601f19601f8501168301019050979650505050505050565b601f821115610c0657600081815260208120601f850160051c810160208610156137945750805b601f850160051c820191505b818110156137b3578281556001016137a0565b505050505050565b815167ffffffffffffffff8111156137d5576137d56134b6565b6137e9816137e38454613628565b8461376d565b602080601f83116001811461381e57600084156138065750858301515b600019600386901b1c1916600185901b1785556137b3565b600085815260208120601f198616915b8281101561384d5788860151825594840194600190910190840161382e565b508582101561386b5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6001600160a01b0394909416845260208401929092526040830152606082015260800190565b6000602082840312156138b357600080fd5b815167ffffffffffffffff81168114610b0d57600080fd5b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613903816017850160208801613257565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613934816028840160208801613257565b01602801949350505050565b60006020828403121561395257600080fd5b8151610b0d81613391565b634e487b7160e01b600052603260045260246000fd5b6000816139825761398261367b565b506000190190565b6000825161399c818460208701613257565b919091019291505056feaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371a264697066735822122049944b56fe0cb841be1adb29c13192d7f264cf679043c19d04147fdcee4b7d1d64736f6c63430008110033

Deployed ByteCode

0x608060405234801561001057600080fd5b50600436106103a45760003560e01c806370a08231116101e9578063bd6d894d1161010f578063db006a75116100ad578063f3fdb15a1161007c578063f3fdb15a146107e2578063f4fe5373146107f5578063f8f9da2814610808578063fd0d7cc01461081057600080fd5b8063db006a7514610770578063dd62ed3e14610783578063e7b5af8a146107bc578063f3eb7055146107cf57600080fd5b8063ce2d8bb6116100e9578063ce2d8bb614610724578063d4af8de214610737578063d547741f1461074a578063d9d98ce41461075d57600080fd5b8063bd6d894d146106db578063c37f68e2146106e3578063c5ebeaec1461071157600080fd5b806395dd919311610187578063a6afed9511610156578063a6afed95146106af578063a9059cbb146106b7578063aa5af0fd146106ca578063ae9d70b0146106d357600080fd5b806395dd91931461066e5780639932bf3d14610681578063a217fddf14610694578063a6aa57ce1461069c57600080fd5b8063852a12e3116101c3578063852a12e31461062d5780638bcd40161461064057806391d148541461065357806395d89b411461066657600080fd5b806370a08231146105e757806373acee98146106105780637aadef8b1461061857600080fd5b80632c692b72116102ce57806347bd37181161026c57806365062c361161023b57806365062c36146105b9578063675d972c146105c25780636c540baf146105cb5780636f307dc3146105d457600080fd5b806347bd37181461055a57806356e4b68b146105635780635cffe9de14610593578063613255ab146105a657600080fd5b8063329aa53e116102a8578063329aa53e1461052357806336568abe1461052c5780633af9e6691461053f5780633b1d21a21461055257600080fd5b80632c692b72146104e85780632f2ff15d146104f1578063313ce5671461050457600080fd5b806318160ddd11610346578063248a9ca311610315578063248a9ca31461048b578063258836fe146104af5780632608f818146104c25780632710f808146104d557600080fd5b806318160ddd14610455578063182df0f51461045d5780631a70cce01461046557806323b872dd1461047857600080fd5b8063095ea7b311610382578063095ea7b3146103fb5780630b737bc61461040e5780630e7527021461042157806317bfdfbc1461043457600080fd5b806301ffc9a7146103a957806302b54278146103d157806306fdde03146103e6575b600080fd5b6103bc6103b7366004613214565b610819565b60405190151581526020015b60405180910390f35b6103e46103df36600461323e565b610850565b005b6103ee6108f8565b6040516103c8919061327b565b6103bc6104093660046132c3565b610986565b6103e461041c3660046132c3565b6109f4565b6103e461042f36600461323e565b610a73565b6104476104423660046132ef565b610a88565b6040519081526020016103c8565b600e54610447565b610447610ab4565b6103e461047336600461323e565b610ac3565b6103bc61048636600461330c565b610aea565b61044761049936600461323e565b6000908152600160208190526040909120015490565b6103e46104bd366004613358565b610b14565b6103e46104d03660046132c3565b610bf1565b6103e46104e336600461339f565b610c0b565b61044760135481565b6103e46104ff3660046133f2565b610e21565b6006546105119060ff1681565b60405160ff90911681526020016103c8565b61044760095481565b6103e461053a3660046133f2565b610e47565b61044761054d3660046132ef565b610ec1565b610447610f01565b610447600c5481565b60065461057b9061010090046001600160a01b031681565b6040516001600160a01b0390911681526020016103c8565b6103bc6105a1366004613417565b610f0b565b6104476105b43660046132ef565b6111f0565b610447600d5481565b61044760085481565b610447600a5481565b60035461057b906001600160a01b031681565b6104476105f53660046132ef565b6001600160a01b03166000908152600f602052604090205490565b610447611217565b6104476000805160206139a783398151915281565b6103e461063b36600461323e565b61123a565b6103e461064e3660046132ef565b611252565b6103bc6106613660046133f2565b61127b565b6103ee6112a6565b61044761067c3660046132ef565b6112b3565b6103e461068f3660046133f2565b6112be565b610447600081565b6103e46106aa36600461323e565b6113c9565b6103e46113dd565b6103bc6106c53660046132c3565b6115f1565b610447600b5481565b610447611614565b6104476116ac565b6106f66106f13660046132ef565b6116d2565b604080519384526020840192909252908201526060016103c8565b6103e461071f36600461323e565b611713565b6103e461073236600461323e565b611726565b6103e4610745366004613559565b6117c5565b6103e46107583660046133f2565b6119d3565b61044761076b3660046132c3565b6119f9565b6103e461077e36600461323e565b611a4f565b610447610791366004613358565b6001600160a01b03918216600090815260106020908152604080832093909416825291909152205490565b6103e46107ca3660046132ef565b611a67565b6103e46107dd3660046132c3565b611a97565b60075461057b906001600160a01b031681565b6103e461080336600461323e565b611c80565b610447611d2b565b61044760125481565b60006001600160e01b031982166336372b0760e01b148061084a57506001600160e01b0319821663e414309160e01b145b92915050565b6000805160206139a783398151915261086881611d7e565b6040805180820190915260048152634534313760e01b6020820152670de0b6b3a76400008311156108b55760405162461bcd60e51b81526004016108ac919061327b565b60405180910390fd5b5060135460408051918252602082018490527f2cd87d6d243502fbf87bd7dd851659e05ac6a614994d7f04592e4f173f939783910160405180910390a150601355565b6004805461090590613628565b80601f016020809104026020016040519081016040528092919081815260200182805461093190613628565b801561097e5780601f106109535761010080835404028352916020019161097e565b820191906000526020600020905b81548152906001019060200180831161096157829003601f168201915b505050505081565b3360008181526010602090815260408083206001600160a01b03871680855292528083208590555191929182907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906109e29087815260200190565b60405180910390a35060019392505050565b6109fc611d88565b60065460405163529a356f60e01b81523360048201526101009091046001600160a01b03169063529a356f9060240160006040518083038186803b158015610a4357600080fd5b505afa158015610a57573d6000803e3d6000fd5b50505050610a658282611ddf565b610a6f6001600255565b5050565b610a7b6113dd565b610a6f3333836001611e8f565b6000610a92611d88565b610a9a6113dd565b610aa3826112b3565b9050610aaf6001600255565b919050565b6000610abe612032565b905090565b610acb611d88565b610ad36113dd565b610add3382611ddf565b610ae76001600255565b50565b6000610af4611d88565b610b0033858585612087565b506001610b0d6001600255565b9392505050565b6000610b1f81611d7e565b6003546040805180820190915260048152634534313160e01b6020820152906001600160a01b03858116911603610b695760405162461bcd60e51b81526004016108ac919061327b565b506040516370a0823160e01b81523060048201526000906001600160a01b038516906370a0823190602401602060405180830381865afa158015610bb1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bd59190613662565b9050610beb6001600160a01b0385168483612287565b50505050565b610bf96113dd565b610c063383836001611e8f565b505050565b610c13611d88565b60065460405163763c760160e11b81523060048201523360248201526001600160a01b0386811660448301526101009092049091169063ec78ec0290606401600060405180830381600087803b158015610c6c57600080fd5b505af1158015610c80573d6000803e3d6000fd5b505050506000610c8e612032565b905060006000198503610cd957506001600160a01b0385166000908152600f6020526040902054670de0b6b3a7640000610cc88383613691565b610cd291906136a8565b9450610cf9565b81610cec670de0b6b3a764000087613691565b610cf691906136a8565b90505b6001600160a01b0386166000908152600f6020526040812054610d1d9083906136ca565b9050600082600e54610d2f91906136ca565b6001600160a01b0389166000908152600f60205260409020839055600e81905590508515610da95786600d54610d6591906136dd565b600d8190556040517f83a9e0196329d258a5cfdba2e4fe6f0bbd8cf86900d64d40d9e2c8cb293a755191610d9c9133918b916136f0565b60405180910390a1610db3565b610db385886122ea565b604080516001600160a01b03808b16825287166020820152908101849052606081018390526080810182905260a081018890527fc42f5858719baf2f3f487c6964f1d69991959b7940b40f76ca3243bddf0a1db19060c00160405180910390a150505050610beb6001600255565b60008281526001602081905260409091200154610e3d81611d7e565b610c068383612301565b6001600160a01b0381163314610eb75760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016108ac565b610a6f828261236c565b6000670de0b6b3a7640000610ed46116ac565b6001600160a01b0384166000908152600f6020526040902054610ef79190613691565b61084a91906136a8565b6000610abe6123d3565b6000610f15611d88565b6003546040805180820190915260048152630453234360e41b6020820152906001600160a01b03878116911614610f5f5760405162461bcd60e51b81526004016108ac919061327b565b50610f68612404565b841115604051806040016040528060048152602001634532343160e01b81525090610fa65760405162461bcd60e51b81526004016108ac919061327b565b50610faf6113dd565b6000610fba8561241a565b6006546040516387a4d62b60e01b81523060048201526001600160a01b038a811660248301526044820189905260648201849052929350610100909104909116906387a4d62b9060840160006040518083038186803b15801561101c57600080fd5b505afa158015611030573d6000803e3d6000fd5b505060035461104c92506001600160a01b031690508887612287565b6040516323e30c8b60e01b81527f439148f0bbc682ca079e46d6e2c2f0c1e3b820f1a291b069d8882abf8cf18dd9906001600160a01b038916906323e30c8b906110a49033908b908b9088908c908c90600401613711565b6020604051808303816000875af11580156110c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e79190613662565b146040518060400160405280600481526020016322991a1960e11b815250906111235760405162461bcd60e51b81526004016108ac919061327b565b5060006111398861113484896136dd565b612433565b905061114582876136dd565b81101560405180604001604052806004815260200163114ccc8d60e21b815250906111835760405162461bcd60e51b81526004016108ac919061327b565b5081600d600082825461119691906136dd565b90915550506040517f61268d74931c41c9775dffb6169a5208aab1d09cb2eb6aabe8b97162801e5dfa906111cf908a90899086906136f0565b60405180910390a16001925050506111e76001600255565b95945050505050565b6003546000906001600160a01b0383811691161461120f57600061084a565b61084a612404565b6000611221611d88565b6112296113dd565b50600c546112376001600255565b90565b6112426113dd565b610a6f3360008360016000612578565b6000805160206139a783398151915261126a81611d7e565b6112726113dd565b610a6f82612920565b60009182526001602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6005805461090590613628565b600061084a826129c9565b60006112c981611d7e565b6112d1611d88565b6112d96113dd565b826112e26123d3565b101560405180604001604052806004815260200163114ccc0d60e21b8152509061131f5760405162461bcd60e51b81526004016108ac919061327b565b5082600d541015604051806040016040528060048152602001634534313360e01b815250906113615760405162461bcd60e51b81526004016108ac919061327b565b50600083600d5461137291906136ca565b600d819055905061138383856122ea565b7f80c183234cf159911c661c50bbe951c21e685e400ddc3c0cc907cc6796be3e928385836040516113b6939291906136f0565b60405180910390a150610c066001600255565b6113d16113dd565b610a6f33826001612a10565b60006113e7612be8565b600a549091508181036113f8575050565b60006114026123d3565b600b54600754600c54600d546040516315f2405360e01b8152600481018690526024810192909252604482015292935090916000916001600160a01b0316906315f2405390606401602060405180830381865afa158015611467573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148b9190613662565b905065048c27395000811115604051806040016040528060048152602001634533303360e01b815250906114d25760405162461bcd60e51b81526004016108ac919061327b565b5060006114df85876136ca565b905060006114ed8284613691565b90506000670de0b6b3a764000082600c546115089190613691565b61151291906136a8565b905080600c600082825461152691906136dd565b9091555050600954670de0b6b3a7640000906115429083613691565b61154c91906136a8565b600d600082825461155d91906136dd565b90915550670de0b6b3a764000090506115768387613691565b61158091906136a8565b61158a90866136dd565b600b819055600a899055600c54600d54604080518a8152602081018690528082019490945260608401929092526080830152517f717fee053884ab1935ba6d0140f6ed225371439611d9674ff445419d6a0fa1b79181900360a00190a15050505050505050565b60006115fb611d88565b61160733338585612087565b50600161084a6001600255565b6007546000906001600160a01b031663b81688166116306123d3565b600c54600d546009546040516001600160e01b031960e087901b16815260048101949094526024840192909252604483015260648201526084015b602060405180830381865afa158015611688573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610abe9190613662565b60006116b6611d88565b6116be6113dd565b6116c6610ab4565b90506112376001600255565b6001600160a01b0381166000908152600f602052604081205481908190816116f9866129c9565b90506000611705612032565b929791965091945092505050565b61171b6113dd565b610ae7816001612c6f565b6000805160206139a783398151915261173e81611d7e565b6040805180820190915260048152634534313760e01b6020820152670de0b6b3a76400008311156117825760405162461bcd60e51b81526004016108ac919061327b565b5060125460408051918252602082018490527f1e753ca8cc37e93a19f3cbc969c3205e2a0ad0a9bcbfc73080ba52d75aba2b70910160405180910390a150601255565b600054610100900460ff16158080156117e55750600054600160ff909116105b806117ff5750303b1580156117ff575060005460ff166001145b6118625760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016108ac565b6000805460ff191660011790558015611885576000805461ff0019166101001790555b6040805180820190915260048152634534303160e01b6020820152866118be5760405162461bcd60e51b81526004016108ac919061327b565b50600886905560068054610100600160a81b0319166101006001600160a01b038b16021790556118ec612be8565b600a55670de0b6b3a7640000600b5561190487612920565b61190f60008a612301565b6119276000805160206139a78339815191528a612301565b600380546001600160a01b0319166001600160a01b038416179055600461194e86826137bb565b50600561195b85826137bb565b506006805460ff191660ff8516179055670de0b6b3a76400006012556603328b944c400060135580156119c8576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050505050505050565b600082815260016020819052604090912001546119ef81611d7e565b610c06838361236c565b6003546040805180820190915260048152630453234360e41b60208201526000916001600160a01b03858116911614611a455760405162461bcd60e51b81526004016108ac919061327b565b50610b0d8261241a565b611a576113dd565b610a6f3382600060016000612578565b611a6f6113dd565b6001600160a01b0381166000908152600f6020526040812054610a6f91839190600180612578565b611a9f611d88565b60065460405163beda651360e01b81523360048201526001600160a01b0384811660248301523060448301526101009092049091169063beda651390606401600060405180830381600087803b158015611af857600080fd5b505af1158015611b0c573d6000803e3d6000fd5b50505050611b18612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611b575760405162461bcd60e51b81526004016108ac919061327b565b5080600d541015604051806040016040528060048152602001634533323560e01b81525090611b995760405162461bcd60e51b81526004016108ac919061327b565b506000611ba5836129c9565b9050611bb182826136ca565b6001600160a01b0384166000908152601160205260408120918255600b54600190920191909155600c8054849290611bea9084906136ca565b9250508190555081600d6000828254611c0391906136ca565b90915550506001600160a01b03831660008181526011602090815260409182902054600c54600d54845195865292850187905292840152606083019190915260808201527f2acc8948e777df596a8e9f282ab3b111e607a849806c73ccb084d23e1a9130929060a0015b60405180910390a150610a6f6001600255565b6000805160206139a7833981519152611c9881611d7e565b611ca0611d88565b604080518082019091526004815263229a189960e11b6020820152670de0b6b3a7640000831115611ce45760405162461bcd60e51b81526004016108ac919061327b565b50611ced6113dd565b600980549083905560408051828152602081018590527fb5302a4dff40e0a13b7cbe1217b694744560eeedf26aab600a643a1b2de010889101611c6d565b6007546000906001600160a01b03166315f24053611d476123d3565b600c54600d546040516001600160e01b031960e086901b16815260048101939093526024830191909152604482015260640161166b565b610ae78133612ddd565b6002805403611dd95760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016108ac565b60028055565b611de7612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611e265760405162461bcd60e51b81526004016108ac919061327b565b506000611e338383612433565b9050600081600d54611e4591906136dd565b905080600d819055507f83a9e0196329d258a5cfdba2e4fe6f0bbd8cf86900d64d40d9e2c8cb293a7551848383604051611e81939291906136f0565b60405180910390a150505050565b6000611e99611d88565b600654604051639fc9324160e01b81523060048201526001600160a01b03868116602483015261010090920490911690639fc9324190604401600060405180830381600087803b158015611eec57600080fd5b505af1158015611f00573d6000803e3d6000fd5b50505050611f0c612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090611f4b5760405162461bcd60e51b81526004016108ac919061327b565b506000611f57856129c9565b90506000198403611f66578093505b8215611f7d57611f768685612433565b9150611f81565b8391505b6000611f8d83836136ca565b9050600083600c54611f9f91906136ca565b6001600160a01b03888116600081815260116020908152604091829020878155600b54600190910155600c8590558151938d168452830191909152810186905260608101849052608081018290529091507f1a2a22cb034d26d1854bdc6666a5b91fe25efbbb5dcad3b0355478d6f5c362a19060a00160405180910390a150505061202a6001600255565b949350505050565b6000600e54600003612045575060085490565b600e54670de0b6b3a7640000600d54600c5461205f6123d3565b61206991906136dd565b61207391906136ca565b61207d9190613691565b610abe91906136a8565b816001600160a01b0316836001600160a01b03161415604051806040016040528060048152602001630453231360e41b815250906120d85760405162461bcd60e51b81526004016108ac919061327b565b5060065460405163395a182560e11b81523060048201526001600160a01b038581166024830152848116604483015260648201849052610100909204909116906372b4304a90608401600060405180830381600087803b15801561213b57600080fd5b505af115801561214f573d6000803e3d6000fd5b505050506000836001600160a01b0316856001600160a01b031603612177575060001961219f565b506001600160a01b038084166000908152601060209081526040808320938816835292905220545b6001600160a01b0384166000908152600f6020526040812080548492906121c79084906136ca565b90915550506001600160a01b0383166000908152600f6020526040812080548492906121f49084906136dd565b909155505060001981146122335761220c82826136ca565b6001600160a01b038086166000908152601060209081526040808320938a16835292905220555b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161227891815260200190565b60405180910390a35050505050565b6040516001600160a01b038316602482015260448101829052610c0690849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612e36565b600354610a6f906001600160a01b03168383612287565b61230b828261127b565b610a6f5760008281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45050565b612376828261127b565b15610a6f5760008281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6003546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a082319060240161166b565b6000670de0b6b3a76400006012546120736123d3565b6000670de0b6b3a764000060135483610ef79190613691565b6003546040516370a0823160e01b815230600482015260009182916001600160a01b03909116906370a0823190602401602060405180830381865afa158015612480573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a49190613662565b6003549091506124bf906001600160a01b0316853086612f0b565b6003546040516370a0823160e01b81523060048201526000916001600160a01b0316906370a0823190602401602060405180830381865afa158015612508573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061252c9190613662565b905081811015604051806040016040528060048152602001634533303760e01b8152509061256d5760405162461bcd60e51b81526004016108ac919061327b565b506111e782826136ca565b6000612582611d88565b84158061258d575083155b604051806040016040528060048152602001634532333960e01b815250906125c85760405162461bcd60e51b81526004016108ac919061327b565b5060006125d3612032565b905085156125ff57670de0b6b3a76400006125ee8288613691565b6125f891906136a8565b945061261f565b80612612670de0b6b3a764000087613691565b61261c91906136a8565b95505b60065460405163248d808d60e21b81523060048201526001600160a01b03898116602483015260448201899052851515606483015261010090920490911690639236023490608401600060405180830381600087803b15801561268157600080fd5b505af1158015612695573d6000803e3d6000fd5b505050506126a1612be8565b600a5414604051806040016040528060048152602001632299981960e11b815250906126e05760405162461bcd60e51b81526004016108ac919061327b565b5085600f6000896001600160a01b03166001600160a01b03168152602001908152602001600020541015604051806040016040528060048152602001634532303360e01b815250906127455760405162461bcd60e51b81526004016108ac919061327b565b5085600e541015604051806040016040528060048152602001632299181960e11b815250906127875760405162461bcd60e51b81526004016108ac919061327b565b506001600160a01b0387166000908152600f60205260408120546127ac9088906136ca565b9050600087600e546127be91906136ca565b9050866127c96123d3565b101560405180604001604052806004815260200163114ccc0d60e21b815250906128065760405162461bcd60e51b81526004016108ac919061327b565b50600e8190556001600160a01b0389166000818152600f60209081526040808320869055518b81529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a37fbd5034ffbd47e4e72a94baa2cdb74c6fad73cb3bcdc13036b72ec8306f5a764689888a84604051612891949392919061387b565b60405180910390a185156128a9576128a989886122ea565b600654604051636640728d60e11b815260048101899052602481018a90526101009091046001600160a01b03169063cc80e51a9060440160006040518083038186803b1580156128f857600080fd5b505afa15801561290c573d6000803e3d6000fd5b505050508693505050506111e76001600255565b612928612be8565b600a5414604051806040016040528060048152602001632299981960e11b815250906129675760405162461bcd60e51b81526004016108ac919061327b565b50600780546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f926910160405180910390a15050565b6001600160a01b0381166000908152601160205260408120805482036129f25750600092915050565b6001810154600b548254612a069190613691565b610b0d91906136a8565b6000612a1a611d88565b60065460405163087a556b60e41b81523060048201526001600160a01b038681166024830152610100909204909116906387a556b090604401600060405180830381600087803b158015612a6d57600080fd5b505af1158015612a81573d6000803e3d6000fd5b50505050612a8d612be8565b600a5414604051806040016040528060048152602001632299981960e11b81525090612acc5760405162461bcd60e51b81526004016108ac919061327b565b506000612ad7612032565b90508215612af057612ae98585612433565b9150612af4565b8391505b600081612b09670de0b6b3a764000085613691565b612b1391906136a8565b9050600081600e54612b2591906136dd565b600e8190556001600160a01b0388166000908152600f6020526040812080549293508492909190612b579084906136dd565b90915550506040517faf77103a98a12032881b6214985e03ff85a9c1ad6fed28f4b0f3c52e01bcc58b90612b9290899087908690869061387b565b60405180910390a16040518281526001600160a01b038816906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a3505050610b0d6001600255565b60007316700000000000000000000000000000000100016001600160a01b03166333d5ac9b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c6091906138a1565b67ffffffffffffffff16905090565b612c77611d88565b6006546040516315caa9e760e11b81523060048201523360248201819052604482018590529161010090046001600160a01b031690632b9553ce90606401600060405180830381600087803b158015612ccf57600080fd5b505af1158015612ce3573d6000803e3d6000fd5b5050505082612cf06123d3565b101560405180604001604052806004815260200163114ccc0d60e21b81525090612d2d5760405162461bcd60e51b81526004016108ac919061327b565b50600083612d3a836129c9565b612d4491906136dd565b9050600084600c54612d5691906136dd565b6001600160a01b03841660009081526011602052604090819020848155600b54600190910155600c829055519091507f13ed6866d4e1ee6da46f845c46d7e54120883d75c5ea9a2dacc1c4ca8984ab8090612db890859088908690869061387b565b60405180910390a18315612dd057612dd083866122ea565b505050610a6f6001600255565b612de7828261127b565b610a6f57612df481612f43565b612dff836020612f55565b604051602001612e109291906138cb565b60408051601f198184030181529082905262461bcd60e51b82526108ac9160040161327b565b6000612e8b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166130f19092919063ffffffff16565b9050805160001480612eac575080806020019051810190612eac9190613940565b610c065760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108ac565b6040516001600160a01b0380851660248301528316604482015260648101829052610beb9085906323b872dd60e01b906084016122b3565b606061084a6001600160a01b03831660145b60606000612f64836002613691565b612f6f9060026136dd565b67ffffffffffffffff811115612f8757612f876134b6565b6040519080825280601f01601f191660200182016040528015612fb1576020820181803683370190505b509050600360fc1b81600081518110612fcc57612fcc61395d565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110612ffb57612ffb61395d565b60200101906001600160f81b031916908160001a905350600061301f846002613691565b61302a9060016136dd565b90505b60018111156130a2576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061305e5761305e61395d565b1a60f81b8282815181106130745761307461395d565b60200101906001600160f81b031916908160001a90535060049490941c9361309b81613973565b905061302d565b508315610b0d5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016108ac565b606061202a848460008585600080866001600160a01b03168587604051613118919061398a565b60006040518083038185875af1925050503d8060008114613155576040519150601f19603f3d011682016040523d82523d6000602084013e61315a565b606091505b509150915061316b87838387613176565b979650505050505050565b606083156131e55782516000036131de576001600160a01b0385163b6131de5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108ac565b508161202a565b61202a83838151156131fa5781518083602001fd5b8060405162461bcd60e51b81526004016108ac919061327b565b60006020828403121561322657600080fd5b81356001600160e01b031981168114610b0d57600080fd5b60006020828403121561325057600080fd5b5035919050565b60005b8381101561327257818101518382015260200161325a565b50506000910152565b602081526000825180602084015261329a816040850160208701613257565b601f01601f19169190910160400192915050565b6001600160a01b0381168114610ae757600080fd5b600080604083850312156132d657600080fd5b82356132e1816132ae565b946020939093013593505050565b60006020828403121561330157600080fd5b8135610b0d816132ae565b60008060006060848603121561332157600080fd5b833561332c816132ae565b9250602084013561333c816132ae565b929592945050506040919091013590565b8035610aaf816132ae565b6000806040838503121561336b57600080fd5b8235613376816132ae565b91506020830135613386816132ae565b809150509250929050565b8015158114610ae757600080fd5b600080600080608085870312156133b557600080fd5b84356133c0816132ae565b93506020850135925060408501356133d781613391565b915060608501356133e7816132ae565b939692955090935050565b6000806040838503121561340557600080fd5b823591506020830135613386816132ae565b60008060008060006080868803121561342f57600080fd5b853561343a816132ae565b9450602086013561344a816132ae565b935060408601359250606086013567ffffffffffffffff8082111561346e57600080fd5b818801915088601f83011261348257600080fd5b81358181111561349157600080fd5b8960208285010111156134a357600080fd5b9699959850939650602001949392505050565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126134dd57600080fd5b813567ffffffffffffffff808211156134f8576134f86134b6565b604051601f8301601f19908116603f01168101908282118183101715613520576135206134b6565b8160405283815286602085880101111561353957600080fd5b836020870160208301376000602085830101528094505050505092915050565b600080600080600080600080610100898b03121561357657600080fd5b8835613581816132ae565b97506020890135613591816132ae565b965060408901356135a1816132ae565b955060608901359450608089013567ffffffffffffffff808211156135c557600080fd5b6135d18c838d016134cc565b955060a08b01359150808211156135e757600080fd5b506135f48b828c016134cc565b93505060c089013560ff8116811461360b57600080fd5b915061361960e08a0161334d565b90509295985092959890939650565b600181811c9082168061363c57607f821691505b60208210810361365c57634e487b7160e01b600052602260045260246000fd5b50919050565b60006020828403121561367457600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b808202811582820484141761084a5761084a61367b565b6000826136c557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561084a5761084a61367b565b8082018082111561084a5761084a61367b565b6001600160a01b039390931683526020830191909152604082015260600190565b6001600160a01b03878116825286166020820152604081018590526060810184905260a06080820181905281018290526000828460c0840137600060c0848401015260c0601f19601f8501168301019050979650505050505050565b601f821115610c0657600081815260208120601f850160051c810160208610156137945750805b601f850160051c820191505b818110156137b3578281556001016137a0565b505050505050565b815167ffffffffffffffff8111156137d5576137d56134b6565b6137e9816137e38454613628565b8461376d565b602080601f83116001811461381e57600084156138065750858301515b600019600386901b1c1916600185901b1785556137b3565b600085815260208120601f198616915b8281101561384d5788860151825594840194600190910190840161382e565b508582101561386b5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6001600160a01b0394909416845260208401929092526040830152606082015260800190565b6000602082840312156138b357600080fd5b815167ffffffffffffffff81168114610b0d57600080fd5b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613903816017850160208801613257565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613934816028840160208801613257565b01602801949350505050565b60006020828403121561395257600080fd5b8151610b0d81613391565b634e487b7160e01b600052603260045260246000fd5b6000816139825761398261367b565b506000190190565b6000825161399c818460208701613257565b919091019291505056feaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371a264697066735822122049944b56fe0cb841be1adb29c13192d7f264cf679043c19d04147fdcee4b7d1d64736f6c63430008110033