Contract 0x9a1EDb903B058298dd0b06f52876d9D45358B7cB 4

 
 
Txn Hash
Method
Block
From
To
Value [Txn Fee]
0xcffd633e25c106c9ea951b2df6e6c34666b95f38b6fb71d43b10e33d7bef7b43_set Factors430198072023-05-22 16:55:127 days 2 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.00619895976 153.177982179
0x69dcd9fd426eb6040415cdd5dfb9dd0e50844b3ebc924f8bacbe3c06c5a73b72_pause Component427753492023-05-16 12:50:4313 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.005216552543 176.395784799
0x624e79b967c1d3bcaee3dae0b6556dd74c1c1abceeaad1dd8fbbffb6ac64786a_pause Component423343792023-05-05 12:24:5424 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.006824114917 230.75490877
0x2a60ebd6fef600065f901657dd1ece0d6f7ba4389c6b05cb5bb82c6e589a585f_pause Component420197852023-04-27 12:48:3832 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.032203777472 625.498251382
0xc86dc036e62565a01cf98115ee68def644ccac9a436ae67535ff3383e61f9385_pause Component420197782023-04-27 12:47:5632 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.023788371961 462.044711303
0x42d3823499f7b1f1f269212069e3ddb6a376677851e3710b453e899133ae0f6a_pause Component420197602023-04-27 12:47:0632 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.019758635451 383.774603308
0x358af112747289c825f06e617ceef45bf02941feed65b04a424bcfd1b7cc4d81_pause Component420197592023-04-27 12:47:0232 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.010885171875 367.717447333
0x12a92e4f01180adf9a39135bfbe13d96cbe907d3d57797a15becc3376722e0c8_pause Component420197472023-04-27 12:46:3832 days 6 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.023344855864 453.174978924
0x9d4b0d73bda1a3497ed85549718d68bb8c1058ec9a4d3e5763347a5e5946f117_pause Component420181342023-04-27 11:37:2332 days 7 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.014186117269 448.899350334
0xa7d54c81e3dc2a40a9ae3568c352eeb727e1715ffebc10f3efaf5a35362bd395_pause Component420181332023-04-27 11:37:2132 days 7 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.013917063361 440.790021903
0x4b8f3c8f2e44f723c8f20153e4e1d9d6860aa6cb4d0fbfcc594ee7ece031e63bGrant Role407881422023-03-26 11:08:3464 days 7 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  0x9a1edb903b058298dd0b06f52876d9d45358b7cb0 MATIC0.0094739280
0x375dcc6965a1d77150fe35e3649474f960281c79db272c796ba133e6d3d58c5f0x60806040407865682023-03-26 10:12:3664 days 8 hrs ago0xe820cc557279acc115d61b7c450f47ff000b4ef6 IN  Create: Controller0 MATIC0.2855221680
[ Download CSV Export 
Parent Txn Hash Block From To Value
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
Controller

Compiler Version
v0.8.15+commit.e14f2714

Optimization Enabled:
Yes with 300 runs

Other Settings:
default evmVersion
File 1 of 24 : AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  // getRoundData and latestRoundData should both raise "No data present"
  // if they do not have data to report, instead of returning unset values
  // which could be misinterpreted as actual reported values.
  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

File 2 of 24 : AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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:
 *
 * ```
 * 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}:
 *
 * ```
 * 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.
 */
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());
        }
    }
}

File 3 of 24 : AccessControlEnumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;

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

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }
}

File 4 of 24 : 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;
}

File 5 of 24 : IAccessControlEnumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

File 6 of 24 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 7 of 24 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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;
    }
}

File 8 of 24 : IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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;
}

File 9 of 24 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

File 10 of 24 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 11 of 24 : 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;
    }
}

File 12 of 24 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 13 of 24 : 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;
    }
}

File 14 of 24 : 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);
}

File 15 of 24 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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 10, 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 * 8) < value ? 1 : 0);
        }
    }
}

File 16 of 24 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.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 `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);
    }
}

File 17 of 24 : EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 18 of 24 : Controller.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.15;

import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

import ".././interfaces/HTokenI.sol";
import "../utils/ErrorReporter.sol";
import "../interfaces/PermissionlessOracleI.sol";
import "../interfaces/ControllerI.sol";
import "../controller/ControllerStorage.sol";

/**
 * @title   Honey Protocol Controller
 * @notice  Controller can be interpreted as the brain of the Honey Protocol, is the one who decides:
 *              - who can borrow and how much it can borrow
 *              - who can redeem and how much it can redeem
 *              - who can transfer their hTokens
 *              - enables different markets to be traded
 * @author  Honey Labs Inc.
 * @custom:coauthor     m4rio
 * @custom:contributor  BowTiedPickle
 */
contract Controller is ControllerStorage, ControllerI, AccessControlEnumerable, ReentrancyGuard, Pausable {
  // ---------- Imports ----------
  using EnumerableSet for EnumerableSet.AddressSet;
  using ECDSA for bytes32;

  // ---------- Role Constants ----------
  bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
  bytes32 public constant FACTORY_ROLE = keccak256("FACTORY_ROLE");

  // ---------- Versioning ----------

  /// @notice this corresponds to 1.0.0
  uint256 public constant version = 1_000_000;

  // ---------- Parameters ----------

  /// @notice No collateralFactorMantissa may exceed this value
  uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 90%

  /// @notice The borrow fee or referred borrow fee can not exceed this value
  uint256 public constant borrowFeeCap = 0.02 ether; // 2%

  constructor() {
    _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
    _setupRole(PAUSER_ROLE, msg.sender);
  }

  // ---------- Public Function ----------

  /**
   * @notice  Add assets to be included in account liquidity calculation
   * @param   _hTokens  The list of addresses of the hToken markets to be enabled
   */
  function enterMarkets(HTokenI[] calldata _hTokens) external override whenNotPaused nonReentrant {
    uint256 len = _hTokens.length;

    for (uint256 i; i < len; ) {
      HTokenI hToken = _hTokens[i];
      addToMarketInternal(hToken, msg.sender);
      unchecked {
        ++i;
      }
    }
  }

  /**
   * @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  _hToken   The address of the asset to be removed
   */
  function exitMarket(HTokenI _hToken) external override whenNotPaused nonReentrant {
    // Get sender tokensHeld and amountOwed underlying from the hToken
    (uint256 tokensHeld, uint256 amountOwed, ) = _hToken.getAccountSnapshot(msg.sender);

    // Fail if the sender has HToken balance, meaning he has underlying deposited
    if (tokensHeld != 0) {
      revert ControllerError(Error.NONZERO_UNDERLYING_BALANCE);
    }

    // Fail if the sender has a borrow balance
    if (amountOwed != 0) {
      revert ControllerError(Error.NONZERO_BORROW_BALANCE);
    }

    Market storage marketToExit = _markets[_hToken];

    // Return true if the sender is not already in the market
    if (!marketToExit.accountMembership[msg.sender]) {
      return;
    }

    // Set hToken account membership to false
    delete marketToExit.accountMembership[msg.sender];

    emit MarketExited(_hToken, msg.sender);
  }

  /**
   * @notice  Checks if the account should be allowed to deposit underlying in the market
   * @param   _hToken     The market to verify the redeem against
   * @param   _depositor  The account that wants to deposit
   * @param   _amount     The number of underlying it wants to deposit
   */
  function depositUnderlyingAllowed(
    HTokenI _hToken,
    address _depositor,
    uint256 _amount
  ) external override whenNotPaused {
    _depositor;
    _amount;
    // Pausing is a very serious situation - we revert to sound the alarms
    if (marketPausedInfo[_hToken].depositPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    Market storage market = _markets[_hToken];

    if (!market.accountMembership[_depositor]) {
      // only hTokens may call depositUnderlyingAllowed if depositor not in market
      if (msg.sender != address(_hToken)) revert Unauthorized();

      // attempt to add depositor to the market
      addToMarketInternal(_hToken, _depositor);

      // it should be impossible to break the important invariant
      assert(market.accountMembership[_depositor]);
    }
  }

  /**
   * @notice  Checks if the account should be allowed to borrow the underlying asset of the given market
   * @param   _hToken         The market to verify the borrow against
   * @param   _borrower       The account which would borrow the asset
   * @param   _collateralId   collateral Id, aka the NFT token Id
   * @param   _borrowAmount   The amount of underlying the account would borrow
   */
  function borrowAllowed(
    HTokenI _hToken,
    address _borrower,
    uint256 _collateralId,
    uint256 _borrowAmount
  ) external override whenNotPaused nonReentrant {
    // Pausing is a very serious situation - we revert to sound the alarms
    if (marketPausedInfo[_hToken].borrowPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    Market storage market = _markets[_hToken];

    if (!market.accountMembership[_borrower]) {
      // only hTokens may call borrowAllowed if borrower not in market
      if (msg.sender != address(_hToken)) revert Unauthorized();

      // attempt to add borrower to the market
      addToMarketInternal(_hToken, _borrower);

      // it should be impossible to break the important invariant
      assert(market.accountMembership[_borrower]);
    }

    uint256 borrowCap = borrowCaps[_hToken];

    // Borrow cap of 0 corresponds to unlimited borrowing
    if (borrowCap != 0) {
      uint256 nextTotalBorrows = HTokenI(_hToken).totalBorrows() + _borrowAmount;
      if (nextTotalBorrows >= borrowCap) revert MarketError(Error.MARKET_CAP_BORROW_REACHED);
    }

    (, uint256 shortfall, ) = getHypotheticalAccountLiquidityBorrowInternal(_hToken, _collateralId, _borrowAmount);
    if (shortfall > 0) {
      revert ControllerError(Error.INSUFFICIENT_LIQUIDITY);
    }
  }

  /**
   * @notice Checks if the collateral is at risk of being liquidated
   * @param  _hToken         The market to verify the liquidation
   * @param  _collateralId   The Collateral Id, aka the NFT token Id
   */
  function liquidationAllowed(HTokenI _hToken, uint256 _collateralId) external view override whenNotPaused {
    // Pausing is a very serious situation - we revert to sound the alarms
    if (marketPausedInfo[_hToken].liquidationPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    (, uint256 shortfall, ) = getHypotheticalAccountLiquidityBorrowInternal(_hToken, _collateralId, 0);

    if (shortfall == 0) revert ControllerError(Error.LIQUIDATION_NOT_ALLOWED);
  }

  /**
   * @notice  Checks if the account should be allowed to redeem tokens in the given market
   * @param   _hToken         The market to verify the redeem against
   * @param   _redeemer       The account which would redeem the tokens
   * @param   _redeemTokens   The number of hTokens to exchange for the underlying asset in the market
   */
  function redeemAllowed(
    HTokenI _hToken,
    address _redeemer,
    uint256 _redeemTokens
  ) public view override whenNotPaused {
    _redeemTokens;
    if (marketPausedInfo[_hToken].redeemPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    Market storage market = _markets[_hToken];

    // If the redeemer is not 'in' the market we revert as no one should redeem if not entered
    if (!market.accountMembership[_redeemer]) {
      revert ControllerError(Error.NOT_FOUND);
    }
    //Otherwise, perform a hypothetical liquidity check to guard against shortfall, we don't do this YET
    (, uint256 shortfall) = getHypotheticalAccountLiquidityRedeemInternal(_hToken, _redeemer, _redeemTokens);
    if (shortfall > 0) {
      revert ControllerError(Error.INSUFFICIENT_LIQUIDITY);
    }
  }

  /**
   * @notice  Checks if the account should be allowed to deposit a collateral
   * @param   _hToken         The market to verify the deposit of the collateral
   * @param   _depositor      The account which deposits the collateral
   * @param   _collateralId   The collateral token id
   */
  function depositCollateralAllowed(
    HTokenI _hToken,
    address _depositor,
    uint256 _collateralId
  ) external override whenNotPaused {
    _depositor;
    _collateralId;
    if (marketPausedInfo[_hToken].depositCollateralPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    Market storage market = _markets[_hToken];

    if (!market.accountMembership[_depositor]) {
      // only hTokens may call borrowAllowed if borrower not in market
      if (msg.sender != address(_hToken)) revert Unauthorized();

      // attempt to add borrower to the market
      addToMarketInternal(_hToken, _depositor);

      // it should be impossible to break the important invariant
      assert(market.accountMembership[_depositor]);
    }
  }

  // ---------- Internal Functions ----------

  /**
   * @notice  Add the market a user's "assets in" for liquidity/withdraw calculations
   * @param   _hToken  The market to enter
   * @param   _account The address of the account to modify
   */
  function addToMarketInternal(HTokenI _hToken, address _account) internal {
    Market storage marketToJoin = _markets[_hToken];

    if (!marketToJoin.isListed) {
      // market is not listed, cannot join
      revert MarketError(Error.MARKET_NOT_LISTED);
    }

    if (marketToJoin.accountMembership[_account]) {
      // already joined
      return;
    }

    marketToJoin.accountMembership[_account] = true;

    emit MarketEntered(_hToken, _account);
  }

  function getCollateralPriceInUnderlying(HTokenI _hToken) internal view returns (uint256) {
    PermissionlessOracleI cachedOracle = _oracles[_hToken];
    uint8 decimals = _hToken.decimals();
    (uint128 nftPriceInETH, uint128 lastUpdated) = cachedOracle.getFloorPrice(
      address(_hToken.collateralToken()),
      decimals
    );

    if (
      lastUpdated < block.timestamp &&
      block.timestamp - lastUpdated > cachedOracle.updateThreshold(address(_hToken.collateralToken()))
    ) revert OracleNotUpdated();

    uint256 underlyingPriceInUSD = uint256(cachedOracle.getUnderlyingPriceInUSD(_hToken.underlyingToken(), decimals));
    uint256 ethPrice = uint256(cachedOracle.getEthPrice(decimals));
    return (nftPriceInETH * ethPrice) / underlyingPriceInUSD;
  }

  /*** Views  ***/

  /**
   * @notice  Determine what the account liquidity would be if the given amounts were redeemed/borrowed
   * @param   _hToken        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
   * @param   _collateralId  The Collateral Id, aka the NFT token Id
   * @return  liquidityTillLiquidation - hypothetical account liquidity in excess of collateral requirements
   * @return  shortfall - hypothetical account shortfall below collateral requirements
   * @return  liquidityTillLTV - Loan to value shortfall, this is the max a user can borrow
   */
  function getHypotheticalAccountLiquidity(
    HTokenI _hToken,
    address _account,
    uint256 _collateralId,
    uint256 _redeemTokens,
    uint256 _borrowAmount
  )
    external
    view
    override
    returns (
      uint256 liquidityTillLiquidation,
      uint256 shortfall,
      uint256 liquidityTillLTV
    )
  {
    if (_redeemTokens > 0)
      (liquidityTillLiquidation, shortfall) = getHypotheticalAccountLiquidityRedeemInternal(
        _hToken,
        _account,
        _redeemTokens
      );
    else
      (liquidityTillLiquidation, shortfall, liquidityTillLTV) = getHypotheticalAccountLiquidityBorrowInternal(
        _hToken,
        _collateralId,
        _borrowAmount
      );
  }

  /**
   * @notice  Returns whether the given account is entered in the given asset
   * @param   _hToken   The hToken to check
   * @param   _account  The address of the account to check
   * @return  True if the account is in the asset, otherwise false.
   */
  function checkMembership(HTokenI _hToken, address _account) external view override returns (bool) {
    return _markets[_hToken].accountMembership[_account];
  }

  /**
   * @notice  Checks if the account should be allowed to transfer tokens in the given market
   * @param   _hToken  The market to verify the transfer against
   */
  function transferAllowed(HTokenI _hToken) external view override whenNotPaused {
    // Pausing is a very serious situation - we revert to sound the alarms
    if (marketPausedInfo[_hToken].transferPaused) revert PausedAction();

    Market storage market = _markets[_hToken];
    if (!market.isListed) {
      revert MarketError(Error.MARKET_NOT_LISTED);
    }
  }

  /**
   * @notice  Returns the borrow fee per market, accounts for referral
   * @param   _hToken     The market we want the borrow fee for
   * @param   _referral   Referral code for Referral program of Honey Labs
   * @param   _signature  Signed message provided by Honey Labs
   */
  function getBorrowFeePerMarket(
    HTokenI _hToken,
    string calldata _referral,
    bytes calldata _signature
  ) external view returns (uint256, bool) {
    (address signed, ) = keccak256(abi.encodePacked(_referral)).toEthSignedMessageHash().tryRecover(_signature);
    if (_referralSigner == signed) {
      return (_referralBorrowFeePerMarket[_hToken], true);
    }
    return (_borrowFeePerMarket[_hToken], false);
  }

  /**
   * @notice  Returns the borrow fee per market if provided a referral code, accounts for referral
   * @param   _hToken  The market we want the borrow fee for
   */
  function getReferralBorrowFeePerMarket(HTokenI _hToken) external view returns (uint256) {
    return _referralBorrowFeePerMarket[_hToken];
  }

  /**
   * @notice  Checks if the account should be allowed to repay a borrow in the given market
   * @param   _hToken        The market to verify the repay against
   * @param   _repayAmount   The amount of the underlying asset the account would repay
   * @param   _collateralId  The Collateral Id, aka the NFT token Id
   */
  function repayBorrowAllowed(
    HTokenI _hToken,
    uint256 _repayAmount,
    uint256 _collateralId
  ) external view override whenNotPaused {
    _repayAmount;
    _collateralId;
    if (marketPausedInfo[_hToken].repayBorrowPaused) revert PausedAction();

    // This also checks if a market is listed as you can not set an oracle for an unlisted market
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);
  }

  /**
   * @notice  Checks if withdrawal are allowed for this collateral id
   * @param   _hToken        The market to verify the withdrawal from
   * @param   _collateralId  The collateral Id we want to withdraw
   */
  function withdrawCollateralAllowed(HTokenI _hToken, uint256 _collateralId) external view override whenNotPaused {
    if (!_markets[_hToken].isListed) {
      revert MarketError(Error.MARKET_NOT_LISTED);
    }
    if (_hToken.getDebtForCollateral(_collateralId) != 0) revert ControllerError(Error.WITHDRAW_NOT_ALLOWED);
  }

  /**
   * @notice Checks if a market exists and it's listed
   * @param  _hToken  The market we check to see if it exists
   * @return bool true or false
   */
  function marketExists(HTokenI _hToken) external view override whenNotPaused returns (bool) {
    return _markets[_hToken].isListed;
  }

  /**
   * @notice Returns market data for a specific market
   * @param  _hToken  The market we want to retrieved Controller data
   * @return bool If the market is listed
   * @return uint256 MAX Factor Mantissa
   * @return uint256 Collateral Factor Mantissa
   */
  function getMarketData(HTokenI _hToken)
    external
    view
    override
    returns (
      bool,
      uint256,
      uint256
    )
  {
    Market storage market = _markets[_hToken];
    return (market.isListed, market.LTVFactorMantissa, market.collateralFactorMantissa);
  }

  /**
   * @notice  Checks if an underlying exists in the market
   * @param   _underlying The underlying address to check if exists
   * @return  bool true or false
   */
  function underlyingExistsInMarkets(address _underlying) external view override returns (bool) {
    return registeredUnderlying.contains(_underlying);
  }

  /**
   * @notice  Checks if a collateral exists in the market
   * @param   _collateral   The collateral to check if exists
   * @return  bool true or false
   */
  function collateralExistsInMarkets(address _collateral) external view override returns (bool) {
    return registeredCollateral.contains(_collateral);
  }

  /**
   * @notice  Checks if a certain action is paused within a market
   * @param   _hToken   The market we want to check if an action is paused
   * @param   _target   The action we want to check if it's paused
   * @return  bool true or false
   */
  function isActionPaused(HTokenI _hToken, uint256 _target) external view override returns (bool) {
    if (!_markets[_hToken].isListed) revert MarketError(Error.MARKET_NOT_LISTED);

    if (_target == 0) {
      return marketPausedInfo[_hToken].borrowPaused;
    } else if (_target == 1) {
      return marketPausedInfo[_hToken].transferPaused;
    } else if (_target == 2) {
      return marketPausedInfo[_hToken].redeemPaused;
    } else if (_target == 3) {
      return marketPausedInfo[_hToken].liquidationPaused;
    } else if (_target == 4) {
      return marketPausedInfo[_hToken].repayBorrowPaused;
    } else if (_target == 5) {
      return marketPausedInfo[_hToken].depositPaused;
    } else if (_target == 6) {
      return marketPausedInfo[_hToken].depositCollateralPaused;
    }

    revert ControllerError(Error.INVALID_ACTION);
  }

  /**
   * @notice  Determine what the account liquidity would be if the given amounts were redeemed
   * @param   _hToken         The market to hypothetically redeem/borrow in
   * @param   _account        The account to determine liquidity for
   * @param   _redeemTokens   The number of tokens to hypothetically redeem
   * @dev     Note that we calculate the exchangeRateStored for each collateral hToken using stored data,
   *            without calculating accumulated interest. Also not used for now
   * @return  liquidity - hypothetical account liquidity in excess of collateral requirements
   * @return  shortfall - hypothetical account shortfall below collateral requirements
   */
  function getHypotheticalAccountLiquidityRedeemInternal(
    HTokenI _hToken,
    address _account,
    uint256 _redeemTokens
  ) internal view returns (uint256 liquidity, uint256 shortfall) {
    // Read the balances and exchange rate from the _hToken
    (uint256 hTokenBalance, , uint256 exchangeRateMantissa) = _hToken.getAccountSnapshot(_account);
    if (hTokenBalance < _redeemTokens) revert ControllerError(Error.BALANCE_INSUFFICIENT);
    uint256 toWithdraw = (_redeemTokens * exchangeRateMantissa) / 1e18;
    liquidity = _hToken.getCashPrior();

    // If we don't have enough liquidity to cover redeem amount raise a shortfall
    if (toWithdraw > liquidity) {
      shortfall = toWithdraw - liquidity;
    }
  }

  /**
   * @notice  Determine what the account liquidity would be if the given amounts were borrowed
   * @param   _hToken         The market to hypothetically redeem/borrow in
   * @param   _collateralId   The Collateral Id, aka the NFT token Id
   * @param   _borrowAmount   The amount of underlying to hypothetically borrow
   * @dev     Note that we calculate the exchangeRateStored for each collateral hToken using stored data,
   *          without calculating accumulated interest.
   * @return  liquidityTillLiquidation - hypothetical account liquidity in excess of collateral requirements
   * @return  shortfall - hypothetical account shortfall below collateral requirements
   * @return  liquidityTillLTV - Loan to value shortfall
   */
  function getHypotheticalAccountLiquidityBorrowInternal(
    HTokenI _hToken,
    uint256 _collateralId,
    uint256 _borrowAmount
  )
    internal
    view
    returns (
      uint256 liquidityTillLiquidation,
      uint256 shortfall,
      uint256 liquidityTillLTV
    )
  {
    uint256 sumCollateral = getCollateralPriceInUnderlying(_hToken);
    uint256 availableUnderlying = _hToken.getCashPrior();

    // Read the balances and exchange rate from the hToken
    uint256 borrowBalance = _hToken.getDebtForCollateral(_collateralId);

    if (sumCollateral == 0) {
      revert ControllerError(Error.PRICE_ERROR);
    }
    uint256 sumBorrowPlusEffects = borrowBalance + _borrowAmount;

    // If we don't have enough liquidity to cover borrow amount then revert
    if (_borrowAmount > availableUnderlying) revert ControllerError(Error.INSUFFICIENT_LIQUIDITY);

    // computing collateral factor applied on the collateral total amount
    // collateral factor % from the NFT price
    uint256 ltvValue = (_markets[_hToken].LTVFactorMantissa * sumCollateral) / 1e18;
    sumCollateral = (_markets[_hToken].collateralFactorMantissa * sumCollateral) / 1e18;

    unchecked {
      if (ltvValue > sumBorrowPlusEffects) {
        liquidityTillLiquidation = sumCollateral - sumBorrowPlusEffects;
        liquidityTillLTV = ltvValue - sumBorrowPlusEffects;
      } else if (sumCollateral > sumBorrowPlusEffects) {
        liquidityTillLiquidation = sumCollateral - sumBorrowPlusEffects;
      } else {
        shortfall = sumBorrowPlusEffects - sumCollateral;
      }
    }
  }

  /**
   * @notice  Returns the oracle per market
   * @param   _hToken   The market to get the oracle for
   */
  function oracle(HTokenI _hToken) external view override returns (PermissionlessOracleI) {
    return _oracles[_hToken];
  }

  function referralSigner() external view returns (address) {
    return _referralSigner;
  }

  // ---------- Admin Functions ----------

  /**
   * @notice  Sets a new price oracle for an HToken
   * @param   _hToken     HToken to set the oracle for
   * @param   _newOracle  New oracle address
   */
  function _setPriceOracle(HTokenI _hToken, PermissionlessOracleI _newOracle) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender) && !hasRole(FACTORY_ROLE, msg.sender)) revert Unauthorized();

    Market storage market = _markets[_hToken];
    if (!market.isListed) {
      revert MarketError(Error.MARKET_NOT_LISTED);
    }
    emit PriceOracleUpdated(_oracles[_hToken], _newOracle);

    _oracles[_hToken] = _newOracle;
  }

  /**
   * @notice  Sets the maxLTVFactor and collateral factor for an HToken
   * @param   _hToken                       Market to set the factors for
   * @param   _newLTVFactorMantissa         New max LTV factor in mantissa format
   * @param   _newCollateralFactorMantissa  New collateral factor in mantissa format
   */
  function _setFactors(
    HTokenI _hToken,
    uint256 _newLTVFactorMantissa,
    uint256 _newCollateralFactorMantissa
  ) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender) && !hasRole(FACTORY_ROLE, msg.sender)) revert Unauthorized();
    if (_newLTVFactorMantissa == 0) revert ControllerError(Error.INVALID_MAX_LTV_FACTOR);
    if (_newCollateralFactorMantissa <= _newLTVFactorMantissa) revert ControllerError(Error.INVALID_COLLATERAL_FACTOR);

    // Check collateral factor <= collateralFactorMaxMantissa
    if (collateralFactorMaxMantissa < _newCollateralFactorMantissa) {
      revert ControllerError(Error.INVALID_COLLATERAL_FACTOR);
    }

    // Fail if oracle not set, then the market is not listed
    if (address(_oracles[_hToken]) == address(0)) revert ControllerError(Error.ORACLE_NOT_SET);

    Market storage market = _markets[_hToken];

    emit CollateralFactorUpdated(_hToken, market.collateralFactorMantissa, _newCollateralFactorMantissa);
    emit NewMaxLTVFactor(_hToken, market.LTVFactorMantissa, _newLTVFactorMantissa);

    // Set market's factors to new factors
    market.collateralFactorMantissa = _newCollateralFactorMantissa;
    market.LTVFactorMantissa = _newLTVFactorMantissa;
  }

  /**
   * @notice  Add the market to the markets mapping and set it as listed
   * @dev     Admin function to set isListed and add support for the market
   * @param   _hToken The address of the market (token) to list
   */
  function _supportMarket(HTokenI _hToken) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender) && !hasRole(FACTORY_ROLE, msg.sender)) revert Unauthorized();

    Market storage market = _markets[_hToken];

    if (market.isListed) {
      revert MarketError(Error.MARKET_ALREADY_LISTED);
    }

    if (!_hToken.supportsInterface(type(HTokenI).interfaceId)) revert WrongParams();

    market.isListed = true;
    market.collateralFactorMantissa = 0;

    IERC20 underlying = _hToken.underlyingToken();
    IERC721 collateral = _hToken.collateralToken();

    if (address(underlying) == address(0) || address(collateral) == address(0))
      revert ControllerError(Error.MARKET_INVALID);

    registeredUnderlying.add(address(underlying));
    registeredCollateral.add(address(collateral));

    emit MarketListed(_hToken);
  }

  /**
   * @notice  Remove the market from the markets mapping
   * @param   _hToken The address of the market (token) to de-list/remove
   */
  function _removeMarket(HTokenI _hToken) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Unauthorized();

    Market storage market = _markets[_hToken];

    if (!market.isListed) {
      revert MarketError(Error.MARKET_NOT_LISTED);
    }

    // You can not remove a market if the oracle is present.
    if (address(_oracles[_hToken]) != address(0)) revert ControllerError(Error.ORACLE_IS_PRESENT);

    delete _markets[_hToken];

    IERC20 underlying = _hToken.underlyingToken();
    IERC721 collateral = _hToken.collateralToken();

    registeredUnderlying.remove(address(underlying));
    registeredCollateral.remove(address(collateral));

    emit MarketRemoved(_hToken);
  }

  /**
   * @notice  Set the given borrow caps for the given hToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
   * @dev     Admin function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
   * @param   _hTokens 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.
   */
  function _setMarketBorrowCaps(HTokenI[] calldata _hTokens, uint256[] calldata _newBorrowCaps) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Unauthorized();

    uint256 numMarkets = _hTokens.length;
    uint256 numBorrowCaps = _newBorrowCaps.length;

    if (numMarkets == 0 || numMarkets != numBorrowCaps) revert WrongParams();

    for (uint256 i; i < numMarkets; ) {
      HTokenI hToken = _hTokens[i];
      Market storage market = _markets[hToken];

      if (!market.isListed) {
        revert MarketError(Error.MARKET_NOT_LISTED);
      }

      borrowCaps[_hTokens[i]] = _newBorrowCaps[i];
      emit BorrowCapUpdated(_hTokens[i], _newBorrowCaps[i]);
      unchecked {
        ++i;
      }
    }
  }

  /**
   * @notice  Pause an action for a particular HToken
   * @param   _hToken   HToken to pause
   * @param   _state    True for paused, false for unpaused
   * @param   _target   Target ID of the component to pause
   */
  function _pauseComponent(
    HTokenI _hToken,
    bool _state,
    uint256 _target
  ) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender) && !hasRole(PAUSER_ROLE, msg.sender)) revert Unauthorized();
    if (!_markets[_hToken].isListed) revert MarketError(Error.MARKET_NOT_LISTED);

    if (_target == 0) {
      marketPausedInfo[_hToken].borrowPaused = _state;
      emit ActionPausedhToken(_hToken, "Borrow", _state);
    } else if (_target == 1) {
      marketPausedInfo[_hToken].transferPaused = _state;
      emit ActionPausedhToken(_hToken, "Transfer", _state);
    } else if (_target == 2) {
      marketPausedInfo[_hToken].redeemPaused = _state;
      emit ActionPausedhToken(_hToken, "Redeem", _state);
    } else if (_target == 3) {
      marketPausedInfo[_hToken].liquidationPaused = _state;
      emit ActionPausedhToken(_hToken, "Liquidation", _state);
    } else if (_target == 4) {
      marketPausedInfo[_hToken].repayBorrowPaused = _state;
      emit ActionPausedhToken(_hToken, "RepayBorrow", _state);
    } else if (_target == 5) {
      marketPausedInfo[_hToken].depositPaused = _state;
      emit ActionPausedhToken(_hToken, "DepositUnderlying", _state);
    } else if (_target == 6) {
      marketPausedInfo[_hToken].depositCollateralPaused = _state;
      emit ActionPausedhToken(_hToken, "DepositCollateral", _state);
    } else revert ControllerError(Error.INVALID_ACTION);
  }

  /**
   * @notice  Pauses the controller
   * @param   _state True to pause, false to unpause
   */
  function _pauseController(bool _state) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Unauthorized();

    if (_state) _pause();
    else _unpause();
    emit ControllerPaused(_state);
  }

  /**
   * @notice  Set the borrow fee for the given hToken market
   * @param   _market The market to set the borrow fee for
   * @param   _fee    The new borrow fee to set
   */
  function _setBorrowFeePerMarket(
    HTokenI _market,
    uint256 _fee,
    uint256 _referralFee
  ) external {
    if (_fee > borrowFeeCap || _referralFee > borrowFeeCap) revert ControllerError(Error.AMOUNT_TOO_BIG);
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender) && !hasRole(FACTORY_ROLE, msg.sender)) revert Unauthorized();

    emit BorrowFeePerMarketUpdated(_market, _fee, _referralFee);
    _borrowFeePerMarket[_market] = _fee;
    _referralBorrowFeePerMarket[_market] = _referralFee;
  }

  function _setReferralSigner(address _newSigner) external {
    if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert Unauthorized();

    emit ReferralSignerUpdated(_referralSigner, _newSigner);
    _referralSigner = _newSigner;
  }

  /**
   * @dev See {IERC165-supportsInterface}.
   */
  function supportsInterface(bytes4 _interfaceId) public pure override returns (bool) {
    return _interfaceId == type(AccessControlEnumerable).interfaceId || _interfaceId == type(ControllerI).interfaceId;
  }

  // ---------- Events ----------

  /// @notice Emitted when an admin supports a market
  event MarketListed(HTokenI indexed _hToken);

  /// @notice Emitted when an admin removes a market
  event MarketRemoved(HTokenI indexed _hToken);

  /// @notice Emitted when an account enters a market
  event MarketEntered(HTokenI indexed _hToken, address _account);

  /// @notice Emitted when an account exits a market
  event MarketExited(HTokenI indexed _hToken, address _account);

  /// @notice Emitted when close factor is changed by admin
  event NewMaxLTVFactor(HTokenI indexed _hToken, uint256 _oldMaxLTVFactorMantissa, uint256 _newMaxLTVFactorMantissa);

  /// @notice Emitted when a collateral factor is changed by admin
  event CollateralFactorUpdated(
    HTokenI indexed _hToken,
    uint256 _oldCollateralFactorMantissa,
    uint256 _newCollateralFactorMantissa
  );

  /// @notice Emitted when price oracle is changed
  event PriceOracleUpdated(PermissionlessOracleI _oldPriceOracle, PermissionlessOracleI _newPriceOracle);

  /// @notice Emitted when an action is paused on a market
  event ActionPausedhToken(HTokenI indexed _hToken, string _action, bool _pauseState);

  /// @notice Emitted when borrow cap for a hToken is changed
  event BorrowCapUpdated(HTokenI indexed _hToken, uint256 _newBorrowCap);

  /// @notice Emitted when borrow cap guardian is changed
  event BorrowCapGuardianUpdated(address _oldBorrowCapGuardian, address _newBorrowCapGuardian);

  /// @notice Emitted when the borrow fee per market is updated
  event BorrowFeePerMarketUpdated(HTokenI indexed _market, uint256 _fee, uint256 _referralFee);

  /// @notice Emitted when the signer that signs the referral codes is updated
  event ReferralSignerUpdated(address _oldSigner, address _newSigner);

  /// @notice Emitted when the controller is paused/unpaused
  event ControllerPaused(bool _paused);
}

File 19 of 24 : ControllerStorage.sol
//SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.15;

import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import ".././interfaces/HTokenI.sol";
import ".././interfaces/PermissionlessOracleI.sol";

/**
/**
 * @title   Honey Protocol Controller Storage
 * @notice  Storage 
 * @author  Honey Labs Inc.
 * @custom:coauthor     m4rio
 * @custom:contributor  BowTiedPickle
 */
contract ControllerStorage {
  using EnumerableSet for EnumerableSet.AddressSet;

  /**
   * @notice Signer address that signed the referral hashes
   */
  address internal _referralSigner;

  struct Market {
    /// @notice Whether or not this market is listed
    bool isListed;
    /**
     * @notice Multiplier representing the most one can borrow against their collateral in this market.
     *         For instance, 0.5e18 to allow borrowing 50% of collateral value.
     *         Must be between 0 (0%) and 1e18 (100%), and stored as a mantissa.
     */
    uint256 LTVFactorMantissa;
    /**
     * @notice Multiplier representing the maximum fraction of collateral value allowable as debt before liquidation in this market.
     *         For instance, 0.9e18 to liquidate any debt position >= 90% of the collateral value.
     *         Must be between 0 (0%) and 1e18 (100%), and stored as a mantissa.
     */
    uint256 collateralFactorMantissa;
    /// @notice Per-market mapping of "accounts in this market"
    mapping(address => bool) accountMembership;
  }

  /**
   * @notice Mapping for price oracles per market
   */
  mapping(HTokenI => PermissionlessOracleI) internal _oracles;

  /**
   * @notice Official mapping of hTokens -> Market metadata
   * @dev Used e.g. to determine if a market is supported
   */
  mapping(HTokenI => Market) internal _markets;

  /**
   * @notice Info about functionalities being paused in a market
   */

  struct MarketPausedInfo {
    bool borrowPaused;
    bool transferPaused;
    bool redeemPaused;
    bool liquidationPaused;
    bool repayBorrowPaused;
    bool depositPaused;
    bool depositCollateralPaused;
  }

  /**
   * @notice Mapping for pausing components per market
   */
  mapping(HTokenI => MarketPausedInfo) public marketPausedInfo;

  /**
   * @notice Whether the ERC-20 token is used as an underlying for any markets
   */
  EnumerableSet.AddressSet internal registeredUnderlying;

  /**
   * @notice Whether the ERC-721 token is used as a collateral for any markets
   */
  EnumerableSet.AddressSet internal registeredCollateral;

  /**
   * @notice Mapping of borrow caps enforced within borrowAllowed for each market address.
   *         Defaults to zero which corresponds to unlimited borrowing.
   */
  mapping(HTokenI => uint256) public borrowCaps;

  /**
   * @notice Mapping of borrow fee per market. The borrow fee represents the fee added on tob of the borrowed amount
   */
  mapping(HTokenI => uint256) internal _borrowFeePerMarket;

  /**
   * @notice Mapping of borrow fee per market if the borrow is made via a referral code.
   *          The borrow fee represents the fee added on tob of the borrowed amount
   */
  mapping(HTokenI => uint256) internal _referralBorrowFeePerMarket;
}

File 20 of 24 : ControllerI.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;

import "./HTokenI.sol";
import "./PermissionlessOracleI.sol";

/**
 * @title   Interface of Controller
 * @author  Honey Labs Inc.
 * @custom:coauthor     m4rio
 * @custom:contributor  BowTiedPickle
 */
interface ControllerI {
  /**
   * @notice returns the oracle per market
   */
  function oracle(HTokenI _hToken) external view returns (PermissionlessOracleI);

  /**
   * @notice Add assets to be included in account liquidity calculation
   * @param _hTokens The list of addresses of the hToken markets to be enabled
   */
  function enterMarkets(HTokenI[] calldata _hTokens) 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 _hToken The address of the asset to be removed
   */
  function exitMarket(HTokenI _hToken) external;

  /**
   * @notice Checks if the account should be allowed to deposit underlying in the market
   * @param _hToken The market to verify the redeem against
   * @param _depositor The account which that wants to deposit
   * @param _amount The number of underlying it wants to deposit
   */
  function depositUnderlyingAllowed(
    HTokenI _hToken,
    address _depositor,
    uint256 _amount
  ) external;

  /**
   * @notice Checks if the account should be allowed to borrow the underlying asset of the given market
   * @param _hToken The market to verify the borrow against
   * @param _borrower The account which would borrow the asset
   * @param _collateralId collateral Id, aka the NFT token Id
   * @param _borrowAmount The amount of underlying the account would borrow
   */
  function borrowAllowed(
    HTokenI _hToken,
    address _borrower,
    uint256 _collateralId,
    uint256 _borrowAmount
  ) external;

  /**
   * @notice Checks if the account should be allowed to deposit a collateral
   * @param _hToken The market to verify the deposit of the collateral
   * @param _depositor The account which deposits the collateral
   * @param _collateralId The collateral token id
   */
  function depositCollateralAllowed(
    HTokenI _hToken,
    address _depositor,
    uint256 _collateralId
  ) external;

  /**
   * @notice Checks if the account should be allowed to redeem tokens in the given market
   * @param _hToken The market to verify the redeem against
   * @param _redeemer The account which would redeem the tokens
   * @param _redeemTokens The number of hTokens to exchange for the underlying asset in the market
   */
  function redeemAllowed(
    HTokenI _hToken,
    address _redeemer,
    uint256 _redeemTokens
  ) external view;

  /**
   * @notice Checks if the collateral is at risk of being liquidated
   * @param _hToken The market to verify the liquidation
   * @param _collateralId collateral Id, aka the NFT token Id
   */
  function liquidationAllowed(HTokenI _hToken, uint256 _collateralId) external view;

  /**
   * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
   * @param _hToken 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
   * @param _collateralId collateral Id, aka the NFT token Id
   * @return liquidity - hypothetical account liquidity in excess of collateral requirements
   * @return shortfall - hypothetical account shortfall below collateral requirements
   * @return ltvShortfall - Loan to value shortfall, this is the max a user can borrow
   */
  function getHypotheticalAccountLiquidity(
    HTokenI _hToken,
    address _account,
    uint256 _collateralId,
    uint256 _redeemTokens,
    uint256 _borrowAmount
  )
    external
    view
    returns (
      uint256 liquidity,
      uint256 shortfall,
      uint256 ltvShortfall
    );

  /**
   * @notice Returns whether the given account is entered in the given asset
   * @param _hToken The hToken to check
   * @param _account The address of the account to check
   * @return True if the account is in the asset, otherwise false.
   */
  function checkMembership(HTokenI _hToken, address _account) external view returns (bool);

  /**
   * @notice Checks if the account should be allowed to transfer tokens in the given market
   * @param _hToken The market to verify the transfer against
   */
  function transferAllowed(HTokenI _hToken) external;

  /**
   * @notice Checks if the account should be allowed to repay a borrow in the given market
   * @param _hToken The market to verify the repay against
   * @param _repayAmount The amount of the underlying asset the account would repay
   * @param _collateralId collateral Id, aka the NFT token Id
   */
  function repayBorrowAllowed(
    HTokenI _hToken,
    uint256 _repayAmount,
    uint256 _collateralId
  ) external view;

  /**
   * @notice checks if withdrawal are allowed for this token id
   * @param _hToken The market to verify the withdrawal from
   * @param _collateralId what to pay for
   */
  function withdrawCollateralAllowed(HTokenI _hToken, uint256 _collateralId) external view;

  /**
   * @notice checks if a market exists and it's listed
   * @param _hToken the market we check to see if it exists
   * @return bool true or false
   */
  function marketExists(HTokenI _hToken) external view returns (bool);

  /**
   * @notice Returns market data for a specific market
   * @param _hToken the market we want to retrieved Controller data
   * @return bool If the market is listed
   * @return uint256 MAX Factor Mantissa
   * @return uint256 Collateral Factor Mantissa
   */
  function getMarketData(HTokenI _hToken)
    external
    view
    returns (
      bool,
      uint256,
      uint256
    );

  /**
   * @notice checks if an underlying exists in the market
   * @param _underlying the underlying to check if exists
   * @return bool true or false
   */
  function underlyingExistsInMarkets(address _underlying) external view returns (bool);

  /**
   * @notice checks if a collateral exists in the market
   * @param _collateral the collateral to check if exists
   * @return bool true or false
   */
  function collateralExistsInMarkets(address _collateral) external view returns (bool);

  /**
   * @notice  Checks if a certain action is paused within a market
   * @param   _hToken   The market we want to check if an action is paused
   * @param   _target   The action we want to check if it's paused
   * @return  bool true or false
   */
  function isActionPaused(HTokenI _hToken, uint256 _target) external view returns (bool);

  /**
   * @notice returns the borrow fee per market, accounts for referral
   * @param _hToken the market we want the borrow fee for
   * @param _referral referral code for Referral program of Honey Labs
   * @param _signature signed message provided by Honey Labs
   */
  function getBorrowFeePerMarket(
    HTokenI _hToken,
    string calldata _referral,
    bytes calldata _signature
  ) external view returns (uint256, bool);

  /**
   * @notice returns the borrow fee per market if provided a referral code, accounts for referral
   * @param _hToken the market we want the borrow fee for
   */
  function getReferralBorrowFeePerMarket(HTokenI _hToken) external view returns (uint256);

  // ---------- Permissioned Functions ----------

  function _supportMarket(HTokenI _hToken) external;

  function _setPriceOracle(HTokenI _hToken, PermissionlessOracleI _newOracle) external;

  function _setFactors(
    HTokenI _hToken,
    uint256 _newMaxLTVFactorMantissa,
    uint256 _newCollateralFactorMantissa
  ) external;

  function _setBorrowFeePerMarket(
    HTokenI _market,
    uint256 _fee,
    uint256 _referralFee
  ) external;

  function _pauseComponent(
    HTokenI _hToken,
    bool _state,
    uint256 _target
  ) external;
}

File 21 of 24 : HTokenI.sol
//SPDX-License-Identifier: BUSL-1.1

pragma solidity >=0.8.4;
import "./HTokenInternalI.sol";

/**
 * @title   Interface of HToken
 * @author  Honey Labs Inc.
 * @custom:coauthor BowTiedPickle
 * @custom:coauthor m4rio
 */
interface HTokenI is HTokenInternalI {
  /**
   * @notice  Deposit underlying ERC-20 asset and mint hTokens
   * @dev     Pull pattern, user must approve the contract before calling. If _to is address(0) then it becomes msg.sender
   * @param   _amount   Quantity of underlying ERC-20 to transfer in
   * @param   _to       Target address to mint hTokens to
   */
  function depositUnderlying(uint256 _amount, address _to) external;

  /**
   * @notice  Redeem a specified amount of hTokens for their underlying ERC-20 asset
   * @param   _amount   Quantity of hTokens to redeem for underlying ERC-20
   */
  function redeem(uint256 _amount) external;

  /**
   * @notice  Withdraws the specified amount of underlying ERC-20 asset, consuming the minimum amount of hTokens necessary
   * @param   _amount   Quantity of underlying ERC-20 tokens to withdraw
   */
  function withdraw(uint256 _amount) external;

  /**
   * @notice  Deposit multiple specified tokens of the underlying ERC-721 asset and mint ERC-1155 deposit coupon NFTs
   * @dev     Pull pattern, user must approve the contract before calling.
   * @param   _collateralIds  Token IDs of underlying ERC-721 to be transferred in
   */
  function depositCollateral(uint256[] calldata _collateralIds) external;

  /**
   * @notice  Sender borrows assets from the protocol against the specified collateral asset, without a referral code
   * @dev     Collateral must be deposited first.
   * @param   _borrowAmount   Amount of underlying ERC-20 to borrow
   * @param   _collateralId   Token ID of underlying ERC-721 to be borrowed against
   */
  function borrow(uint256 _borrowAmount, uint256 _collateralId) external;

  /**
   * @notice  Sender borrows assets from the protocol against the specified collateral asset, using a referral code
   * @param   _borrowAmount   Amount of underlying ERC-20 to borrow
   * @param   _collateralId   Token ID of underlying ERC-721 to be borrowed against
   * @param   _referral       Referral code as a plain string
   * @param   _signature      Signed message authorizing the referral, provided by Honey Labs
   */
  function borrowReferred(
    uint256 _borrowAmount,
    uint256 _collateralId,
    string calldata _referral,
    bytes calldata _signature
  ) external;

  /**
   * @notice  Sender repays a borrow taken against the specified collateral asset
   * @dev     Pull pattern, user must approve the contract before calling.
   * @param   _repayAmount    Amount of underlying ERC-20 to repay
   * @param   _collateralId   Token ID of underlying ERC-721 to be repaid against
   */
  function repayBorrow(
    uint256 _repayAmount,
    uint256 _collateralId,
    address _to
  ) external;

  /**
   * @notice  Burn deposit coupon NFTs and withdraw the associated underlying ERC-721 NFTs
   * @param   _collateralIds  Token IDs of underlying ERC-721 to be withdrawn
   */
  function withdrawCollateral(uint256[] calldata _collateralIds) external;

  /**
   * @notice  Trigger transfer of an NFT to the liquidation contract
   * @param   _collateralId   Token ID of underlying ERC-721 to be liquidated
   */
  function liquidateBorrow(uint256 _collateralId) external;

  /**
   * @notice  Pay off the entirety of a liquidated debt position and burn the coupon
   * @dev     May only be called by the liquidator
   * @param   _borrower       Owner of the debt position
   * @param   _collateralId   Token ID of underlying ERC-721 to be closed out
   */
  function closeoutLiquidation(address _borrower, uint256 _collateralId) external;

  /**
   * @notice  Accrues all interest due to the protocol
   * @dev     Call this before performing calculations using 'totalBorrows' or other contract-wide quantities
   */
  function accrueInterest() external;

  // ----- Utility functions -----

  /**
   * @notice  Sweep accidental ERC-20 transfers to this contract.
   * @dev     Tokens are sent to the DAO for later distribution
   * @param   _token  The address of the ERC-20 token to sweep
   */
  function sweepToken(IERC20 _token) external;
}

File 22 of 24 : HTokenInternalI.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";

/**
 * @title   Interface of HToken Internal
 * @author  Honey Labs Inc.
 * @custom:coauthor m4rio
 * @custom:coauthor BowTiedPickle
 */
interface HTokenInternalI is IERC1155, IAccessControl {
  struct Coupon {
    uint32 id; //Coupon's id
    uint8 active; // Coupon activity status
    address owner; // Who is the current owner of this coupon
    uint256 collateralId; // tokenId of the collateral collection that is borrowed against
    uint256 borrowAmount; // Principal borrow balance, denominated in underlying ERC20 token.
    uint256 debtShares; // Debt shares, keeps the shares of total debt by the protocol
  }

  struct Collateral {
    uint256 collateralId; // TokenId of the collateral
    bool active; // Collateral activity status
  }

  // ----- Informational -----

  function decimals() external view returns (uint8);

  function name() external view returns (string memory);

  function symbol() external view returns (string memory);

  // ----- Addresses -----

  function collateralToken() external view returns (IERC721);

  function underlyingToken() external view returns (IERC20);

  // ----- Protocol Accounting -----

  function totalBorrows() external view returns (uint256);

  function totalReserves() external view returns (uint256);

  function totalSupply() external view returns (uint256);

  function totalFuseFees() external view returns (uint256);

  function totalAdminCommission() external view returns (uint256);

  function accrualBlockNumber() external view returns (uint256);

  function interestIndexStored() external view returns (uint256);

  function totalProtocolCommissions() external view returns (uint256);

  function userToCoupons(address _user) external view returns (uint256);

  function collateralPerBorrowCouponId(uint256 _couponId) external view returns (Collateral memory);

  function borrowCoupons(uint256 _collateralId) external view returns (Coupon memory);

  // ----- Views -----

  /**
   * @notice  Get the outstanding debt of a collateral
   * @dev     Simulates accrual of interest
   * @param   _collateralId   Token ID of underlying ERC-721
   * @return  Outstanding debt in units of underlying ERC-20
   */
  function getDebtForCollateral(uint256 _collateralId) external view returns (uint256);

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

  /**
   * @notice  Get the outstanding debt of a coupon
   * @dev     Simulates accrual of interest
   * @param   _couponId   ID of the coupon
   * @return  Outstanding debt in units of underlying ERC-20
   */
  function getDebtForCoupon(uint256 _couponId) external view returns (uint256);

  /**
   * @notice  Gets balance of this contract in terms of the underlying excluding the fees
   * @dev     This excludes the value of the current message, if any
   * @return  The quantity of underlying ERC-20 tokens owned by this contract
   */
  function getCashPrior() external view returns (uint256);

  /**
   * @notice  Get a snapshot of the account's balances, and the cached exchange rate
   * @dev     This is used by controller 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  Get the outstanding debt of the protocol
   * @return  Protocol debt
   */
  function getDebt() external view returns (uint256);

  /**
   * @notice  Returns protocol fees
   * @return  Reserve factor mantissa
   * @return  Admin fee mantissa
   * @return  Hive fee mantissa
   * @return  Initial exchange rate mantissa
   * @return  Maximum borrow rate mantissa
   */
  function getProtocolFees()
    external
    view
    returns (
      uint256,
      uint256,
      uint256,
      uint256,
      uint256
    );

  /**
   * @notice  Returns different addresses of the protocol
   * @return  Liquidator address
   * @return  HTokenHelper address
   * @return  Controller address
   * @return  Admin Fee Receiver address
   * @return  Hive Fee Receiver address
   * @return  Interest Model address
   * @return  Referral Pool address
   * @return  DAO address
   */
  function getAddresses()
    external
    view
    returns (
      address,
      address,
      address,
      address,
      address,
      address,
      address,
      address
    );

  /**
   * @notice  Get the last minted coupon ID
   * @return  The last minted coupon ID
   */
  function idCounter() external view returns (uint256);

  /**
   * @notice  Get the coupon for a specific collateral NFT
   * @param   _collateralId   Token ID of underlying ERC-721
   * @return  Coupon
   */
  function getSpecificCouponByCollateralId(uint256 _collateralId) external view returns (Coupon memory);

  /**
   * @notice  Calculate the prevailing interest due per token of debt principal
   * @return  Mantissa formatted interest rate per token of debt
   */
  function interestIndex() external view returns (uint256);

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

  /**
   * @notice  Calculates the exchange rate from the ERC-20 underlying to the HToken
   * @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  Add to or take away from reserves
   * @dev     Accrues interest
   * @param   _amount  Quantity of underlying ERC-20 token to change the reserves by
   */
  function _modifyReserves(uint256 _amount, bool _add) external;

  /**
   * @notice  Set new admin fee mantissas
   * @dev     Accrues interest
   * @param   _newAdminCommissionMantissa        New admin fee mantissa
   */
  function _setAdminCommission(uint256 _newAdminCommissionMantissa) external;

  /**
   * @notice  Set new protocol commission and reserve factor mantissas
   * @dev     Accrues interest
   * @param   _newProtocolCommissionMantissa         New protocol commission mantissa
   * @param   _newReserveFactorMantissa   New reserve factor mantissa
   */
  function _setProtocolFees(uint256 _newProtocolCommissionMantissa, uint256 _newReserveFactorMantissa) external;

  /**
   * @notice  Sets a new admin fee receiver
   * @param   _newAddress   Address of the new admin fee receiver
   * @param   _target       Target ID of the address to be set
   */
  function _setAddressMarketAdmin(address _newAddress, uint256 _target) external;
}

File 23 of 24 : PermissionlessOracleI.sol
//SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.4;

import "./HTokenI.sol";

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

/**
 * @title   PermissionlessOracleI interface for the Permissionless oracle
 * @author  Honey Labs Inc.
 * @custom:coauthor BowTiedPickle
 * @custom:coauthor m4rio
 */
interface PermissionlessOracleI {
  /**
   * @notice returns the price (in eth) for the floor of a collection
   * @param _collection address of the collection
   * @param _decimals adjust decimals of the returned price
   */
  function getFloorPrice(address _collection, uint256 _decimals) external view returns (uint128, uint128);

  /**
   * @notice returns the latest price for a given pair
   * @param _erc20 the erc20 we want to get the price for in USD
   * @param _decimals decimals to denote the result in
   */
  function getUnderlyingPriceInUSD(IERC20 _erc20, uint256 _decimals) external view returns (uint256);

  /**
   * @notice get price of eth
   * @param _decimals adjust decimals of the returned price
   */
  function getEthPrice(uint256 _decimals) external view returns (uint256);

  /**
   * @notice get price feeds for a token
   * @return returns the Chainlink Aggregator interface
   */
  function priceFeeds(IERC20 _token) external view returns (AggregatorV3Interface);

  /**
   * @notice returns the update threshold for a specific _collection
   */
  function updateThreshold(address _collection) external view returns (uint256);

  /**
   * @notice returns the number of floors for a specific _collection
   * @param _address address of the collection
   *
   */
  function getNoOfFloors(address _address) external view returns (uint256);

  /**
   * @notice returns the last updated timestamp for a specific _collection
   * @param _collection address of the collection
   *
   */
  function getLastUpdated(address _collection) external view returns (uint256);
}

File 24 of 24 : ErrorReporter.sol
//SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.15;

error Unauthorized();
error AccrueInterestError(Error error);
error WrongParams();
error Unexpected(string error);
error InvalidCoupon();
error ControllerError(Error error);
error AdminError(Error error);
error MarketError(Error error);
error HTokenError(Error error);
error LiquidatorError(Error error);
error ControlPanelError(Error error);
error HTokenFactoryError(Error error);
error PausedAction();
error NotOwner();
error ExternalFailure(string error);
error Initialized();
error Uninitialized();
error OracleNotUpdated();
error TransferError();
error StalePrice();

/**
 * @title   Errors reported across Honey Labs Inc. contracts
 * @author  Honey Labs Inc.
 * @custom:coauthor BowTiedPickle
 * @custom:coauthor m4rio
 */
enum Error {
  UNAUTHORIZED, //0
  INSUFFICIENT_LIQUIDITY,
  INVALID_COLLATERAL_FACTOR,
  MAX_MARKETS_IN,
  MARKET_NOT_LISTED,
  MARKET_ALREADY_LISTED, //5
  MARKET_CAP_BORROW_REACHED,
  MARKET_NOT_FRESH,
  PRICE_ERROR,
  BAD_INPUT,
  AMOUNT_ZERO, //10
  NO_DEBT,
  LIQUIDATION_NOT_ALLOWED,
  WITHDRAW_NOT_ALLOWED,
  INITIAL_EXCHANGE_MANTISSA,
  TRANSFER_ERROR, //15
  COUPON_LOOKUP,
  TOKEN_INSUFFICIENT_CASH,
  BORROW_RATE_TOO_BIG,
  NONZERO_BORROW_BALANCE,
  AMOUNT_TOO_BIG, //20
  AUCTION_NOT_ACTIVE,
  AUCTION_FINISHED,
  AUCTION_NOT_FINISHED,
  AUCTION_BID_TOO_LOW,
  AUCTION_NO_BIDS, //25
  CLAWBACK_WINDOW_EXPIRED,
  CLAWBACK_WINDOW_NOT_EXPIRED,
  REFUND_NOT_OWED,
  TOKEN_LOOKUP_ERROR,
  INSUFFICIENT_WINNING_BID, //30
  TOKEN_DEBT_NONEXISTENT,
  AUCTION_SETTLE_FORBIDDEN,
  NFT20_PAIR_NOT_FOUND,
  NFTX_PAIR_NOT_FOUND,
  TOKEN_NOT_PRESENT, //35
  CANCEL_TOO_SOON,
  AUCTION_USER_NOT_FOUND,
  NOT_FOUND,
  INVALID_MAX_LTV_FACTOR,
  BALANCE_INSUFFICIENT, //40
  ORACLE_NOT_SET,
  MARKET_INVALID,
  FACTORY_INVALID_COLLATERAL,
  FACTORY_INVALID_UNDERLYING,
  FACTORY_INVALID_ORACLE, //45
  FACTORY_DEPLOYMENT_FAILED,
  REPAY_NOT_ALLOWED,
  NONZERO_UNDERLYING_BALANCE,
  INVALID_ACTION,
  ORACLE_IS_PRESENT, //50
  FACTORY_INVALID_UNDERLYING_DECIMALS,
  FACTORY_INVALID_INTEREST_RATE_MODEL
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 300
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"enum Error","name":"error","type":"uint8"}],"name":"ControllerError","type":"error"},{"inputs":[{"internalType":"enum Error","name":"error","type":"uint8"}],"name":"MarketError","type":"error"},{"inputs":[],"name":"OracleNotUpdated","type":"error"},{"inputs":[],"name":"PausedAction","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"WrongParams","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"string","name":"_action","type":"string"},{"indexed":false,"internalType":"bool","name":"_pauseState","type":"bool"}],"name":"ActionPausedhToken","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_oldBorrowCapGuardian","type":"address"},{"indexed":false,"internalType":"address","name":"_newBorrowCapGuardian","type":"address"}],"name":"BorrowCapGuardianUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"_newBorrowCap","type":"uint256"}],"name":"BorrowCapUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_market","type":"address"},{"indexed":false,"internalType":"uint256","name":"_fee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_referralFee","type":"uint256"}],"name":"BorrowFeePerMarketUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"_oldCollateralFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newCollateralFactorMantissa","type":"uint256"}],"name":"CollateralFactorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"_paused","type":"bool"}],"name":"ControllerPaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"address","name":"_account","type":"address"}],"name":"MarketEntered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"address","name":"_account","type":"address"}],"name":"MarketExited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"MarketListed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"MarketRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"_oldMaxLTVFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_newMaxLTVFactorMantissa","type":"uint256"}],"name":"NewMaxLTVFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract PermissionlessOracleI","name":"_oldPriceOracle","type":"address"},{"indexed":false,"internalType":"contract PermissionlessOracleI","name":"_newPriceOracle","type":"address"}],"name":"PriceOracleUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_oldSigner","type":"address"},{"indexed":false,"internalType":"address","name":"_newSigner","type":"address"}],"name":"ReferralSignerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FACTORY_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"bool","name":"_state","type":"bool"},{"internalType":"uint256","name":"_target","type":"uint256"}],"name":"_pauseComponent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_state","type":"bool"}],"name":"_pauseController","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"_removeMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_market","type":"address"},{"internalType":"uint256","name":"_fee","type":"uint256"},{"internalType":"uint256","name":"_referralFee","type":"uint256"}],"name":"_setBorrowFeePerMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"uint256","name":"_newLTVFactorMantissa","type":"uint256"},{"internalType":"uint256","name":"_newCollateralFactorMantissa","type":"uint256"}],"name":"_setFactors","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI[]","name":"_hTokens","type":"address[]"},{"internalType":"uint256[]","name":"_newBorrowCaps","type":"uint256[]"}],"name":"_setMarketBorrowCaps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"contract PermissionlessOracleI","name":"_newOracle","type":"address"}],"name":"_setPriceOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newSigner","type":"address"}],"name":"_setReferralSigner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"_supportMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_borrower","type":"address"},{"internalType":"uint256","name":"_collateralId","type":"uint256"},{"internalType":"uint256","name":"_borrowAmount","type":"uint256"}],"name":"borrowAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"","type":"address"}],"name":"borrowCaps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowFeeCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_account","type":"address"}],"name":"checkMembership","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_collateral","type":"address"}],"name":"collateralExistsInMarkets","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_depositor","type":"address"},{"internalType":"uint256","name":"_collateralId","type":"uint256"}],"name":"depositCollateralAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_depositor","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"depositUnderlyingAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI[]","name":"_hTokens","type":"address[]"}],"name":"enterMarkets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"exitMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"string","name":"_referral","type":"string"},{"internalType":"bytes","name":"_signature","type":"bytes"}],"name":"getBorrowFeePerMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_account","type":"address"},{"internalType":"uint256","name":"_collateralId","type":"uint256"},{"internalType":"uint256","name":"_redeemTokens","type":"uint256"},{"internalType":"uint256","name":"_borrowAmount","type":"uint256"}],"name":"getHypotheticalAccountLiquidity","outputs":[{"internalType":"uint256","name":"liquidityTillLiquidation","type":"uint256"},{"internalType":"uint256","name":"shortfall","type":"uint256"},{"internalType":"uint256","name":"liquidityTillLTV","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"getMarketData","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"getReferralBorrowFeePerMarket","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"uint256","name":"_target","type":"uint256"}],"name":"isActionPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"uint256","name":"_collateralId","type":"uint256"}],"name":"liquidationAllowed","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"marketExists","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"","type":"address"}],"name":"marketPausedInfo","outputs":[{"internalType":"bool","name":"borrowPaused","type":"bool"},{"internalType":"bool","name":"transferPaused","type":"bool"},{"internalType":"bool","name":"redeemPaused","type":"bool"},{"internalType":"bool","name":"liquidationPaused","type":"bool"},{"internalType":"bool","name":"repayBorrowPaused","type":"bool"},{"internalType":"bool","name":"depositPaused","type":"bool"},{"internalType":"bool","name":"depositCollateralPaused","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"oracle","outputs":[{"internalType":"contract PermissionlessOracleI","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"address","name":"_redeemer","type":"address"},{"internalType":"uint256","name":"_redeemTokens","type":"uint256"}],"name":"redeemAllowed","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralSigner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"uint256","name":"_repayAmount","type":"uint256"},{"internalType":"uint256","name":"_collateralId","type":"uint256"}],"name":"repayBorrowAllowed","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"_interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"}],"name":"transferAllowed","outputs":[],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_underlying","type":"address"}],"name":"underlyingExistsInMarkets","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract HTokenI","name":"_hToken","type":"address"},{"internalType":"uint256","name":"_collateralId","type":"uint256"}],"name":"withdrawCollateralAllowed","outputs":[],"stateMutability":"view","type":"function"}]

60806040523480156200001157600080fd5b506001600d55600e805460ff191690556200002e60003362000060565b6200005a7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a3362000060565b620001c9565b6200006c828262000070565b5050565b620000878282620000b360201b620024761760201c565b6000828152600c60209081526040909120620000ae918390620024fc62000157821b17901c565b505050565b6000828152600b602090815260408083206001600160a01b038516845290915290205460ff166200006c576000828152600b602090815260408083206001600160a01b03851684529091529020805460ff19166001179055620001133390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60006200016e836001600160a01b03841662000177565b90505b92915050565b6000818152600183016020526040812054620001c05750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915562000171565b50600062000171565b613bc080620001d96000396000f3fe608060405234801561001057600080fd5b50600436106102ea5760003560e01c8063a30c302d1161018c578063cd11e70a116100ee578063e2cded3211610097578063eb37d34911610071578063eb37d349146107a3578063ede4edd0146107cf578063edf04a7d146107e257600080fd5b8063e2cded3214610756578063e63ab1e914610769578063eabe7d911461079057600080fd5b8063d547741f116100c8578063d547741f1461071f578063dad0eeb714610732578063e124075f1461074357600080fd5b8063cd11e70a146106e6578063cf826615146106f9578063d286947b1461070c57600080fd5b8063b3623f3111610150578063c1b1f7001161012a578063c1b1f700146106ad578063c2998238146106c0578063ca15c873146106d357600080fd5b8063b3623f31146105e5578063b5c2f93d146105f8578063baafee3e1461060b57600080fd5b8063a30c302d1461053d578063a76b3fda14610599578063a9ab107f146105ac578063a9f70f15146105bf578063af9ed5ab146105d257600080fd5b80635c975abb1161025057806384388115116101f957806391d14854116101d357806391d14854146104e2578063929fe9a1146104f5578063a217fddf1461053557600080fd5b8063843881151461047b57806384a558dc1461048e5780639010d07c146104b757600080fd5b806370d064d11161022a57806370d064d114610427578063712ca0181461043a5780637e361b111461044d57600080fd5b80635c975abb146103f6578063607ef6c1146104015780636e3794451461041457600080fd5b806317064f63116102b257806336568abe1161028c57806336568abe146103b95780634a584432146103cc57806354fd4d50146103ec57600080fd5b806317064f6314610375578063248a9ca3146103835780632f2ff15d146103a657600080fd5b806301ffc9a7146102ef57806304a0fb1714610317578063059a80081461033a5780630b777a7c1461034f578063151eeb5514610362575b600080fd5b6103026102fd36600461341a565b61080a565b60405190151581526020015b60405180910390f35b61032c600080516020613b4b83398151915281565b60405190815260200161030e565b61034d610348366004613459565b610841565b005b61034d61035d3660046134ad565b610a58565b61034d6103703660046134ee565b610e7b565b61032c66470de4df82000081565b61032c61039136600461350b565b6000908152600b602052604090206001015490565b61034d6103b4366004613524565b610f03565b61034d6103c7366004613524565b610f28565b61032c6103da3660046134ee565b60086020526000908152604090205481565b61032c620f424081565b600e5460ff16610302565b61034d61040f366004613599565b610fa2565b61034d610422366004613605565b61115d565b61034d610435366004613631565b611217565b6103026104483660046134ee565b611324565b61046061045b36600461365f565b611351565b6040805193845260208401929092529082015260600161030e565b61034d6104893660046136b0565b61138e565b61032c61049c3660046134ee565b6001600160a01b03166000908152600a602052604090205490565b6104ca6104c53660046136e5565b611413565b6040516001600160a01b03909116815260200161030e565b6103026104f0366004613524565b611432565b610302610503366004613631565b6001600160a01b0391821660009081526002602090815260408083209390941682526003909201909152205460ff1690565b61032c600081565b61057c61054b3660046134ee565b6001600160a01b0316600090815260026020819052604090912080546001820154919092015460ff90921692909190565b60408051931515845260208401929092529082015260600161030e565b61034d6105a73660046134ee565b61145d565b61034d6105ba366004613707565b6116e6565b6103026105cd3660046134ee565b6117fa565b6103026105e0366004613605565b611807565b61034d6105f3366004613605565b611993565b61034d6106063660046134ee565b611a61565b61066c6106193660046134ee565b60036020526000908152604090205460ff808216916101008104821691620100008204811691630100000081048216916401000000008204811691650100000000008104821691600160301b9091041687565b60408051971515885295151560208801529315159486019490945290151560608501521515608084015290151560a0830152151560c082015260e00161030e565b61034d6106bb366004613737565b611c47565b61034d6106ce366004613754565b611cc1565b61032c6106e136600461350b565b611d27565b61034d6106f43660046136b0565b611d3e565b61034d6107073660046136b0565b611e30565b61030261071a3660046134ee565b611fd9565b61034d61072d366004613524565b611fe6565b6000546001600160a01b03166104ca565b61034d610751366004613707565b61200b565b61034d6107643660046134ee565b612054565b61032c7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b61034d61079e366004613707565b6120e4565b6104ca6107b13660046134ee565b6001600160a01b039081166000908152600160205260409020541690565b61034d6107dd3660046134ee565b6121ee565b6107f56107f03660046137d8565b612357565b6040805192835290151560208301520161030e565b60006001600160e01b03198216630b7f5a3560e31b148061083b57506001600160e01b031982166372fe09a560e01b145b92915050565b610849612511565b610851612559565b6001600160a01b03841660009081526003602052604090205460ff161561088b5760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b03848116600090815260016020526040902054166108cf57602960405163064b261f60e01b81526004016108c6919061385b565b60405180910390fd5b6001600160a01b03808516600090815260026020908152604080832093871683526003840190915290205460ff1661095d57336001600160a01b03861614610929576040516282b42960e81b815260040160405180910390fd5b61093385856125b2565b6001600160a01b038416600090815260038201602052604090205460ff1661095d5761095d613883565b6001600160a01b0385166000908152600860205260409020548015610a1257600083876001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109e19190613899565b6109eb91906138c8565b9050818110610a1057600660405163614fcefb60e01b81526004016108c6919061385b565b505b6000610a1f87868661267a565b509150508015610a4557600160405163064b261f60e01b81526004016108c6919061385b565b505050610a526001600d55565b50505050565b610a63600033611432565b158015610a975750610a957f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a33611432565b155b15610ab4576040516282b42960e81b815260040160405180910390fd5b6001600160a01b03831660009081526002602052604090205460ff16610af057600460405163614fcefb60e01b81526004016108c6919061385b565b80600003610b65576001600160a01b038316600081815260036020908152604091829020805460ff1916861515908117909155825183815260069381019390935265426f72726f7760d01b606084015290820152600080516020613b6b833981519152906080015b60405180910390a2505050565b80600103610bdb576001600160a01b0383166000818152600360205260409081902080548515156101000261ff001990911617905551600080516020613b6b83398151915290610b589085906040808252600890820152672a3930b739b332b960c11b6060820152901515602082015260800190565b80600203610c51576001600160a01b038316600081815260036020526040908190208054851515620100000262ff00001990911617905551600080516020613b6b83398151915290610b5890859060408082526006908201526552656465656d60d01b6060820152901515602082015260800190565b80600303610cce576001600160a01b03831660008181526003602052604090819020805485151563010000000263ff0000001990911617905551600080516020613b6b83398151915290610b589085906040808252600b908201526a2634b8bab4b230ba34b7b760a91b6060820152901515602082015260800190565b80600403610d4d576001600160a01b0383166000818152600360205260409081902080548515156401000000000264ff000000001990911617905551600080516020613b6b83398151915290610b589085906040808252600b908201526a5265706179426f72726f7760a81b6060820152901515602082015260800190565b80600503610dd4576001600160a01b038316600081815260036020526040908190208054851515650100000000000265ff00000000001990911617905551600080516020613b6b83398151915290610b589085906040808252601190820152704465706f736974556e6465726c79696e6760781b6060820152901515602082015260800190565b80600603610e5a576001600160a01b038316600081815260036020526040908190208054851515600160301b0266ff0000000000001990911617905551600080516020613b6b83398151915290610b5890859060408082526011908201527011195c1bdcda5d10dbdb1b185d195c985b607a1b6060820152901515602082015260800190565b603160405163064b261f60e01b81526004016108c6919061385b565b505050565b610e83612511565b6001600160a01b038116600090815260036020526040902054610100900460ff1615610ec25760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b0381166000908152600260205260409020805460ff16610eff57600460405163614fcefb60e01b81526004016108c6919061385b565b5050565b6000828152600b6020526040902060010154610f1e8161286f565b610e768383612879565b6001600160a01b0381163314610f985760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016108c6565b610eff828261289b565b610fad600033611432565b610fc9576040516282b42960e81b815260040160405180910390fd5b8281811580610fd85750808214155b15610ff657604051635863f78960e01b815260040160405180910390fd5b60005b82811015611154576000878783818110611015576110156138e0565b905060200201602081019061102a91906134ee565b6001600160a01b038116600090815260026020526040902080549192509060ff1661106b57600460405163614fcefb60e01b81526004016108c6919061385b565b86868481811061107d5761107d6138e0565b90506020020135600860008b8b8781811061109a5761109a6138e0565b90506020020160208101906110af91906134ee565b6001600160a01b031681526020810191909152604001600020558888848181106110db576110db6138e0565b90506020020160208101906110f091906134ee565b6001600160a01b03167f84d2db42497fc6f1882756be420935d982025ad8a2a903dfb83638a09e49a77588888681811061112c5761112c6138e0565b9050602002013560405161114291815260200190565b60405180910390a25050600101610ff9565b50505050505050565b611165612511565b6001600160a01b0382166000908152600360205260409020546301000000900460ff16156111a65760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b03828116600090815260016020526040902054166111e157602960405163064b261f60e01b81526004016108c6919061385b565b60006111ef8383600061267a565b5091505080600003610e7657600c60405163064b261f60e01b81526004016108c6919061385b565b611222600033611432565b1580156112445750611242600080516020613b4b83398151915233611432565b155b15611261576040516282b42960e81b815260040160405180910390fd5b6001600160a01b0382166000908152600260205260409020805460ff1661129e57600460405163614fcefb60e01b81526004016108c6919061385b565b6001600160a01b038381166000908152600160209081526040918290205482519084168152928516908301527f56b5f80d8cac1479698aa7d01605fd6111e90b15fc4d2b377417f46034876cbd910160405180910390a1506001600160a01b03918216600090815260016020526040902080546001600160a01b03191691909216179055565b600061132e612511565b506001600160a01b03811660009081526002602052604090205460ff165b919050565b600080808415611370576113668888876128bd565b9093509150611383565b61137b88878661267a565b919450925090505b955095509592505050565b611396612511565b6001600160a01b038316600090815260036020526040902054640100000000900460ff16156113d85760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b0383811660009081526001602052604090205416610e7657602960405163064b261f60e01b81526004016108c6919061385b565b6000828152600c6020526040812061142b90836129fe565b9392505050565b6000918252600b602090815260408084206001600160a01b0393909316845291905290205460ff1690565b611468600033611432565b15801561148a5750611488600080516020613b4b83398151915233611432565b155b156114a7576040516282b42960e81b815260040160405180910390fd5b6001600160a01b0381166000908152600260205260409020805460ff16156114e557600560405163614fcefb60e01b81526004016108c6919061385b565b6040516301ffc9a760e01b81526341277d7560e01b60048201526001600160a01b038316906301ffc9a790602401602060405180830381865afa158015611530573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061155491906138f6565b61157157604051635863f78960e01b815260040160405180910390fd5b805460ff1916600117815560006002820181905560408051632495a59960e01b815290516001600160a01b03851691632495a5999160048083019260209291908290030181865afa1580156115ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ee9190613913565b90506000836001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611630573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116549190613913565b90506001600160a01b038216158061167357506001600160a01b038116155b1561169457602a60405163064b261f60e01b81526004016108c6919061385b565b61169f6004836124fc565b506116ab6006826124fc565b506040516001600160a01b038516907fcf583bb0c569eb967f806b11601c4cb93c10310485c67add5f8362c2f212321f90600090a250505050565b6116ee612511565b6001600160a01b03831660009081526003602052604090205465010000000000900460ff16156117315760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b038381166000908152600160205260409020541661176c57602960405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b03808416600090815260026020908152604080832093861683526003840190915290205460ff16610a5257336001600160a01b038516146117c6576040516282b42960e81b815260040160405180910390fd5b6117d084846125b2565b6001600160a01b038316600090815260038201602052604090205460ff16610a5257610a52613883565b600061083b600483612a0a565b6001600160a01b03821660009081526002602052604081205460ff1661184357600460405163614fcefb60e01b81526004016108c6919061385b565b8160000361186d57506001600160a01b03821660009081526003602052604090205460ff1661083b565b8160010361189c57506001600160a01b038216600090815260036020526040902054610100900460ff1661083b565b816002036118cc57506001600160a01b03821660009081526003602052604090205462010000900460ff1661083b565b816003036118fd57506001600160a01b0382166000908152600360205260409020546301000000900460ff1661083b565b8160040361192f57506001600160a01b038216600090815260036020526040902054640100000000900460ff1661083b565b8160050361196257506001600160a01b03821660009081526003602052604090205465010000000000900460ff1661083b565b81600603610e5a57506001600160a01b038216600090815260036020526040902054600160301b900460ff1661083b565b61199b612511565b6001600160a01b03821660009081526002602052604090205460ff166119d757600460405163614fcefb60e01b81526004016108c6919061385b565b6040516305b71aed60e51b8152600481018290526001600160a01b0383169063b6e35da090602401602060405180830381865afa158015611a1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a409190613899565b15610eff57600d60405163064b261f60e01b81526004016108c6919061385b565b611a6c600033611432565b611a88576040516282b42960e81b815260040160405180910390fd5b6001600160a01b0381166000908152600260205260409020805460ff16611ac557600460405163614fcefb60e01b81526004016108c6919061385b565b6001600160a01b038281166000908152600160205260409020541615611b0157603260405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b0382166000818152600260208181526040808420805460ff19168155600181018590559092018390558151632495a59960e01b81529151929392632495a5999260048082019392918290030181865afa158015611b69573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b8d9190613913565b90506000836001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bcf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bf39190613913565b9050611c00600483612a2c565b50611c0c600682612a2c565b506040516001600160a01b038516907f59d7b1e52008dc342c9421dadfc773114b914a65682a4e4b53cf60a970df0d7790600090a250505050565b611c52600033611432565b611c6e576040516282b42960e81b815260040160405180910390fd5b8015611c8157611c7c612a41565b611c89565b611c89612a9b565b60405181151581527f39567b785870bed9653807a175b95d7b0d9143f81efd6442752171db25032fe59060200160405180910390a150565b611cc9612511565b611cd1612559565b8060005b81811015611d1b576000848483818110611cf157611cf16138e0565b9050602002016020810190611d0691906134ee565b9050611d1281336125b2565b50600101611cd5565b5050610eff6001600d55565b6000818152600c6020526040812061083b90612ad4565b66470de4df820000821180611d59575066470de4df82000081115b15611d7a57601460405163064b261f60e01b81526004016108c6919061385b565b611d85600033611432565b158015611da75750611da5600080516020613b4b83398151915233611432565b155b15611dc4576040516282b42960e81b815260040160405180910390fd5b60408051838152602081018390526001600160a01b038516917f54a36fd3638bbd8551e3ec6eccadac6d84e7f13a61e1d17551eafa5061d3e22c910160405180910390a26001600160a01b03909216600090815260096020908152604080832093909355600a90522055565b611e3b600033611432565b158015611e5d5750611e5b600080516020613b4b83398151915233611432565b155b15611e7a576040516282b42960e81b815260040160405180910390fd5b81600003611e9e57602760405163064b261f60e01b81526004016108c6919061385b565b818111611ec157600260405163064b261f60e01b81526004016108c6919061385b565b80670c7d713b49da00001015611eed57600260405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b0383811660009081526001602052604090205416611f2857602960405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b0383166000818152600260208181526040928390209182015483519081529081018590529092917f4fce63c9b39fc1b7743c9f477629998ceb9a8cb4abbd2084083bb9bddcbf8ec7910160405180910390a2600181015460408051918252602082018590526001600160a01b038616917f4d72e9a8c74de24e3129411d9159812e76eb75c30bf9c5710d67106a12b522cc910160405180910390a260028101919091556001015550565b600061083b600683612a0a565b6000828152600b60205260409020600101546120018161286f565b610e76838361289b565b612013612511565b6001600160a01b038316600090815260036020526040902054600160301b900460ff16156117315760405163a59392f560e01b815260040160405180910390fd5b61205f600033611432565b61207b576040516282b42960e81b815260040160405180910390fd5b600054604080516001600160a01b03928316815291831660208301527f6f4d0691827ad0350d7d1ce5f71b0158531998b9e0ad46cf91250d4c9aac8d10910160405180910390a1600080546001600160a01b0319166001600160a01b0392909216919091179055565b6120ec612511565b6001600160a01b03831660009081526003602052604090205462010000900460ff161561212c5760405163a59392f560e01b815260040160405180910390fd5b6001600160a01b038381166000908152600160205260409020541661216757602960405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b03808416600090815260026020908152604080832093861683526003840190915290205460ff166121b557602660405163064b261f60e01b81526004016108c6919061385b565b60006121c28585856128bd565b91505080156121e757600160405163064b261f60e01b81526004016108c6919061385b565b5050505050565b6121f6612511565b6121fe612559565b6040516361bfb47160e11b815233600482015260009081906001600160a01b0384169063c37f68e290602401606060405180830381865afa158015612247573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061226b9190613930565b50915091508160001461229457603060405163064b261f60e01b81526004016108c6919061385b565b80156122b657601360405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b0383166000908152600260209081526040808320338452600381019092529091205460ff166122ee5750505061234a565b336000818152600383016020908152604091829020805460ff1916905590519182526001600160a01b038616917fe699a64c18b07ac5b7301aa273f36a2287239eb9501d81950672794afba29a0d910160405180910390a25050505b6123546001600d55565b50565b600080600061241285858080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152505060405161240c92506123ac91508b908b9060200161395e565b60408051601f1981840301815282825280516020918201207f19457468657265756d205369676e6564204d6573736167653a0a33320000000084830152603c8085019190915282518085039091018152605c909301909152815191012090565b90612ade565b506000549091506001600160a01b0380831691160361244e575050506001600160a01b0385166000908152600a6020526040902054600161246c565b5050506001600160a01b038516600090815260096020526040812054905b9550959350505050565b6124808282611432565b610eff576000828152600b602090815260408083206001600160a01b03851684529091529020805460ff191660011790556124b83390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600061142b836001600160a01b038416612b23565b600e5460ff16156125575760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016108c6565b565b6002600d54036125ab5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016108c6565b6002600d55565b6001600160a01b0382166000908152600260205260409020805460ff166125ef57600460405163614fcefb60e01b81526004016108c6919061385b565b6001600160a01b038216600090815260038201602052604090205460ff161561261757505050565b6001600160a01b038281166000818152600384016020908152604091829020805460ff191660011790559051918252918516917f3ab23ab0d51cccc0c3085aec51f99228625aa1a922b3a8ca89a26b0f2027a1a5910160405180910390a2505050565b60008060008061268987612b72565b90506000876001600160a01b031663dd5a612c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156126cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126ef9190613899565b6040516305b71aed60e51b8152600481018990529091506000906001600160a01b038a169063b6e35da090602401602060405180830381865afa15801561273a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061275e9190613899565b90508260000361278457600860405163064b261f60e01b81526004016108c6919061385b565b600061279088836138c8565b9050828811156127b657600160405163064b261f60e01b81526004016108c6919061385b565b6001600160a01b038a16600090815260026020526040812060010154670de0b6b3a7640000906127e790879061396e565b6127f1919061398d565b6001600160a01b038c1660009081526002602081905260409091200154909150670de0b6b3a76400009061282690879061396e565b612830919061398d565b9450818111156128495781850397508181039550612861565b8185111561285b578185039750612861565b84820396505b505050505093509350939050565b6123548133612f79565b6128838282612476565b6000828152600c60205260409020610e7690826124fc565b6128a58282612fd2565b6000828152600c60205260409020610e769082612a2c565b6040516361bfb47160e11b81526001600160a01b03838116600483015260009182918291829188169063c37f68e290602401606060405180830381865afa15801561290c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129309190613930565b92505091508482101561295957602860405163064b261f60e01b81526004016108c6919061385b565b6000670de0b6b3a764000061296e838861396e565b612978919061398d565b9050876001600160a01b031663dd5a612c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156129b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129dc9190613899565b9450848111156129f3576129f085826139af565b93505b505050935093915050565b600061142b8383613039565b6001600160a01b0381166000908152600183016020526040812054151561142b565b600061142b836001600160a01b038416613063565b612a49612511565b600e805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612a7e3390565b6040516001600160a01b03909116815260200160405180910390a1565b612aa3613156565b600e805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa33612a7e565b600061083b825490565b6000808251604103612b145760208301516040840151606085015160001a612b08878285856131a8565b94509450505050612b1c565b506000905060025b9250929050565b6000818152600183016020526040812054612b6a5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561083b565b50600061083b565b6001600160a01b03808216600081815260016020908152604080832054815163313ce56760e01b81529151939516938593909263313ce56792600480820193918290030181865afa158015612bcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bef91906139c6565b9050600080836001600160a01b0316637996eef0876001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612c41573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c659190613913565b6040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260ff861660248201526044016040805180830381865afa158015612cb1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cd59190613a00565b9150915042816001600160801b0316108015612dda5750836001600160a01b031663a1718c3d876001600160a01b031663b2016bd46040518163ffffffff1660e01b8152600401602060405180830381865afa158015612d39573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d5d9190613913565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa158015612da1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612dc59190613899565b612dd86001600160801b038316426139af565b115b15612df8576040516359fc9ea760e11b815260040160405180910390fd5b6000846001600160a01b031663297b5180886001600160a01b0316632495a5996040518163ffffffff1660e01b8152600401602060405180830381865afa158015612e47573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6b9190613913565b6040516001600160e01b031960e084901b1681526001600160a01b03909116600482015260ff87166024820152604401602060405180830381865afa158015612eb8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612edc9190613899565b60405163870d365d60e01b815260ff861660048201529091506000906001600160a01b0387169063870d365d90602401602060405180830381865afa158015612f29573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f4d9190613899565b905081612f63826001600160801b03871661396e565b612f6d919061398d565b98975050505050505050565b612f838282611432565b610eff57612f908161326c565b612f9b83602061327e565b604051602001612fac929190613a5f565b60408051601f198184030181529082905262461bcd60e51b82526108c691600401613ad4565b612fdc8282611432565b15610eff576000828152600b602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000826000018281548110613050576130506138e0565b9060005260206000200154905092915050565b6000818152600183016020526040812054801561314c5760006130876001836139af565b855490915060009061309b906001906139af565b90508181146131005760008660000182815481106130bb576130bb6138e0565b90600052602060002001549050808760000184815481106130de576130de6138e0565b6000918252602080832090910192909255918252600188019052604090208390555b855486908061311157613111613b07565b60019003818190600052602060002001600090559055856001016000868152602001908152602001600020600090556001935050505061083b565b600091505061083b565b600e5460ff166125575760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f742070617573656400000000000000000000000060448201526064016108c6565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311156131df5750600090506003613263565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015613233573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b03811661325c57600060019250925050613263565b9150600090505b94509492505050565b606061083b6001600160a01b03831660145b6060600061328d83600261396e565b6132989060026138c8565b67ffffffffffffffff8111156132b0576132b0613b1d565b6040519080825280601f01601f1916602001820160405280156132da576020820181803683370190505b509050600360fc1b816000815181106132f5576132f56138e0565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110613324576133246138e0565b60200101906001600160f81b031916908160001a905350600061334884600261396e565b6133539060016138c8565b90505b60018111156133cb576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110613387576133876138e0565b1a60f81b82828151811061339d5761339d6138e0565b60200101906001600160f81b031916908160001a90535060049490941c936133c481613b33565b9050613356565b50831561142b5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016108c6565b60006020828403121561342c57600080fd5b81356001600160e01b03198116811461142b57600080fd5b6001600160a01b038116811461235457600080fd5b6000806000806080858703121561346f57600080fd5b843561347a81613444565b9350602085013561348a81613444565b93969395505050506040820135916060013590565b801515811461235457600080fd5b6000806000606084860312156134c257600080fd5b83356134cd81613444565b925060208401356134dd8161349f565b929592945050506040919091013590565b60006020828403121561350057600080fd5b813561142b81613444565b60006020828403121561351d57600080fd5b5035919050565b6000806040838503121561353757600080fd5b82359150602083013561354981613444565b809150509250929050565b60008083601f84011261356657600080fd5b50813567ffffffffffffffff81111561357e57600080fd5b6020830191508360208260051b8501011115612b1c57600080fd5b600080600080604085870312156135af57600080fd5b843567ffffffffffffffff808211156135c757600080fd5b6135d388838901613554565b909650945060208701359150808211156135ec57600080fd5b506135f987828801613554565b95989497509550505050565b6000806040838503121561361857600080fd5b823561362381613444565b946020939093013593505050565b6000806040838503121561364457600080fd5b823561364f81613444565b9150602083013561354981613444565b600080600080600060a0868803121561367757600080fd5b853561368281613444565b9450602086013561369281613444565b94979496505050506040830135926060810135926080909101359150565b6000806000606084860312156136c557600080fd5b83356136d081613444565b95602085013595506040909401359392505050565b600080604083850312156136f857600080fd5b50508035926020909101359150565b60008060006060848603121561371c57600080fd5b833561372781613444565b925060208401356134dd81613444565b60006020828403121561374957600080fd5b813561142b8161349f565b6000806020838503121561376757600080fd5b823567ffffffffffffffff81111561377e57600080fd5b61378a85828601613554565b90969095509350505050565b60008083601f8401126137a857600080fd5b50813567ffffffffffffffff8111156137c057600080fd5b602083019150836020828501011115612b1c57600080fd5b6000806000806000606086880312156137f057600080fd5b85356137fb81613444565b9450602086013567ffffffffffffffff8082111561381857600080fd5b61382489838a01613796565b9096509450604088013591508082111561383d57600080fd5b5061384a88828901613796565b969995985093965092949392505050565b602081016035831061387d57634e487b7160e01b600052602160045260246000fd5b91905290565b634e487b7160e01b600052600160045260246000fd5b6000602082840312156138ab57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b600082198211156138db576138db6138b2565b500190565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561390857600080fd5b815161142b8161349f565b60006020828403121561392557600080fd5b815161142b81613444565b60008060006060848603121561394557600080fd5b8351925060208401519150604084015190509250925092565b8183823760009101908152919050565b6000816000190483118215151615613988576139886138b2565b500290565b6000826139aa57634e487b7160e01b600052601260045260246000fd5b500490565b6000828210156139c1576139c16138b2565b500390565b6000602082840312156139d857600080fd5b815160ff8116811461142b57600080fd5b80516001600160801b038116811461134c57600080fd5b60008060408385031215613a1357600080fd5b613a1c836139e9565b9150613a2a602084016139e9565b90509250929050565b60005b83811015613a4e578181015183820152602001613a36565b83811115610a525750506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613a97816017850160208801613a33565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613ac8816028840160208801613a33565b01602801949350505050565b6020815260008251806020840152613af3816040850160208701613a33565b601f01601f19169190910160400192915050565b634e487b7160e01b600052603160045260246000fd5b634e487b7160e01b600052604160045260246000fd5b600081613b4257613b426138b2565b50600019019056fedfbefbf47cfe66b701d8cfdbce1de81c821590819cb07e71cb01b6602fb0ee27821a7d13d576f16fb74d8c3368fdca30664a87854dbb22f5e83b1188dcf20d9da2646970667358221220584638974384110128c6702e1aee2406bd3d0cbcaf51b4d917faac9807c9baf564736f6c634300080f0033

Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.