ETH Price: $1,977.23 (-5.27%)
Gas: 0.45 Gwei

Contract

0x5D4cb367EAcDfeB9B42F86Cd6F98f5A7C43bf933
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Transfer242453752026-01-16 6:04:3549 days ago1768543475IN
0x5D4cb367...7C43bf933
0 ETH0.000114272.03181207
Transfer242368832026-01-15 1:39:3550 days ago1768441175IN
0x5D4cb367...7C43bf933
0 ETH0.000116472.070877
Approve242368052026-01-15 1:23:5950 days ago1768440239IN
0x5D4cb367...7C43bf933
0 ETH0.000026340.57110558
Transfer241012242025-12-27 3:16:3569 days ago1766805395IN
0x5D4cb367...7C43bf933
0 ETH0.000059942.02908645
Transfer240718842025-12-23 0:59:1173 days ago1766451551IN
0x5D4cb367...7C43bf933
0 ETH0.000069622.02739539
Approve240613892025-12-21 13:50:1175 days ago1766325011IN
0x5D4cb367...7C43bf933
0 ETH0.000094592.05076005

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LifeToken

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Votes} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";

/**
 * @title LifeToken - A Fully Decentralized ERC20 Token With Governance Capabilities
 * @author Jose Herrera
 * @notice A protocol token designed for maximum decentralization and DeFi composability with governance capabilities.
 * @dev This contract implements ERC20 with voting capabilities and gasless approvals
 * 
 * Key Features:
 * - Fixed supply: The entire maximum supply is minted at deployment with no possibility of further minting
 * - Voting capabilities: Supports delegation and vote tracking for decentralized governance
 * - Gasless approvals: EIP-2612 permit functionality allows users to approve spending without gas
 * - Fully decentralized: No owner, admin roles, or pausability mechanisms
 * - DeFi compatible: Designed to integrate seamlessly with DEXs, lending protocols, and other DeFi applications
 * 
 * Security Model:
 * - Immutable tokenomics: Total supply is permanently fixed at deployment
 * - No admin controls: Cannot be paused, frozen, or administratively controlled
 * - Unstoppable transfers: Follows the same security model as major DeFi tokens (UNI, AAVE, COMP)
 */
contract LifeToken is ERC20, ERC20Permit, ERC20Votes {
    
    // =============================
    // Constants
    // =============================
    
    /// @notice Maximum and total token supply (5 billion tokens with 18 decimals)
    /// @dev This supply is minted once at deployment and cannot be increased
    uint256 public constant MAX_SUPPLY = 5_000_000_000 * 1e18;

    // =============================
    // Constructor
    // =============================
    
    /**
     * @notice Initializes the LifeToken contract with fixed supply and governance capabilities
     * @dev Mints the entire maximum supply to the specified destination address
     * @param initialMintDestination_ The address that will receive the entire token supply
     * @param name_ The human-readable name of the token (e.g., "LifeToken")
     * @param symbol_ The token symbol (e.g., "LIFE")
     * 
     * Requirements:
     * - initialMintDestination_ cannot be the zero address (handled by _mint)
     * 
     * Effects:
     * - Sets up ERC20 basic functionality with name and symbol
     * - Initializes EIP-712 domain for permit functionality
     * - Mints entire MAX_SUPPLY to initialMintDestination_
     * - No admin roles or ownership is established
     */
    constructor(address initialMintDestination_, string memory name_, string memory symbol_)
        ERC20(name_, symbol_)
        ERC20Permit(name_)
    {
        _mint(initialMintDestination_, MAX_SUPPLY);
    }

    // =============================
    // Internal Overrides
    // =============================

    /**
     * @notice Internal function called after token transfers, mints, and burns
     * @dev Overrides both ERC20 and ERC20Votes to enable vote tracking on balance changes
     * @param from The address tokens are transferred from (address(0) for minting)
     * @param to The address tokens are transferred to (address(0) for burning)
     * @param amount The amount of tokens being transferred
     *
     * Note: This function automatically updates voting power when tokens are transferred,
     * enabling accurate governance participation tracking.
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Votes) {
        super._afterTokenTransfer(from, to, amount);
    }

    /**
     * @notice Internal function for minting tokens
     * @dev Overrides both ERC20 and ERC20Votes to enable vote tracking on minting
     */
    function _mint(address account, uint256 amount) internal override(ERC20, ERC20Votes) {
        super._mint(account, amount);
    }

    /**
     * @notice Internal function for burning tokens
     * @dev Overrides both ERC20 and ERC20Votes to enable vote tracking on burning
     */
    function _burn(address account, uint256 amount) internal override(ERC20, ERC20Votes) {
        super._burn(account, amount);
    }

    /**
     * @notice Returns the current nonce for permit and delegation signatures
     * @dev Inherited from ERC20Permit and ERC20Votes
     * @param owner The address to query the nonce for
     * @return The current nonce value for the specified address
     *
     * Note: This nonce is used for both EIP-2612 permit approvals and vote delegation signatures,
     * providing replay protection for gasless transactions.
     */
    function nonces(address owner) public view override(ERC20Permit) returns (uint256) {
        return super.nonces(owner);
    }
}

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

pragma solidity ^0.8.0;

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

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

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

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

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

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

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

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

        _revokeRole(role, account);
    }

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

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

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

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

// 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;
}

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

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

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

pragma solidity ^0.8.0;

import "../access/AccessControl.sol";
import "../token/ERC721/IERC721Receiver.sol";
import "../token/ERC1155/IERC1155Receiver.sol";

/**
 * @dev Contract module which acts as a timelocked controller. When set as the
 * owner of an `Ownable` smart contract, it enforces a timelock on all
 * `onlyOwner` maintenance operations. This gives time for users of the
 * controlled contract to exit before a potentially dangerous maintenance
 * operation is applied.
 *
 * By default, this contract is self administered, meaning administration tasks
 * have to go through the timelock process. The proposer (resp executor) role
 * is in charge of proposing (resp executing) operations. A common use case is
 * to position this {TimelockController} as the owner of a smart contract, with
 * a multisig or a DAO as the sole proposer.
 *
 * _Available since v3.3._
 */
contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver {
    bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
    bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
    bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
    bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
    uint256 internal constant _DONE_TIMESTAMP = uint256(1);

    mapping(bytes32 => uint256) private _timestamps;
    uint256 private _minDelay;

    /**
     * @dev Emitted when a call is scheduled as part of operation `id`.
     */
    event CallScheduled(
        bytes32 indexed id,
        uint256 indexed index,
        address target,
        uint256 value,
        bytes data,
        bytes32 predecessor,
        uint256 delay
    );

    /**
     * @dev Emitted when a call is performed as part of operation `id`.
     */
    event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);

    /**
     * @dev Emitted when new proposal is scheduled with non-zero salt.
     */
    event CallSalt(bytes32 indexed id, bytes32 salt);

    /**
     * @dev Emitted when operation `id` is cancelled.
     */
    event Cancelled(bytes32 indexed id);

    /**
     * @dev Emitted when the minimum delay for future operations is modified.
     */
    event MinDelayChange(uint256 oldDuration, uint256 newDuration);

    /**
     * @dev Initializes the contract with the following parameters:
     *
     * - `minDelay`: initial minimum delay for operations
     * - `proposers`: accounts to be granted proposer and canceller roles
     * - `executors`: accounts to be granted executor role
     * - `admin`: optional account to be granted admin role; disable with zero address
     *
     * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment
     * without being subject to delay, but this role should be subsequently renounced in favor of
     * administration through timelocked proposals. Previous versions of this contract would assign
     * this admin to the deployer automatically and should be renounced as well.
     */
    constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) {
        _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
        _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
        _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
        _setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);

        // self administration
        _setupRole(TIMELOCK_ADMIN_ROLE, address(this));

        // optional admin
        if (admin != address(0)) {
            _setupRole(TIMELOCK_ADMIN_ROLE, admin);
        }

        // register proposers and cancellers
        for (uint256 i = 0; i < proposers.length; ++i) {
            _setupRole(PROPOSER_ROLE, proposers[i]);
            _setupRole(CANCELLER_ROLE, proposers[i]);
        }

        // register executors
        for (uint256 i = 0; i < executors.length; ++i) {
            _setupRole(EXECUTOR_ROLE, executors[i]);
        }

        _minDelay = minDelay;
        emit MinDelayChange(0, minDelay);
    }

    /**
     * @dev Modifier to make a function callable only by a certain role. In
     * addition to checking the sender's role, `address(0)` 's role is also
     * considered. Granting a role to `address(0)` is equivalent to enabling
     * this role for everyone.
     */
    modifier onlyRoleOrOpenRole(bytes32 role) {
        if (!hasRole(role, address(0))) {
            _checkRole(role, _msgSender());
        }
        _;
    }

    /**
     * @dev Contract might receive/hold ETH as part of the maintenance process.
     */
    receive() external payable {}

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

    /**
     * @dev Returns whether an id correspond to a registered operation. This
     * includes both Pending, Ready and Done operations.
     */
    function isOperation(bytes32 id) public view virtual returns (bool) {
        return getTimestamp(id) > 0;
    }

    /**
     * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready".
     */
    function isOperationPending(bytes32 id) public view virtual returns (bool) {
        return getTimestamp(id) > _DONE_TIMESTAMP;
    }

    /**
     * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending".
     */
    function isOperationReady(bytes32 id) public view virtual returns (bool) {
        uint256 timestamp = getTimestamp(id);
        return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
    }

    /**
     * @dev Returns whether an operation is done or not.
     */
    function isOperationDone(bytes32 id) public view virtual returns (bool) {
        return getTimestamp(id) == _DONE_TIMESTAMP;
    }

    /**
     * @dev Returns the timestamp at which an operation becomes ready (0 for
     * unset operations, 1 for done operations).
     */
    function getTimestamp(bytes32 id) public view virtual returns (uint256) {
        return _timestamps[id];
    }

    /**
     * @dev Returns the minimum delay for an operation to become valid.
     *
     * This value can be changed by executing an operation that calls `updateDelay`.
     */
    function getMinDelay() public view virtual returns (uint256) {
        return _minDelay;
    }

    /**
     * @dev Returns the identifier of an operation containing a single
     * transaction.
     */
    function hashOperation(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) public pure virtual returns (bytes32) {
        return keccak256(abi.encode(target, value, data, predecessor, salt));
    }

    /**
     * @dev Returns the identifier of an operation containing a batch of
     * transactions.
     */
    function hashOperationBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt
    ) public pure virtual returns (bytes32) {
        return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
    }

    /**
     * @dev Schedule an operation containing a single transaction.
     *
     * Emits {CallSalt} if salt is nonzero, and {CallScheduled}.
     *
     * Requirements:
     *
     * - the caller must have the 'proposer' role.
     */
    function schedule(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt,
        uint256 delay
    ) public virtual onlyRole(PROPOSER_ROLE) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        _schedule(id, delay);
        emit CallScheduled(id, 0, target, value, data, predecessor, delay);
        if (salt != bytes32(0)) {
            emit CallSalt(id, salt);
        }
    }

    /**
     * @dev Schedule an operation containing a batch of transactions.
     *
     * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch.
     *
     * Requirements:
     *
     * - the caller must have the 'proposer' role.
     */
    function scheduleBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt,
        uint256 delay
    ) public virtual onlyRole(PROPOSER_ROLE) {
        require(targets.length == values.length, "TimelockController: length mismatch");
        require(targets.length == payloads.length, "TimelockController: length mismatch");

        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
        _schedule(id, delay);
        for (uint256 i = 0; i < targets.length; ++i) {
            emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
        }
        if (salt != bytes32(0)) {
            emit CallSalt(id, salt);
        }
    }

    /**
     * @dev Schedule an operation that is to become valid after a given delay.
     */
    function _schedule(bytes32 id, uint256 delay) private {
        require(!isOperation(id), "TimelockController: operation already scheduled");
        require(delay >= getMinDelay(), "TimelockController: insufficient delay");
        _timestamps[id] = block.timestamp + delay;
    }

    /**
     * @dev Cancel an operation.
     *
     * Requirements:
     *
     * - the caller must have the 'canceller' role.
     */
    function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
        require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
        delete _timestamps[id];

        emit Cancelled(id);
    }

    /**
     * @dev Execute an (ready) operation containing a single transaction.
     *
     * Emits a {CallExecuted} event.
     *
     * Requirements:
     *
     * - the caller must have the 'executor' role.
     */
    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
    // thus any modifications to the operation during reentrancy should be caught.
    // slither-disable-next-line reentrancy-eth
    function execute(
        address target,
        uint256 value,
        bytes calldata payload,
        bytes32 predecessor,
        bytes32 salt
    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
        bytes32 id = hashOperation(target, value, payload, predecessor, salt);

        _beforeCall(id, predecessor);
        _execute(target, value, payload);
        emit CallExecuted(id, 0, target, value, payload);
        _afterCall(id);
    }

    /**
     * @dev Execute an (ready) operation containing a batch of transactions.
     *
     * Emits one {CallExecuted} event per transaction in the batch.
     *
     * Requirements:
     *
     * - the caller must have the 'executor' role.
     */
    // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
    // thus any modifications to the operation during reentrancy should be caught.
    // slither-disable-next-line reentrancy-eth
    function executeBatch(
        address[] calldata targets,
        uint256[] calldata values,
        bytes[] calldata payloads,
        bytes32 predecessor,
        bytes32 salt
    ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
        require(targets.length == values.length, "TimelockController: length mismatch");
        require(targets.length == payloads.length, "TimelockController: length mismatch");

        bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);

        _beforeCall(id, predecessor);
        for (uint256 i = 0; i < targets.length; ++i) {
            address target = targets[i];
            uint256 value = values[i];
            bytes calldata payload = payloads[i];
            _execute(target, value, payload);
            emit CallExecuted(id, i, target, value, payload);
        }
        _afterCall(id);
    }

    /**
     * @dev Execute an operation's call.
     */
    function _execute(address target, uint256 value, bytes calldata data) internal virtual {
        (bool success, ) = target.call{value: value}(data);
        require(success, "TimelockController: underlying transaction reverted");
    }

    /**
     * @dev Checks before execution of an operation's calls.
     */
    function _beforeCall(bytes32 id, bytes32 predecessor) private view {
        require(isOperationReady(id), "TimelockController: operation is not ready");
        require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
    }

    /**
     * @dev Checks after execution of an operation's calls.
     */
    function _afterCall(bytes32 id) private {
        require(isOperationReady(id), "TimelockController: operation is not ready");
        _timestamps[id] = _DONE_TIMESTAMP;
    }

    /**
     * @dev Changes the minimum timelock duration for future operations.
     *
     * Emits a {MinDelayChange} event.
     *
     * Requirements:
     *
     * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
     * an operation where the timelock is the target and the data is the ABI-encoded call to this function.
     */
    function updateDelay(uint256 newDelay) external virtual {
        require(msg.sender == address(this), "TimelockController: caller must be timelock");
        emit MinDelayChange(_minDelay, newDelay);
        _minDelay = newDelay;
    }

    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }

    /**
     * @dev See {IERC1155Receiver-onERC1155Received}.
     */
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    /**
     * @dev See {IERC1155Receiver-onERC1155BatchReceived}.
     */
    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;

/**
 * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
 *
 * _Available since v4.5._
 */
interface IVotes {
    /**
     * @dev Emitted when an account changes their delegate.
     */
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);

    /**
     * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
     */
    event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);

    /**
     * @dev Returns the current amount of votes that `account` has.
     */
    function getVotes(address account) external view returns (uint256);

    /**
     * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     */
    function getPastVotes(address account, uint256 timepoint) external view returns (uint256);

    /**
     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     *
     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
     * Votes that have not been delegated are still part of total supply, even though they would not participate in a
     * vote.
     */
    function getPastTotalSupply(uint256 timepoint) external view returns (uint256);

    /**
     * @dev Returns the delegate that `account` has chosen.
     */
    function delegates(address account) external view returns (address);

    /**
     * @dev Delegates votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) external;

    /**
     * @dev Delegates votes from signer to `delegatee`.
     */
    function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
}

File 7 of 63 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

File 8 of 63 : IERC5805.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5805.sol)

pragma solidity ^0.8.0;

import "../governance/utils/IVotes.sol";
import "./IERC6372.sol";

interface IERC5805 is IERC6372, IVotes {}

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

pragma solidity ^0.8.0;

interface IERC6372 {
    /**
     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
     */
    function clock() external view returns (uint48);

    /**
     * @dev Description of the clock
     */
    // solhint-disable-next-line func-name-mixedcase
    function CLOCK_MODE() external view returns (string memory);
}

// 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());
    }
}

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

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

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @inheritdoc IERC20Permit
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

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

pragma solidity ^0.8.0;

import "./ERC20Permit.sol";
import "../../../interfaces/IERC5805.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";

/**
 * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
 * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
 *
 * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
 *
 * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
 * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
 * power can be queried through the public accessors {getVotes} and {getPastVotes}.
 *
 * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
 * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
 *
 * _Available since v4.2._
 */
abstract contract ERC20Votes is ERC20Permit, IERC5805 {
    struct Checkpoint {
        uint32 fromBlock;
        uint224 votes;
    }

    bytes32 private constant _DELEGATION_TYPEHASH =
        keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");

    mapping(address => address) private _delegates;
    mapping(address => Checkpoint[]) private _checkpoints;
    Checkpoint[] private _totalSupplyCheckpoints;

    /**
     * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting).
     */
    function clock() public view virtual override returns (uint48) {
        return SafeCast.toUint48(block.number);
    }

    /**
     * @dev Description of the clock
     */
    // solhint-disable-next-line func-name-mixedcase
    function CLOCK_MODE() public view virtual override returns (string memory) {
        // Check that the clock was not modified
        require(clock() == block.number, "ERC20Votes: broken clock mode");
        return "mode=blocknumber&from=default";
    }

    /**
     * @dev Get the `pos`-th checkpoint for `account`.
     */
    function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
        return _checkpoints[account][pos];
    }

    /**
     * @dev Get number of checkpoints for `account`.
     */
    function numCheckpoints(address account) public view virtual returns (uint32) {
        return SafeCast.toUint32(_checkpoints[account].length);
    }

    /**
     * @dev Get the address `account` is currently delegating to.
     */
    function delegates(address account) public view virtual override returns (address) {
        return _delegates[account];
    }

    /**
     * @dev Gets the current votes balance for `account`
     */
    function getVotes(address account) public view virtual override returns (uint256) {
        uint256 pos = _checkpoints[account].length;
        unchecked {
            return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
        }
    }

    /**
     * @dev Retrieve the number of votes for `account` at the end of `timepoint`.
     *
     * Requirements:
     *
     * - `timepoint` must be in the past
     */
    function getPastVotes(address account, uint256 timepoint) public view virtual override returns (uint256) {
        require(timepoint < clock(), "ERC20Votes: future lookup");
        return _checkpointsLookup(_checkpoints[account], timepoint);
    }

    /**
     * @dev Retrieve the `totalSupply` at the end of `timepoint`. Note, this value is the sum of all balances.
     * It is NOT the sum of all the delegated votes!
     *
     * Requirements:
     *
     * - `timepoint` must be in the past
     */
    function getPastTotalSupply(uint256 timepoint) public view virtual override returns (uint256) {
        require(timepoint < clock(), "ERC20Votes: future lookup");
        return _checkpointsLookup(_totalSupplyCheckpoints, timepoint);
    }

    /**
     * @dev Lookup a value in a list of (sorted) checkpoints.
     */
    function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 timepoint) private view returns (uint256) {
        // We run a binary search to look for the last (most recent) checkpoint taken before (or at) `timepoint`.
        //
        // Initially we check if the block is recent to narrow the search range.
        // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
        // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
        // - If the middle checkpoint is after `timepoint`, we look in [low, mid)
        // - If the middle checkpoint is before or equal to `timepoint`, we look in [mid+1, high)
        // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
        // out of bounds (in which case we're looking too far in the past and the result is 0).
        // Note that if the latest checkpoint available is exactly for `timepoint`, we end up with an index that is
        // past the end of the array, so we technically don't find a checkpoint after `timepoint`, but it works out
        // the same.
        uint256 length = ckpts.length;

        uint256 low = 0;
        uint256 high = length;

        if (length > 5) {
            uint256 mid = length - Math.sqrt(length);
            if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);
            if (_unsafeAccess(ckpts, mid).fromBlock > timepoint) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        unchecked {
            return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes;
        }
    }

    /**
     * @dev Delegate votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) public virtual override {
        _delegate(_msgSender(), delegatee);
    }

    /**
     * @dev Delegates votes from signer to `delegatee`
     */
    function delegateBySig(
        address delegatee,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= expiry, "ERC20Votes: signature expired");
        address signer = ECDSA.recover(
            _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
            v,
            r,
            s
        );
        require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
        _delegate(signer, delegatee);
    }

    /**
     * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
     */
    function _maxSupply() internal view virtual returns (uint224) {
        return type(uint224).max;
    }

    /**
     * @dev Snapshots the totalSupply after it has been increased.
     */
    function _mint(address account, uint256 amount) internal virtual override {
        super._mint(account, amount);
        require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");

        _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
    }

    /**
     * @dev Snapshots the totalSupply after it has been decreased.
     */
    function _burn(address account, uint256 amount) internal virtual override {
        super._burn(account, amount);

        _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
    }

    /**
     * @dev Move voting power when tokens are transferred.
     *
     * Emits a {IVotes-DelegateVotesChanged} event.
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual override {
        super._afterTokenTransfer(from, to, amount);

        _moveVotingPower(delegates(from), delegates(to), amount);
    }

    /**
     * @dev Change delegation for `delegator` to `delegatee`.
     *
     * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
     */
    function _delegate(address delegator, address delegatee) internal virtual {
        address currentDelegate = delegates(delegator);
        uint256 delegatorBalance = balanceOf(delegator);
        _delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);

        _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
    }

    function _moveVotingPower(address src, address dst, uint256 amount) private {
        if (src != dst && amount > 0) {
            if (src != address(0)) {
                (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
                emit DelegateVotesChanged(src, oldWeight, newWeight);
            }

            if (dst != address(0)) {
                (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
                emit DelegateVotesChanged(dst, oldWeight, newWeight);
            }
        }
    }

    function _writeCheckpoint(
        Checkpoint[] storage ckpts,
        function(uint256, uint256) view returns (uint256) op,
        uint256 delta
    ) private returns (uint256 oldWeight, uint256 newWeight) {
        uint256 pos = ckpts.length;

        unchecked {
            Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1);

            oldWeight = oldCkpt.votes;
            newWeight = op(oldWeight, delta);

            if (pos > 0 && oldCkpt.fromBlock == clock()) {
                _unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight);
            } else {
                ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(clock()), votes: SafeCast.toUint224(newWeight)}));
            }
        }
    }

    function _add(uint256 a, uint256 b) private pure returns (uint256) {
        return a + b;
    }

    function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
     */
    function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) {
        assembly {
            mstore(0, ckpts.slot)
            result.slot := add(keccak256(0, 0x20), pos)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

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

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

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

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

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

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

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

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

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

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @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.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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 23 of 63 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @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 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

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

pragma solidity ^0.8.8;

import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _name.toStringWithFallback(_nameFallback),
            _version.toStringWithFallback(_versionFallback),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }
}

// 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;
    }
}

// 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);
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

pragma solidity ^0.8.8;

import "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(_FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

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

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/// @title AdminControl - Core contract for system administration and configuration
/// @notice Manages system roles, fees, KYC verification, and reward parameters
/// @dev Implements role-based access control and emergency pause functionality
contract AdminControl is AccessControl, Pausable {
    // Rename these events to avoid conflicts with AccessControl contract events
    event AdminRoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
    event AdminRoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
    using EnumerableSet for EnumerableSet.AddressSet;
    
    // ========== Role Definitions ==========
    bytes32 public constant PROTOCOL_PARAM_MANAGER_ROLE = keccak256("PROTOCOL_PARAM_MANAGER_ROLE");
    bytes32 public constant KYC_ROLE = keccak256("KYC_ROLE");
    bytes32 public constant REWARD_MANAGER_ROLE = keccak256("REWARD_MANAGER_ROLE");
    bytes32 public constant NFT_PROPERTY_MANAGER_ROLE = keccak256("NFT_PROPERTY_MANAGER_ROLE");

    // ========== Constants ==========
    uint256 public constant BASIS_POINTS = 10000; // Base for percentage calculations (100% = 10000, 1% = 100)
    
    // ========== Fee Structure ==========
    struct FeeSettings {
        uint256 baseFee;        // Base transaction fee rate (basis points: 100 = 1%)
        uint256 maxFee;         // Maximum allowed fee rate (basis points)
        address feeCollector;   // Fee collection address
    }

    // ========== Reward Parameters Structure ==========
    struct RewardParameters {
        uint256 baseRate;              // Base reward rate (basis points)
        uint256 communityMultiplier;   // Community bonus multiplier
        uint256 maxLeaseBonus;         // Maximum lease duration bonus
        address rewardsVault;          // Rewards vault address
    }

    // ========== State Variables ==========
    FeeSettings public feeConfig;
    RewardParameters public rewardParams;
    
    EnumerableSet.AddressSet private _kycVerified;
    mapping(address => uint256) public communityScores;
    mapping(uint256 => bool) public functionPaused;

    // ========== Event Definitions ==========
    event FeeConfigUpdated(uint256 oldBaseFee, uint256 newBaseFee, uint256 oldMaxFee, uint256 newMaxFee, address indexed admin);
    event RewardParametersUpdated(uint256 oldBaseRate, uint256 newBaseRate, uint256 oldMultiplier, uint256 newMultiplier, address indexed admin);
    event KYCStatusUpdated(address indexed account, bool approved);
    event CommunityScoreUpdated(address indexed user, uint256 oldScore, uint256 newScore);


    function _initializeRoles(address admin) internal {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(PROTOCOL_PARAM_MANAGER_ROLE, admin);
        _grantRole(KYC_ROLE, admin);
        _grantRole(REWARD_MANAGER_ROLE, admin);
        _grantRole(NFT_PROPERTY_MANAGER_ROLE, admin);
    }

    constructor(
        address initialAdmin,
        address feeCollector,
        address rewardsVault
    ) {
        require(feeCollector != address(0), "Invalid fee collector address");
        require(rewardsVault != address(0), "Invalid rewards vault address");
        require(initialAdmin != address(0), "Invalid admin address");
        
        // Initialize role assignments
        _initializeRoles(initialAdmin);

        // Initialize fee configuration
        feeConfig = FeeSettings({
            baseFee: 200,       // 2%
            maxFee: 1000,       // 10%
            feeCollector: feeCollector
        });

        // Initialize reward parameters
        rewardParams = RewardParameters({
            baseRate: 1000,     // 10% base reward
            communityMultiplier: 2000, // 20% max community bonus
            maxLeaseBonus: 300, // 3% max lease bonus
            rewardsVault: rewardsVault
        });
    }

    // ========== Fee Management ==========
    /// @notice Updates the fee configuration for the system
    /// @dev Only callable by accounts with PROTOCOL_PARAM_MANAGER_ROLE (governance-managed)
    /// @param newBaseFee New base fee rate in basis points (100 = 1%)
    /// @param newCollector New address to collect fees
    function updateFeeConfig(
        uint256 newBaseFee, 
        address newCollector
    ) external onlyRole(PROTOCOL_PARAM_MANAGER_ROLE) {
        require(newCollector != address(0), "Invalid fee collector address");
        require(newBaseFee <= feeConfig.maxFee, "Exceeds max fee");
        
        uint256 oldBase = feeConfig.baseFee;
        uint256 oldMax = feeConfig.maxFee;
        
        feeConfig.baseFee = newBaseFee;
        feeConfig.feeCollector = newCollector;
        
        emit FeeConfigUpdated(oldBase, newBaseFee, oldMax, feeConfig.maxFee, msg.sender);
    }

    // ========== KYC Management ==========
    /// @notice Batch approves or revokes KYC verification for multiple accounts
    /// @dev Only callable by accounts with KYC_ROLE (governance-managed)
    /// @param accounts Array of addresses to update KYC status
    /// @param approved True to approve, false to revoke KYC status
    function batchApproveKYC(
        address[] calldata accounts, 
        bool approved
    ) external onlyRole(KYC_ROLE) {
        uint256 length = accounts.length;
        for(uint256 i = 0; i < length;) {
            address account = accounts[i];
            if (approved) {
                _kycVerified.add(account);
            } else {
                _kycVerified.remove(account);
            }
            emit KYCStatusUpdated(account, approved);
            unchecked { ++i; }
        }
    }

    // ========== Reward Management ==========
    /// @notice Configures the reward parameters for the system
    /// @dev Only callable by accounts with REWARD_MANAGER role
    /// @param newBaseRate New base reward rate in basis points
    /// @param newMultiplier New community multiplier for rewards
    /// @param newLeaseBonus New maximum lease bonus percentage
    function configureRewards(
        uint256 newBaseRate,
        uint256 newMultiplier,
        uint256 newLeaseBonus
    ) external onlyRole(REWARD_MANAGER_ROLE) {
        require(rewardParams.rewardsVault != address(0), "Rewards vault not set");
        require(newBaseRate <= 2000, "Base rate >20%");
        require(newMultiplier <= 2000, "Multiplier >20%");
        require(newLeaseBonus <= 500, "Lease bonus >5%");

        uint256 oldRate = rewardParams.baseRate;
        uint256 oldMulti = rewardParams.communityMultiplier;
        
        rewardParams.baseRate = newBaseRate;
        rewardParams.communityMultiplier = newMultiplier;
        rewardParams.maxLeaseBonus = newLeaseBonus;
        
        emit RewardParametersUpdated(oldRate, newBaseRate, oldMulti, newMultiplier, msg.sender);
    }

    // ========== Emergency Controls ==========
    /// @notice Pauses or unpauses a specific function in emergency situations
    /// @dev Only callable by accounts with DEFAULT_ADMIN_ROLE
    /// @param functionId ID of the function to pause/unpause
    /// @param paused True to pause, false to unpause
    function emergencyPauseFunction(
        uint256 functionId, 
        bool paused
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        functionPaused[functionId] = paused;
    }

    /// @notice Pauses all contract operations in emergency situations
    /// @dev Only callable by accounts with DEFAULT_ADMIN_ROLE
    function globalPause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
    }

    /// @notice Resumes all contract operations after emergency pause
    /// @dev Only callable by accounts with DEFAULT_ADMIN_ROLE
    function globalUnpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
    }

    // ========== Community Score Management ==========
    /// @notice Updates a user's community score
    /// @dev Only callable by accounts with PROTOCOL_PARAM_MANAGER_ROLE (governance-managed)
    /// @param user Address of the user to update score
    /// @param scoreDelta Amount to change the score by
    /// @param isAddition True to add score, false to subtract
    function updateCommunityScore(
        address user, 
        uint256 scoreDelta, 
        bool isAddition
    ) external onlyRole(PROTOCOL_PARAM_MANAGER_ROLE) {
        uint256 oldScore = communityScores[user];
        uint256 newScore;
        
        if(isAddition) {
            newScore = oldScore + scoreDelta;
        } else {
            newScore = oldScore > scoreDelta ? oldScore - scoreDelta : 0;
        }
        
        communityScores[user] = newScore;
        emit CommunityScoreUpdated(user, oldScore, newScore);
    }

    // ========== View Functions ==========
    /// @notice Gets the current base fee rate
    /// @return Current base fee rate in basis points
    function getCurrentFee() external view returns (uint256) {
        return feeConfig.baseFee;
    }

    /// @notice Checks if an account is KYC verified
    /// @param account Address to check KYC status
    /// @return True if account is KYC verified
    function isKYCVerified(address account) external view returns (bool) {
        return _kycVerified.contains(account);
    }

    /// @notice Calculates total rewards for a user including all bonuses
    /// @dev Includes base rate, lease bonus and community bonus
    /// @param user Address of the user to calculate rewards for
    /// @param baseAmount Base amount to calculate rewards on
    /// @return Total reward amount including all bonuses
    function calculateRewards(
        address user, 
        uint256 baseAmount
    ) external view returns (uint256) {
        uint256 leaseBonus = _getLeaseBonus(user);
        uint256 communityBonus = _getCommunityBonus(user);
        return baseAmount * (rewardParams.baseRate + leaseBonus + communityBonus) / BASIS_POINTS;
    }

    // ========== Internal Functions ==========
    /// @notice Gets lease bonus for a user
    /// @dev Implementation roadmap: integrate with lease duration tracking
    /// @return Lease bonus in basis points
    function _getLeaseBonus(address /*user*/) internal view returns (uint256) {
        // TODO: Implement actual lease duration calculation
        return rewardParams.maxLeaseBonus;
    }

    /// @notice Gets community bonus for a user based on their score
    /// @param user Address of the user
    /// @return Community bonus in basis points
    function _getCommunityBonus(address user) internal view returns (uint256) {
        uint256 score = communityScores[user];
        return score > rewardParams.communityMultiplier ? 
            rewardParams.communityMultiplier : score;
    }

    /// @notice Modifier to check if a function is active
    /// @param functionId ID of the function to check
    modifier whenFunctionActive(uint256 functionId) {
        require(!functionPaused[functionId], "Function paused");
        _;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/governance/TimelockController.sol";

/// @title PropertyMarketTimelock
/// @notice Timelock controller for PropertyMarket privileged operations
/// @dev Implements 48-hour delay for sensitive operations as recommended for MA2-02 mitigation
contract PropertyMarketTimelock is TimelockController {
    
    /// @notice Minimum delay for operations (48 hours)
    uint256 public constant MIN_DELAY = 48 hours;
    
    /// @notice Event emitted when a sensitive operation is scheduled
    event SensitiveOperationScheduled(
        bytes32 indexed id,
        uint256 indexed delay,
        address indexed target,
        bytes4 selector,
        string operation
    );
    
    /// @notice Event emitted when a sensitive operation is executed
    event SensitiveOperationExecuted(
        bytes32 indexed id,
        address indexed target,
        bytes4 selector,
        string operation
    );
    
    /// @notice Constructor for PropertyMarketTimelock
    /// @param proposers Array of addresses that can propose operations
    /// @param executors Array of addresses that can execute operations (empty for open execution)
    /// @param admin Address that can grant/revoke roles (should be multisig)
    constructor(
        address[] memory proposers,
        address[] memory executors,
        address admin
    ) TimelockController(MIN_DELAY, proposers, executors, admin) {
        // Additional setup if needed
    }
    
    /// @notice Schedule a sensitive PropertyMarket operation
    /// @param target The target contract address
    /// @param value The ETH value to send
    /// @param data The call data
    /// @param predecessor The predecessor operation hash
    /// @param salt The salt for unique operation ID
    /// @param operationName Human-readable operation name for transparency
    function scheduleSensitiveOperation(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt,
        string calldata operationName
    ) external onlyRole(PROPOSER_ROLE) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        
        // Extract function selector for logging
        bytes4 selector = bytes4(data[:4]);
        
        // Schedule with minimum delay
        schedule(target, value, data, predecessor, salt, MIN_DELAY);
        
        emit SensitiveOperationScheduled(id, MIN_DELAY, target, selector, operationName);
    }
    
    /// @notice Execute a sensitive PropertyMarket operation
    /// @param target The target contract address
    /// @param value The ETH value to send
    /// @param data The call data
    /// @param predecessor The predecessor operation hash
    /// @param salt The salt for unique operation ID
    /// @param operationName Human-readable operation name for transparency
    function executeSensitiveOperation(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt,
        string calldata operationName
    ) external onlyRole(EXECUTOR_ROLE) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        
        // Extract function selector for logging
        bytes4 selector = bytes4(data[:4]);
        
        // Execute the operation
        execute(target, value, data, predecessor, salt);
        
        emit SensitiveOperationExecuted(id, target, selector, operationName);
    }
    
    /// @notice Check if an operation is ready for execution
    /// @param target The target contract address
    /// @param value The ETH value to send
    /// @param data The call data
    /// @param predecessor The predecessor operation hash
    /// @param salt The salt for unique operation ID
    /// @return bool True if ready for execution
    function checkOperationReady(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) external view returns (bool) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        return isOperationReady(id);
    }
    
    /// @notice Get operation details for transparency
    /// @param target The target contract address
    /// @param value The ETH value to send
    /// @param data The call data
    /// @param predecessor The predecessor operation hash
    /// @param salt The salt for unique operation ID
    /// @return timestamp When the operation can be executed
    function getOperationTimestamp(
        address target,
        uint256 value,
        bytes calldata data,
        bytes32 predecessor,
        bytes32 salt
    ) external view returns (uint256 timestamp) {
        bytes32 id = hashOperation(target, value, data, predecessor, salt);
        return getTimestamp(id);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

interface IAdminControl {
    function hasRole(bytes32 role, address account) external view returns (bool);
    function NFT_PROPERTY_MANAGER_ROLE() external view returns (bytes32);
    function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {IAdminControl} from "./IAdminControl.sol";
interface IManageLifePropertyNFT {
    function mintPropertyNFT(address to, bool deedHeldAtManageLife) external returns (uint256);
    function setDeedHeldAtManageLife(uint256 tokenId, bool deedHeldAtManageLife) external;
    function propertyControllerContract() external view returns (address);
    function adminController() external view returns (IAdminControl);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IAdminControl} from "./IAdminControl.sol";
import {IManageLifePropertyNFT} from "./IManageLifePropertyNFT.sol";

interface IManageLifePropertyNFTController {
    function adminController() external view returns (IAdminControl);
    function manageLifePropertiesNftContract() external view returns (IManageLifePropertyNFT);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ErrorCodes} from "./ErrorCodes.sol";

/**
 * @title BiddingLibrary
 * @notice Library for managing property bidding logic
 * @dev Extracted from PropertyMarket to reduce contract size
 */
library BiddingLibrary {
    using SafeERC20 for IERC20;

    // Optimized Bid structure with packed fields
    struct Bid {
        uint256 tokenId;
        address bidder;
        uint256 amount;
        address paymentToken;
        uint64 bidTimestamp;  // Packed: sufficient until year 2554
        bool isActive;
    }

    event BidPlaced(
        uint256 indexed tokenId,
        address indexed bidder,
        uint256 amount,
        address paymentToken
    );

    event BidCancelled(
        uint256 indexed tokenId,
        address indexed bidder,
        uint256 amount
    );

    /**
     * @notice Get the highest active bid for a token
     * @param bids Array of bids for the token
     * @return highest The highest bid amount
     */
    function getHighestActiveBid(Bid[] storage bids) internal view returns (uint256 highest) {
        uint256 length = bids.length;
        for (uint256 i = 0; i < length; i++) {
            if (bids[i].isActive && bids[i].amount > highest) {
                highest = bids[i].amount;
            }
        }
    }

    /**
     * @notice Cancel all active bids for a token
     * @param bids Array of bids for the token
     * @param bidIndexByBidder Mapping of bidder to bid index
     * @param tokenId The token ID
     */
    function cancelAllBids(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        mapping(address => mapping(address => uint256)) storage refundableBalances,
        mapping(uint256 => uint256) storage activeBidsCount
    ) internal {
        uint256 length = bids.length;
        for (uint256 i = 0; i < length; i++) {
            if (bids[i].isActive) {
                address bidder = bids[i].bidder;
                uint256 refundAmount = bids[i].amount;
                address paymentToken = bids[i].paymentToken;

                bids[i].isActive = false;
                bidIndexByBidder[bidder][tokenId] = 0;
                if (activeBidsCount[tokenId] > 0) {
                    activeBidsCount[tokenId] -= 1;
                }
                refundableBalances[bidder][paymentToken] += refundAmount;
                emit BidCancelled(tokenId, bidder, refundAmount);
            }
        }
    }

    /**
     * @notice Cancel all bids except for a specific bidder
     * @param bids Array of bids for the token
     * @param bidIndexByBidder Mapping of bidder to bid index
     * @param tokenId The token ID
     * @param excludeBidder The bidder to exclude from cancellation
     */
    function cancelOtherBids(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        address excludeBidder,
        mapping(address => mapping(address => uint256)) storage refundableBalances,
        mapping(uint256 => uint256) storage activeBidsCount
    ) internal {
        uint256 length = bids.length;
        for (uint256 i = 0; i < length; i++) {
            if (bids[i].isActive && bids[i].bidder != excludeBidder) {
                address bidder = bids[i].bidder;
                uint256 refundAmount = bids[i].amount;
                address paymentToken = bids[i].paymentToken;

                bids[i].isActive = false;
                bidIndexByBidder[bidder][tokenId] = 0;
                if (activeBidsCount[tokenId] > 0) {
                    activeBidsCount[tokenId] -= 1;
                }
                refundableBalances[bidder][paymentToken] += refundAmount;
                emit BidCancelled(tokenId, bidder, refundAmount);
            }
        }
    }

    /**
     * @notice Validate a new bid amount
     * @param bids Array of bids for the token
     * @param bidAmount The new bid amount
     * @param listingPrice The listing price
     * @return isValid Whether the bid is valid
     */
    function validateBidAmount(
        Bid[] storage bids,
        uint256 bidAmount,
        uint256 listingPrice
    ) internal view returns (bool isValid) {
        require(bidAmount >= listingPrice, ErrorCodes.E206);
        
        uint256 highestBid = getHighestActiveBid(bids);
        if (highestBid > 0) {
            require(bidAmount >= highestBid, ErrorCodes.E205);
        }
        
        return true;
    }

    /**
     * @notice Process a bid placement or update
     * @param bids Array of bids for the token
     * @param bidIndexByBidder Mapping of bidder to bid index
     * @param tokenId The token ID
     * @param bidder The bidder address
     * @param bidAmount The bid amount
     * @param paymentToken The payment token address
     * @param listingPrice The listing price
     */
    function placeBid(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        address bidder,
        uint256 bidAmount,
        address paymentToken,
        uint256 listingPrice
    ) internal {
        // Validate bid amount
        validateBidAmount(bids, bidAmount, listingPrice);

        uint256 existingBidIndex = bidIndexByBidder[bidder][tokenId];
        
        if (existingBidIndex > 0) {
            // Update existing bid
            Bid storage existingBid = bids[existingBidIndex - 1];
            require(existingBid.isActive, ErrorCodes.E202);
            require(existingBid.paymentToken == paymentToken, ErrorCodes.E302);
            require(bidAmount > existingBid.amount, ErrorCodes.E205);

            uint256 additionalAmount = bidAmount - existingBid.amount;
            IERC20(paymentToken).safeTransferFrom(bidder, address(this), additionalAmount);

            existingBid.amount = bidAmount;
            existingBid.bidTimestamp = uint64(block.timestamp);
        } else {
            // Create new bid
            IERC20(paymentToken).safeTransferFrom(bidder, address(this), bidAmount);

            Bid memory newBid = Bid({
                tokenId: tokenId,
                bidder: bidder,
                amount: bidAmount,
                paymentToken: paymentToken,
                bidTimestamp: uint64(block.timestamp),
                isActive: true
            });

            bids.push(newBid);
            bidIndexByBidder[bidder][tokenId] = bids.length;
        }

        emit BidPlaced(tokenId, bidder, bidAmount, paymentToken);
    }

    /**
     * @notice Cancel a specific bid
     * @param bids Array of bids for the token
     * @param bidIndexByBidder Mapping of bidder to bid index
     * @param tokenId The token ID
     * @param bidder The bidder address
     */
    function cancelBid(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        address bidder,
        mapping(address => mapping(address => uint256)) storage refundableBalances,
        mapping(uint256 => uint256) storage activeBidsCount
    ) internal {
        uint256 bidIndex = bidIndexByBidder[bidder][tokenId];
        require(bidIndex > 0, ErrorCodes.E201);

        Bid storage bid = bids[bidIndex - 1];
        require(bid.isActive, ErrorCodes.E202);
        require(bid.bidder == bidder, ErrorCodes.E203);

        uint256 refundAmount = bid.amount;
        address paymentToken = bid.paymentToken;

        bid.isActive = false;
        bidIndexByBidder[bidder][tokenId] = 0;

        if (activeBidsCount[tokenId] > 0) {
            activeBidsCount[tokenId] -= 1;
        }
        refundableBalances[bidder][paymentToken] += refundAmount;
        emit BidCancelled(tokenId, bidder, refundAmount);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "./ErrorCodes.sol";

/// @title BidManagement - Library for bid-related operations
/// @dev Extracts bid management logic to reduce main contract size
library BidManagement {
    
    struct Bid {
        uint256 tokenId;
        address bidder;
        uint256 amount;
        address paymentToken;
        uint256 bidTimestamp;
        bool isActive;
    }

    /// @notice Find the highest active bid for a token
    /// @param bids Array of bids for the token
    /// @return highest The highest bid amount
    function getHighestActiveBid(Bid[] storage bids) external view returns (uint256 highest) {
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].amount > highest) {
                highest = bids[i].amount;
            }
        }
    }

    /// @notice Cancel all bids for a token
    /// @param bids Array of bids for the token
    /// @param bidIndexByBidder Mapping to track bidder indices
    /// @param tokenId The token ID
    function cancelAllBids(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId
    ) external {
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive) {
                bids[i].isActive = false;
                bidIndexByBidder[bids[i].bidder][tokenId] = 0;
            }
        }
    }

    /// @notice Cancel all bids except for a specific bidder
    /// @param bids Array of bids for the token
    /// @param bidIndexByBidder Mapping to track bidder indices
    /// @param tokenId The token ID
    /// @param excludeBidder Bidder to exclude from cancellation
    function cancelOtherBids(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        address excludeBidder
    ) external {
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].bidder != excludeBidder) {
                bids[i].isActive = false;
                bidIndexByBidder[bids[i].bidder][tokenId] = 0;
            }
        }
    }

    /// @notice Validate bid amount against listing price and existing bids
    /// @param bidAmount The proposed bid amount
    /// @param listingPrice The listing price
    /// @param highestBid The current highest bid
    /// @return valid Whether the bid amount is valid
    function validateBidAmount(
        uint256 bidAmount,
        uint256 listingPrice,
        uint256 highestBid
    ) external pure returns (bool valid) {
        // Must meet listing price
        if (bidAmount < listingPrice) return false;
        
        // Must meet or exceed highest bid if exists
        if (highestBid > 0 && bidAmount < highestBid) return false;
        
        return true;
    }

    /// @notice Calculate minimum increment for a bid
    /// @param currentPrice The current highest price
    /// @return increment The minimum increment required
    function calculateMinimumIncrement(uint256 currentPrice) external pure returns (uint256 increment) {
        if (currentPrice < 1 ether) {
            return currentPrice * 5 / 100; // 5% for small amounts
        } else if (currentPrice < 10 ether) {
            return currentPrice * 3 / 100; // 3% for medium amounts
        } else {
            return currentPrice * 1 / 100; // 1% for large amounts
        }
    }

    /// @notice Clean up inactive bids in batches
    /// @param bids Array of bids for the token
    /// @param bidIndexByBidder Mapping to track bidder indices
    /// @param tokenId The token ID
    /// @param batchSize Maximum number of bids to process
    /// @return removedCount Number of inactive bids removed
    function cleanupInactiveBids(
        Bid[] storage bids,
        mapping(address => mapping(uint256 => uint256)) storage bidIndexByBidder,
        uint256 tokenId,
        uint256 batchSize
    ) external returns (uint256 removedCount) {
        uint256 originalLength = bids.length;
        if (originalLength == 0) return 0;

        uint256 processLimit = originalLength > batchSize ? batchSize : originalLength;

        for (uint256 i = 0; i < processLimit; i++) {
            if (!bids[i].isActive) {
                bidIndexByBidder[bids[i].bidder][tokenId] = 0;
                removedCount++;
            }
        }

        // Only rebuild if we processed all bids and there were removals
        if (processLimit == originalLength && removedCount > 0) {
            _rebuildBidsArray(bids);
        }
    }

    /// @notice Rebuild bids array by removing inactive entries
    /// @param bids Array of bids to rebuild
    function _rebuildBidsArray(Bid[] storage bids) internal {
        uint256 activeCount = 0;
        uint256 length = bids.length;
        
        // Count active bids
        for (uint256 i = 0; i < length; i++) {
            if (bids[i].isActive) {
                activeCount++;
            }
        }

        // Create new array with only active bids
        Bid[] memory activeBids = new Bid[](activeCount);
        uint256 index = 0;
        
        for (uint256 i = 0; i < length; i++) {
            if (bids[i].isActive) {
                activeBids[index] = bids[i];
                index++;
            }
        }

        // Clear the storage array and repopulate
        while (bids.length > 0) {
            bids.pop();
        }
        
        for (uint256 i = 0; i < activeCount; i++) {
            bids.push(activeBids[i]);
        }
    }

    /// @notice Find active ETH bid for payment completion
    /// @param bids Array of bids for the token
    /// @return bidIndex Index of the ETH bid (0 if not found)
    /// @return bidder Address of the bidder
    /// @return bidAmount Amount of the bid
    function findActiveETHBid(Bid[] storage bids) 
        external 
        view 
        returns (uint256 bidIndex, address bidder, uint256 bidAmount) 
    {
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].paymentToken == address(0)) {
                return (i, bids[i].bidder, bids[i].amount);
            }
        }
        return (0, address(0), 0);
    }
}

File 45 of 63 : ErrorCodes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

/// @title ErrorCodes - Compact error codes for gas optimization
/// @dev Short error codes to reduce contract size while maintaining clarity
library ErrorCodes {
    // ========== General Errors ==========
    string constant E001 = "E001"; // Invalid address
    string constant E002 = "E002"; // Unauthorized access
    string constant E003 = "E003"; // Invalid amount
    string constant E004 = "E004"; // Transfer failed
    string constant E005 = "E005"; // Payment failed
    
    // ========== Listing Errors ==========
    string constant E101 = "E101"; // Not available
    string constant E102 = "E102"; // Already listed
    string constant E103 = "E103"; // Not listed
    string constant E104 = "E104"; // Invalid price
    string constant E105 = "E105"; // Not owner
    
    // ========== Bidding Errors ==========
    string constant E201 = "E201"; // No active bid
    string constant E202 = "E202"; // Bid not active
    string constant E203 = "E203"; // Not your bid
    string constant E204 = "E204"; // Bid too low
    string constant E205 = "E205"; // Bid increment low
    string constant E206 = "E206"; // Must meet price
    string constant E207 = "E207"; // ETH amount mismatch
    string constant E208 = "E208"; // Insufficient allowance
    
    // ========== Payment Errors ==========
    string constant E301 = "E301"; // Token not allowed
    string constant E302 = "E302"; // Payment token mismatch
    string constant E303 = "E303"; // ETH refund failed
    string constant E304 = "E304"; // Excess refund failed
    
    // ========== Access Control Errors ==========
    string constant E401 = "E401"; // Not admin
    string constant E402 = "E402"; // Not operator
    string constant E403 = "E403"; // KYC required
    string constant E404 = "E404"; // Paused
    
    // ========== Validation Errors ==========
    string constant E501 = "E501"; // Invalid input
    string constant E502 = "E502"; // Out of range
    string constant E503 = "E503"; // Already exists
    string constant E504 = "E504"; // Not found
    
    // ========== Purchase/Confirmation Errors ==========
    string constant E601 = "E601"; // Insufficient ETH sent
    string constant E602 = "E602"; // No pending purchase
    string constant E603 = "E603"; // Purchase not active
    string constant E604 = "E604"; // Not the seller
    string constant E605 = "E605"; // Confirmation period expired
    string constant E606 = "E606"; // Confirmation period not expired
    string constant E607 = "E607"; // Confirmation period too long
    string constant E608 = "E608"; // No additional payment required
    string constant E609 = "E609"; // Payment to seller failed
    string constant E610 = "E610"; // Payment to fee collector failed

    // ========== Bid Management Errors ==========
    string constant E701 = "E701"; // No active ETH bid found
    string constant E702 = "E702"; // Not in pending payment status
    string constant E703 = "E703"; // Payment deadline not expired
    string constant E704 = "E704"; // No pending refund
    string constant E705 = "E705"; // Refund withdrawal failed
    string constant E706 = "E706"; // Must send exact additional amount
    string constant E707 = "E707"; // Token transfer failed

    // ========== Timelock/MultiSig Errors ==========
    string constant E801 = "E801"; // Timelock required
    string constant E802 = "E802"; // MultiSig required
    string constant E803 = "E803"; // Invalid timelock
    string constant E804 = "E804"; // Invalid multisig

    // ========== Transfer Errors ==========
    string constant E901 = "E901"; // Token transfer failed
    string constant E902 = "E902"; // ETH refund failed
    string constant E903 = "E903"; // Payment to seller failed
    string constant E904 = "E904"; // Fee payment failed
    string constant E905 = "E905"; // ETH transfer failed
    string constant E906 = "E906"; // Payment deadline expired
    string constant E907 = "E907"; // No active bid found
    string constant E908 = "E908"; // Bid is not active
    string constant E909 = "E909"; // Not your bid
    string constant E910 = "E910"; // Not an ETH bid
    string constant E911 = "E911"; // Cannot change payment token with active bids
    string constant E912 = "E912"; // Unauthorized: admin role required
    string constant E913 = "E913"; // Invalid recipient address
    string constant E914 = "E914"; // Insufficient contract balance
    string constant E915 = "E915"; // Invalid token address
    string constant E916 = "E916"; // Insufficient token balance
}

File 46 of 63 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

/// @title Errors - Centralized error message library
/// @notice Provides standardized error messages across all contracts
/// @dev Library to ensure consistent error handling and reduce code duplication
library Errors {
    
    // ========== General Errors ==========
    string constant ZERO_ADDRESS = "Zero address not allowed";
    string constant INVALID_ADDRESS = "Invalid address";
    string constant INVALID_AMOUNT = "Invalid amount";
    string constant INSUFFICIENT_BALANCE = "Insufficient balance";
    string constant UNAUTHORIZED_ACCESS = "Unauthorized access";
    string constant OPERATION_FAILED = "Operation failed";
    
    // ========== Access Control Errors ==========
    string constant NOT_OWNER = "Not the owner";
    string constant NOT_OPERATOR = "Operator required";
    string constant NOT_REBASER = "Caller is not the rebaser";
    string constant NOT_DISTRIBUTOR = "Caller is not the distributor";
    string constant KYC_REQUIRED = "KYC required";
    
    // ========== Token Errors ==========
    string constant INVALID_TOKEN = "Invalid token";
    string constant TOKEN_NOT_ALLOWED = "Payment token not allowed";
    string constant INSUFFICIENT_ALLOWANCE = "Insufficient token allowance";
    string constant TRANSFER_FAILED = "Transfer failed";
    string constant MINT_FAILED = "Mint failed";
    string constant BURN_FAILED = "Burn failed";
    
    // ========== NFT Errors ==========
    string constant NOT_NFT_OWNER = "Not NFT owner";
    string constant NFT_NOT_EXISTS = "NFT does not exist";
    string constant NFT_ALREADY_EXISTS = "NFT already exists";
    string constant INVALID_TOKEN_ID = "Invalid token ID";
    
    // ========== Market Errors ==========
    string constant NOT_LISTED = "Property not listed";
    string constant NOT_AVAILABLE = "Not available";
    string constant ALREADY_LISTED = "Already listed";
    string constant INVALID_PRICE = "Invalid price";
    string constant PAYMENT_FAILED = "Payment failed";
    string constant NOT_SELLER = "Not the seller";
    string constant CANNOT_BID_OWN_LISTING = "Cannot bid on your own listing";
    string constant ETH_AMOUNT_MISMATCH = "ETH amount mismatch";
    string constant ETH_REFUND_FAILED = "ETH refund failed";
    string constant BID_MUST_MEET_PRICE = "Bid must meet listing price";
    string constant NO_BIDS_AVAILABLE = "No bids available";
    string constant NO_PENDING_PAYMENT = "No pending payment";
    string constant EXCESS_REFUND_FAILED = "Excess refund failed";
    string constant BID_INCREMENT_LOW = "Bid increment too low";
    string constant BID_AMOUNT_TOO_LARGE = "Bid amount too large";
    string constant CANNOT_CHANGE_TOKEN = "Cannot change payment token";
    string constant ETH_DEFAULT_ALLOWED = "ETH is allowed by default";
    string constant CANNOT_REMOVE_ETH = "Cannot remove ETH as payment method";
    
    // ========== Bidding Errors ==========
    string constant NO_ACTIVE_BID = "No active bid found";
    string constant BID_NOT_ACTIVE = "Bid is not active";
    string constant NOT_YOUR_BID = "Not your bid";
    string constant INVALID_BID_INDEX = "Invalid bid index";
    string constant BID_TOO_LOW = "Bid too low";
    string constant BIDDER_MISMATCH = "Bidder mismatch";
    string constant AMOUNT_MISMATCH = "Amount mismatch";
    string constant PAYMENT_TOKEN_MISMATCH = "Payment token mismatch";
    string constant INSUFFICIENT_ETH_DEPOSIT = "Insufficient ETH deposit";
    
    // ========== Staking Errors ==========
    string constant INSUFFICIENT_STAKE = "Insufficient stake";
    string constant STAKING_PERIOD_NOT_MET = "Staking period not met";
    string constant ALREADY_STAKED = "Already staked";
    string constant NOT_STAKED = "Not staked";
    string constant REWARD_CALCULATION_FAILED = "Reward calculation failed";
    string constant CLAIM_FAILED = "Claim failed";
    
    // ========== Rebase Errors ==========
    string constant REBASE_TOO_SOON = "Rebase too soon";
    string constant INVALID_REBASE_FACTOR = "Invalid rebase factor";
    string constant REBASE_FAILED = "Rebase failed";
    string constant SUPPLY_LIMIT_EXCEEDED = "Supply limit exceeded";
    string constant BELOW_MIN_SUPPLY = "Below minimum supply";
    
    // ========== Configuration Errors ==========
    string constant INVALID_CONFIGURATION = "Invalid configuration";
    string constant RATE_TOO_HIGH = "Rate too high";
    string constant PERIOD_TOO_SHORT = "Period too short";
    string constant PERIOD_TOO_LONG = "Period too long";
    string constant COOLDOWN_NOT_MET = "Cooldown not met";
    string constant PAUSED = "Contract is paused";
    
    // ========== Payment Errors ==========
    string constant INSUFFICIENT_ETH_SENT = "Insufficient ETH sent";
    string constant PAYMENT_TO_SELLER_FAILED = "Payment to seller failed";
    string constant FEE_PAYMENT_FAILED = "Fee payment failed";
    string constant REFUND_FAILED = "Refund failed";
    string constant TRANSFER_TO_SELLER_FAILED = "Transfer to seller failed";
    string constant FEE_TRANSFER_FAILED = "Fee transfer failed";
    
    // ========== Validation Errors ==========
    string constant INVALID_SIGNATURE = "Invalid signature";
    string constant EXPIRED = "Expired";
    string constant ALREADY_USED = "Already used";
    string constant INVALID_PROOF = "Invalid proof";
    string constant OUT_OF_BOUNDS = "Out of bounds";
    string constant ARRAY_LENGTH_MISMATCH = "Array length mismatch";

    // ========== MA2-02 Mitigation Errors ==========
    string constant TIMELOCK_NOT_SET = "Timelock not configured";
    string constant MULTISIG_NOT_SET = "MultiSig not configured";
    string constant INVALID_TIMELOCK = "Invalid timelock address";
    string constant INVALID_MULTISIG = "Invalid multisig address";
    string constant TIMELOCK_ALREADY_SET = "Timelock already configured";
    string constant MULTISIG_ALREADY_SET = "MultiSig already configured";
    string constant MUST_USE_TIMELOCK = "Must be called through timelock";

    // ========== Bidding Mechanism Fix Errors ==========
    string constant MUST_OUTBID_HIGHEST = "Must exceed highest active bid";
    string constant PURCHASE_AMOUNT_MISMATCH = "Purchase amount mismatch";
    // Note: TRANSFER_FAILED and EXCESS_REFUND_FAILED already defined above
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "./ErrorCodes.sol";

/// @title MarketValidation - Common validation functions for PropertyMarket
/// @dev Library to reduce code duplication and contract size
library MarketValidation {
    
    /// @notice Validates basic requirements for market operations
    /// @param user Address to validate
    /// @param amount Amount to validate
    /// @param isKYCRequired Whether KYC is required
    /// @param userKYCStatus User's KYC status
    /// @param isPaused Whether the contract is paused
    function validateBasicRequirements(
        address user,
        uint256 amount,
        bool isKYCRequired,
        bool userKYCStatus,
        bool isPaused
    ) internal pure {
        require(user != address(0), ErrorCodes.E001);
        require(amount > 0, ErrorCodes.E003);
        if (isKYCRequired) {
            require(userKYCStatus, ErrorCodes.E403);
        }
        require(!isPaused, ErrorCodes.E404);
    }
    
    /// @notice Validates NFT ownership
    /// @param nftContract The NFT contract
    /// @param tokenId Token ID to check
    /// @param expectedOwner Expected owner address
    function validateNFTOwnership(
        address nftContract,
        uint256 tokenId,
        address expectedOwner
    ) internal view {
        require(
            IERC721(nftContract).ownerOf(tokenId) == expectedOwner,
            ErrorCodes.E105
        );
    }
    
    /// @notice Validates payment token
    /// @param paymentToken Token address (address(0) for ETH)
    /// @param allowedTokens Mapping of allowed tokens
    function validatePaymentToken(
        address paymentToken,
        mapping(address => bool) storage allowedTokens
    ) internal view {
        require(allowedTokens[paymentToken], ErrorCodes.E301);
    }
    
    /// @notice Validates ETH payment
    /// @param sentValue msg.value
    /// @param requiredAmount Required amount
    function validateETHPayment(
        uint256 sentValue,
        uint256 requiredAmount
    ) internal pure {
        require(sentValue == requiredAmount, ErrorCodes.E207);
    }
    
    /// @notice Validates ERC20 allowance
    /// @param token Token contract
    /// @param owner Token owner
    /// @param spender Token spender
    /// @param amount Required amount
    function validateERC20Allowance(
        address token,
        address owner,
        address spender,
        uint256 amount
    ) internal view {
        require(
            IERC20(token).allowance(owner, spender) >= amount,
            ErrorCodes.E208
        );
    }
}

interface IERC721 {
    function ownerOf(uint256 tokenId) external view returns (address);
}

interface IERC20 {
    function allowance(address owner, address spender) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title PaymentProcessor - Centralized payment processing library
/// @notice Handles ERC20 token payments with fee calculation
/// @dev Library to consolidate payment logic across contracts
library PaymentProcessor {
        using SafeERC20 for IERC20;

    /// @notice Configuration for payment processing
    struct PaymentConfig {
        uint256 baseFee;        // Fee percentage in basis points
        address feeCollector;   // Address to receive fees
        uint256 percentageBase; // Base for percentage calculations (e.g., 10000 for basis points)
    }
    
    /// @notice Emitted when a payment is processed
    event PaymentProcessed(
        address indexed seller,
        address indexed buyer,
        uint256 amount,
        uint256 fees,
        address paymentToken
    );
    
    /// @notice Processes payment for transactions
    /// @dev Handles ERC20 token payments with proper fee calculation
    /// @param config Payment configuration containing fee settings
    /// @param seller Address of the payment recipient
    /// @param buyer Address of the payment sender
    /// @param amount Total payment amount
    /// @param paymentToken Address of payment token
    function processPayment(
        PaymentConfig memory config,
        address seller,
        address buyer,
        uint256 amount,
        address paymentToken
    ) internal {
        uint256 fees = (amount * config.baseFee) / config.percentageBase;
        uint256 netValue = amount - fees;
        _processTokenPayment(paymentToken, buyer, seller, config.feeCollector, netValue, fees);
        emit PaymentProcessed(seller, buyer, amount, fees, paymentToken);
    }
    
    
    /// @notice Processes ERC20 token payments
    /// @dev Internal function to handle token transfers with fee deduction
    /// @param paymentToken Address of the ERC20 token
    /// @param buyer Address sending the payment
    /// @param seller Address receiving the net payment
    /// @param feeCollector Address receiving the fees
    /// @param netValue Amount to send to seller (after fees)
    /// @param fees Fee amount to send to collector
    function _processTokenPayment(
        address paymentToken,
        address buyer,
        address seller,
        address feeCollector,
        uint256 netValue,
        uint256 fees
    ) private {
        IERC20 token = IERC20(paymentToken);
        token.safeTransferFrom(buyer, seller, netValue);  
        token.safeTransferFrom(buyer, feeCollector, fees);

    }
    
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ErrorCodes.sol";

/// @title PaymentValidation - Library for payment validation operations
/// @dev Extracts payment validation logic to reduce main contract size
library PaymentValidation {

    /// @notice Validate payment for property purchase
    /// @param listedPrice The original listing price
    /// @param offerPrice The offered price
    /// @param paymentToken The payment token address (address(0) for ETH)
    /// @param highestBid The current highest bid
    /// @param allowedTokens Mapping of allowed payment tokens
    /// @return valid Whether the payment is valid
    function validatePayment(
        uint256 listedPrice,
        uint256 offerPrice,
        address paymentToken,
        uint256 highestBid,
        mapping(address => bool) storage allowedTokens
    ) external view returns (bool valid) {
        // Validate that the payment token is allowed
        if (!allowedTokens[paymentToken]) {
            return false;
        }

        // Check if there are active bids that need to be outbid
        uint256 minimumPrice = highestBid > 0 ? highestBid : listedPrice;

        if (paymentToken == address(0)) {
            // For ETH payments, ensure msg.value equals offerPrice
            return msg.value >= minimumPrice && offerPrice >= minimumPrice && msg.value == offerPrice;
        } else {
            return offerPrice >= minimumPrice;
        }
    }

    /// @notice Validate token allowance for ERC20 payments
    /// @param token The ERC20 token contract
    /// @param spender The spender address (usually the contract)
    /// @param amount The required amount
    /// @return valid Whether allowance is sufficient
    function validateTokenAllowance(
        IERC20 token,
        address spender,
        uint256 amount
    ) external view returns (bool valid) {
        return token.allowance(msg.sender, spender) >= amount;
    }

    /// @notice Safe token transfer with deflationary token support
    /// @param token The ERC20 token contract
    /// @param from The sender address
    /// @param to The recipient address
    /// @param amount The amount to transfer
    /// @return actualReceived The actual amount received (may be less for deflationary tokens)
    function safeTokenTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 amount
    ) external returns (uint256 actualReceived) {
        uint256 balanceBefore = token.balanceOf(to);
        
        bool success = token.transferFrom(from, to, amount);
        require(success, ErrorCodes.E707);
        
        uint256 balanceAfter = token.balanceOf(to);
        actualReceived = balanceAfter - balanceBefore;
    }

    /// @notice Validate bid payment (ETH or ERC20)
    /// @param bidAmount The bid amount
    /// @param paymentToken The payment token (address(0) for ETH)
    /// @param allowedTokens Mapping of allowed payment tokens
    /// @return valid Whether the payment is valid
    function validateBidPayment(
        uint256 bidAmount,
        address paymentToken,
        mapping(address => bool) storage allowedTokens
    ) external view returns (bool valid) {
        // Check if token is allowed
        if (!allowedTokens[paymentToken]) {
            return false;
        }

        if (paymentToken == address(0)) {
            // For ETH, msg.value must equal bid amount
            return msg.value == bidAmount;
        } else {
            // For ERC20, check allowance
            IERC20 token = IERC20(paymentToken);
            return token.allowance(msg.sender, address(this)) >= bidAmount;
        }
    }

    /// @notice Calculate payment distribution (seller amount and fees)
    /// @param totalAmount The total payment amount
    /// @param feeRate The fee rate (in basis points)
    /// @param percentageBase The percentage base (usually 10000)
    /// @return sellerAmount Amount for the seller
    /// @return feeAmount Amount for fees
    function calculatePaymentDistribution(
        uint256 totalAmount,
        uint256 feeRate,
        uint256 percentageBase
    ) external pure returns (uint256 sellerAmount, uint256 feeAmount) {
        feeAmount = (totalAmount * feeRate) / percentageBase;
        sellerAmount = totalAmount - feeAmount;
    }

    /// @notice Validate ETH payment amount
    /// @param expectedAmount The expected ETH amount
    /// @return valid Whether msg.value matches expected amount
    function validateETHAmount(uint256 expectedAmount) external view returns (bool valid) {
        return msg.value == expectedAmount;
    }

    /// @notice Validate additional payment for bid increases
    /// @param oldAmount The previous bid amount
    /// @param newAmount The new bid amount
    /// @param paymentToken The payment token (address(0) for ETH)
    /// @return valid Whether the additional payment is valid
    /// @return additionalAmount The additional amount required
    function validateAdditionalPayment(
        uint256 oldAmount,
        uint256 newAmount,
        address paymentToken
    ) external view returns (bool valid, uint256 additionalAmount) {
        if (newAmount <= oldAmount) {
            return (msg.value == 0, 0);
        }

        additionalAmount = newAmount - oldAmount;

        if (paymentToken == address(0)) {
            return (msg.value == additionalAmount, additionalAmount);
        } else {
            IERC20 token = IERC20(paymentToken);
            return (token.allowance(msg.sender, address(this)) >= additionalAmount, additionalAmount);
        }
    }

    /// @notice Check if a token is deflationary
    /// @param token The token address
    /// @param deflationaryTokens Mapping of deflationary tokens
    /// @return isDeflationary Whether the token is deflationary
    function isDeflationaryToken(
        address token,
        mapping(address => bool) storage deflationaryTokens
    ) external view returns (bool isDeflationary) {
        return deflationaryTokens[token];
    }
}

File 50 of 63 : StakingConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library StakingConstants {
    uint256 public constant MIN_STAKING_PERIOD = 7 days;
    uint256 public constant MAX_STAKING_PERIOD = 365 days;
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "./Errors.sol";

/// @title Validation - Centralized validation library
/// @notice Provides common validation functions across all contracts
/// @dev Library to ensure consistent validation logic and reduce code duplication
library Validation {
    
    /// @notice Validates that an address is not zero
    /// @param addr The address to validate
    function validateNonZeroAddress(address addr) internal pure {
        require(addr != address(0), Errors.ZERO_ADDRESS);
    }
    
    /// @notice Validates that an amount is greater than zero
    /// @param amount The amount to validate
    function validatePositiveAmount(uint256 amount) internal pure {
        require(amount > 0, Errors.INVALID_AMOUNT);
    }
    
    /// @notice Validates that two addresses are different
    /// @param addr1 First address
    /// @param addr2 Second address
    function validateDifferentAddresses(address addr1, address addr2) internal pure {
        require(addr1 != addr2, "Addresses must be different");
    }
    
    /// @notice Validates that an array is not empty
    /// @param length The length of the array
    function validateNonEmptyArray(uint256 length) internal pure {
        require(length > 0, "Array cannot be empty");
    }
    
    /// @notice Validates that two arrays have the same length
    /// @param length1 Length of first array
    /// @param length2 Length of second array
    function validateArrayLengths(uint256 length1, uint256 length2) internal pure {
        require(length1 == length2, Errors.ARRAY_LENGTH_MISMATCH);
    }
    
    /// @notice Validates that a percentage is within valid range (0-10000 basis points)
    /// @param percentage The percentage in basis points
    function validatePercentage(uint256 percentage) internal pure {
        require(percentage <= 10000, "Percentage too high");
    }
    
    /// @notice Validates that a timestamp is in the future
    /// @param timestamp The timestamp to validate
    function validateFutureTimestamp(uint256 timestamp) internal view {
        require(timestamp > block.timestamp, "Timestamp must be in future");
    }
    
    /// @notice Validates that a timestamp is not expired
    /// @param timestamp The timestamp to validate
    function validateNotExpired(uint256 timestamp) internal view {
        require(timestamp >= block.timestamp, Errors.EXPIRED);
    }
    
    /// @notice Validates that an index is within bounds
    /// @param index The index to validate
    /// @param maxIndex The maximum valid index (exclusive)
    function validateIndex(uint256 index, uint256 maxIndex) internal pure {
        require(index < maxIndex, Errors.OUT_OF_BOUNDS);
    }
    
    /// @notice Validates that a value is within a specified range
    /// @param value The value to validate
    /// @param min Minimum allowed value (inclusive)
    /// @param max Maximum allowed value (inclusive)
    function validateRange(uint256 value, uint256 min, uint256 max) internal pure {
        require(value >= min && value <= max, "Value out of range");
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {AdminControl} from "../governance/AdminControl.sol";
import {PaymentProcessor} from "../libraries/PaymentProcessor.sol";
import {ErrorCodes} from "../libraries/ErrorCodes.sol";

contract PropertyMarket is ReentrancyGuard {
    using SafeERC20 for IERC20;
    constructor(address _nfti, address _nftm, AdminControl _adminControl){
        require(_nfti != address(0), ErrorCodes.E001);
        require(_nftm != address(0), ErrorCodes.E001);

        nftiContract = IERC721(_nfti);
        nftmContract = IERC721(_nftm);
        adminControl = _adminControl;
    }

    uint256 public constant PERCENTAGE_BASE = 10000;

    enum PropertyStatus { LISTED, SOLD, DELISTED, PENDING_SELLER_CONFIRMATION }

    struct Bid {
        uint256 tokenId;
        address bidder;
        uint256 amount;
        address paymentToken;
        uint256 bidTimestamp;
        bool isActive;
    }

    struct PropertyListing {
        uint256 tokenId;
        address seller;
        uint256 price;
        address paymentToken;
        PropertyStatus status;
        uint256 listTimestamp;
        uint256 lastRenewed;
        uint256 confirmationPeriod;
    }

    struct PendingPurchase {
        uint256 tokenId;
        address buyer;
        uint256 offerPrice;
        address paymentToken;
        uint256 purchaseTimestamp;
        uint256 confirmationDeadline;
        bool isActive;
    }

    IERC721 public immutable nftiContract;
    IERC721 public immutable nftmContract;
    mapping(address => bool) public allowedPaymentTokens;
    AdminControl public adminControl;

    mapping(uint256 => PropertyListing) public listings;
    mapping(uint256 => PendingPurchase) public pendingPurchases;

    mapping(uint256 => Bid[]) public bidsForToken;
    mapping(address => mapping(uint256 => uint256)) public bidIndexByBidder;
    event NewListing(
        uint256 indexed tokenId,
        address indexed seller,
        uint256 price,
        address paymentToken
    );

    event PropertySold(
        uint256 indexed tokenId,
        address buyer,
        uint256 price,
        address paymentToken
    );

    event ListingUpdated(
        uint256 indexed tokenId,
        uint256 newPrice,
        address newPaymentToken
    );
    event BidPlaced(
        uint256 indexed tokenId,
        address indexed bidder,
        uint256 amount,
        address paymentToken
    );

    event BidAccepted(
        uint256 indexed tokenId,
        address indexed seller,
        address indexed bidder,
        uint256 amount,
        address paymentToken
    );

    event BidCancelled(
        uint256 indexed tokenId,
        address indexed bidder,
        uint256 amount
    );
    event PaymentTokenAdded(address indexed token);
    event PaymentTokenRemoved(address indexed token);
    event ListingPriceChanged(uint256 indexed tokenId, uint256 newPrice);

    event EmergencyTokenWithdrawal(address indexed token, address indexed recipient, uint256 amount);
    event CompetitivePurchase(
        uint256 indexed tokenId,
        address indexed buyer,
        uint256 purchasePrice,
        uint256 highestBidOutbid,
        address paymentToken
    );
    event PurchaseRequested(
        uint256 indexed tokenId,
        address indexed buyer,
        uint256 offerPrice,
        address paymentToken,
        uint256 confirmationDeadline
    );

    event PurchaseConfirmed(
        uint256 indexed tokenId,
        address indexed seller,
        address indexed buyer,
        uint256 finalPrice,
        address paymentToken
    );

    event PurchaseRejected(
        uint256 indexed tokenId,
        address indexed seller,
        address indexed buyer,
        uint256 offerPrice,
        address paymentToken
    );

    event PurchaseExpired(
        uint256 indexed tokenId,
        address indexed buyer,
        uint256 offerPrice,
        address paymentToken
    );


    error DirectEthTransferNotAllowed();

    function isTokenAllowed(address token) internal view returns (bool) {
        return allowedPaymentTokens[token];
    }
    function addAllowedToken(address token) external onlyAdminControlAdmin {
        require(token != address(0), ErrorCodes.E001);
        allowedPaymentTokens[token] = true;
        emit PaymentTokenAdded(token);
    }
    function removeAllowedToken(address token) external onlyAdminControlAdmin {
        require(token != address(0), ErrorCodes.E001);
        allowedPaymentTokens[token] = false;
        emit PaymentTokenRemoved(token);
    }
    
    function listProperty(uint256 tokenId, uint256 price, address paymentToken) external nonReentrant onlyKYCVerified onlyAllowedToken(paymentToken) onlyValidAmount(price) {
        _listPropertyWithConfirmation(tokenId, price, paymentToken, 0);
    }

    function listPropertyWithConfirmation(uint256 tokenId, uint256 price, address paymentToken, uint256 period) external nonReentrant onlyKYCVerified onlyAllowedToken(paymentToken) onlyValidAmount(price) {
        require(period <= 7 days, ErrorCodes.E607);
        _listPropertyWithConfirmation(tokenId, price, paymentToken, period);
    }
    function _listPropertyWithConfirmation(uint256 tokenId, uint256 price, address paymentToken, uint256 period) internal {
        address currentOwner = nftiContract.ownerOf(tokenId);
        require(currentOwner == msg.sender, ErrorCodes.E105);
        PropertyListing storage existingListing = listings[tokenId];

        if (existingListing.seller != address(0) && existingListing.seller != currentOwner) {
            if (existingListing.status == PropertyStatus.LISTED) {
                _cancelAllBids(tokenId);
            }
        } else if (existingListing.seller == currentOwner) {
            require(existingListing.status != PropertyStatus.LISTED, ErrorCodes.E102);
        }

        listings[tokenId] = PropertyListing({
            tokenId: tokenId,
            seller: msg.sender,
            price: price,
            paymentToken: paymentToken,
            status: PropertyStatus.LISTED,
            listTimestamp: block.timestamp,
            lastRenewed: block.timestamp,
            confirmationPeriod: period
        });

        emit NewListing(tokenId, msg.sender, price, paymentToken);
    }
    function purchaseProperty(uint256 tokenId, uint256 offerPrice) external nonReentrant onlyKYCVerified onlyValidAmount(offerPrice) {
        PropertyListing storage listing = listings[tokenId];
        require(listing.status == PropertyStatus.LISTED, ErrorCodes.E101);
        require(_validatePayment(listing.price, offerPrice, listing.paymentToken, tokenId), ErrorCodes.E005);
        uint256 highestBid = _getHighestActiveBid(tokenId);
        uint256 actualPrice = highestBid > 0 ? offerPrice : listing.price;
        if (listing.confirmationPeriod > 0) {
            _createPendingPurchase(tokenId, actualPrice, listing.paymentToken);
        } else {
            _completePurchase(tokenId, actualPrice, listing.paymentToken, highestBid);
        }
    }
    function _createPendingPurchase(uint256 tokenId, uint256 actualPrice, address paymentToken) internal {
        PropertyListing storage listing = listings[tokenId];
        IERC20 token = IERC20(paymentToken);
        token.safeTransferFrom(msg.sender, address(this), actualPrice);
        listing.status = PropertyStatus.PENDING_SELLER_CONFIRMATION;
        uint256 deadline = block.timestamp + listing.confirmationPeriod;

        pendingPurchases[tokenId] = PendingPurchase({
            tokenId: tokenId,
            buyer: msg.sender,
            offerPrice: actualPrice,
            paymentToken: paymentToken,
            purchaseTimestamp: block.timestamp,
            confirmationDeadline: deadline,
            isActive: true
        });

        emit PurchaseRequested(tokenId, msg.sender, actualPrice, paymentToken, deadline);
    }
    function _completePurchase(uint256 tokenId, uint256 actualPrice, address paymentToken, uint256 highestBid) internal {
        PropertyListing storage listing = listings[tokenId];

        listing.status = PropertyStatus.SOLD;
        _cancelAllBids(tokenId);

        _processPayment(listing.seller, msg.sender, actualPrice, paymentToken);
        nftiContract.safeTransferFrom(listing.seller, msg.sender, tokenId, "");

        emit PropertySold(tokenId, msg.sender, actualPrice, paymentToken);
        if (highestBid > 0) {
            emit CompetitivePurchase(
                tokenId,
                msg.sender,
                actualPrice,
                highestBid,
                paymentToken
            );
        }
    }
    function _handlePurchaseDecision(uint256 tokenId, bool accept) internal {
        PropertyListing storage listing = listings[tokenId];
        PendingPurchase storage purchase = pendingPurchases[tokenId];

        require(listing.status == PropertyStatus.PENDING_SELLER_CONFIRMATION, ErrorCodes.E602);
        require(purchase.isActive, ErrorCodes.E603);
        require(nftiContract.ownerOf(tokenId) == msg.sender, ErrorCodes.E604);
        require(block.timestamp <= purchase.confirmationDeadline, ErrorCodes.E605);

        purchase.isActive = false;

        if (accept) {
            listing.status = PropertyStatus.SOLD;
            _cancelAllBids(tokenId);
            _processPayment(listing.seller, purchase.buyer, purchase.offerPrice, purchase.paymentToken);
            nftiContract.safeTransferFrom(listing.seller, purchase.buyer, tokenId, "");
            emit PurchaseConfirmed(tokenId, msg.sender, purchase.buyer, purchase.offerPrice, purchase.paymentToken);
            emit PropertySold(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken);
        } else {
            _refundPendingPurchase(tokenId);
            listing.status = PropertyStatus.LISTED;
            emit PurchaseRejected(tokenId, msg.sender, purchase.buyer, purchase.offerPrice, purchase.paymentToken);
        }
    }
    function confirmPurchase(uint256 tokenId) external nonReentrant {
        _handlePurchaseDecision(tokenId, true);
    }
    function rejectPurchase(uint256 tokenId) external nonReentrant {
        _handlePurchaseDecision(tokenId, false);
    }
    function cancelExpiredPurchase(uint256 tokenId) external nonReentrant {
        PropertyListing storage listing = listings[tokenId];
        PendingPurchase storage purchase = pendingPurchases[tokenId];

        require(listing.status == PropertyStatus.PENDING_SELLER_CONFIRMATION, ErrorCodes.E602);
        require(purchase.isActive, ErrorCodes.E603);
        require(block.timestamp > purchase.confirmationDeadline, ErrorCodes.E606);
        _refundPendingPurchase(tokenId);
        purchase.isActive = false;
        listing.status = PropertyStatus.LISTED;

        emit PurchaseExpired(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken);
    }
    function _refundPendingPurchase(uint256 tokenId) internal {
        PendingPurchase storage purchase = pendingPurchases[tokenId];
        IERC20 token = IERC20(purchase.paymentToken);
        token.safeTransfer(purchase.buyer, purchase.offerPrice);
    }

    function _cancelAllBids(uint256 tokenId) private {
        Bid[] storage bids = bidsForToken[tokenId];
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive) {
                address bidder = bids[i].bidder;
                uint256 refundAmount = bids[i].amount;
                address paymentToken = bids[i].paymentToken;

                bids[i].isActive = false;
                bidIndexByBidder[bidder][tokenId] = 0;
                _refundBid(bidder, refundAmount, paymentToken, tokenId);

                emit BidCancelled(tokenId, bidder, refundAmount);
            }
        }
    }

    function _cancelOtherBids(uint256 tokenId, address excludeBidder) private {
        Bid[] storage bids = bidsForToken[tokenId];
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].bidder != excludeBidder) {
                address bidder = bids[i].bidder;
                uint256 refundAmount = bids[i].amount;
                address paymentToken = bids[i].paymentToken;

                bids[i].isActive = false;
                bidIndexByBidder[bidder][tokenId] = 0;
                _refundBid(bidder, refundAmount, paymentToken, tokenId);

                emit BidCancelled(tokenId, bidder, refundAmount);
            }
        }
    }

    function _refundBid(address bidder, uint256 amount, address paymentToken, uint256) private {
        IERC20(paymentToken).safeTransfer(bidder, amount);
    }
    function _validatePayment(
        uint256 listedPrice,
        uint256 offerPrice,
        address paymentToken,
        uint256 tokenId
    ) private view returns (bool) {
        if (!isTokenAllowed(paymentToken)) {
            return false;
        }
        uint256 highestBid = _getHighestActiveBid(tokenId);
        uint256 minimumPrice = highestBid > 0 ? highestBid : listedPrice;
        return offerPrice >= minimumPrice;
    }

    function _processPayment(
        address seller,
        address buyer,
        uint256 amount,
        address paymentToken
    ) internal {
        (uint256 baseFee,, address feeCollector) = adminControl.feeConfig();
        PaymentProcessor.PaymentConfig memory config = PaymentProcessor.PaymentConfig({
            baseFee: baseFee,
            feeCollector: feeCollector,
            percentageBase: PERCENTAGE_BASE
        });

        PaymentProcessor.processPayment(
            config,
            seller,
            buyer,
            amount,
            paymentToken
        );
    }

    function _processPaymentFromBalance(
        address seller,
        uint256 amount,
        address paymentToken
    ) internal {
        (uint256 baseFee,, address feeCollector) = adminControl.feeConfig();

        uint256 fees = (amount * baseFee) / PERCENTAGE_BASE;
        uint256 netValue = amount - fees;

        IERC20 token = IERC20(paymentToken);
        token.safeTransfer(seller, netValue);
        token.safeTransfer(feeCollector, fees);
        
    }
    function updateListing(uint256 tokenId, uint256 newPrice, address newPaymentToken) external onlyAdminControlAdmin {
        PropertyListing storage listing = listings[tokenId];
        require(listing.status == PropertyStatus.LISTED, ErrorCodes.E103);
        require(newPrice > 0, ErrorCodes.E104);
        require(isTokenAllowed(newPaymentToken), ErrorCodes.E301);

        listing.price = newPrice;
        listing.paymentToken = newPaymentToken;
        listing.lastRenewed = block.timestamp;

        emit ListingUpdated(tokenId, newPrice, newPaymentToken);
    }


    modifier onlyAdminControlAdmin(){
        require(adminControl.hasRole(adminControl.DEFAULT_ADMIN_ROLE(), msg.sender), ErrorCodes.E401);
        _;
    }

    modifier onlyTokenOwner(uint256 tokenId) {
        require(nftiContract.ownerOf(tokenId) == msg.sender, ErrorCodes.E002);
        _;
    }

    modifier onlyKYCVerified() {
        require(adminControl.isKYCVerified(msg.sender), ErrorCodes.E403);
        _;
    }

    modifier onlyAllowedToken(address token) {
        require(isTokenAllowed(token), ErrorCodes.E301);
        _;
    }

    modifier onlyValidAmount(uint256 amount) {
        require(amount > 0, ErrorCodes.E003);
        _;
    }

    function getListingDetails(uint256 tokenId)
        external
        view
        returns (
            address seller,
            uint256 price,
            address paymentToken,
            PropertyStatus status,
            uint256 listTimestamp,
            uint256 confirmationPeriod
        )
    {
        PropertyListing storage listing = listings[tokenId];
        return (
            listing.seller,
            listing.price,
            listing.paymentToken,
            listing.status,
            listing.listTimestamp,
            listing.confirmationPeriod
        );
    }

    function placeBid(uint256 tokenId, uint256 bidAmount, address paymentToken) external nonReentrant onlyKYCVerified onlyAllowedToken(paymentToken) onlyValidAmount(bidAmount) {
        PropertyListing storage listing = listings[tokenId];
        require(listing.status == PropertyStatus.LISTED, ErrorCodes.E103);

        address currentOwner = nftiContract.ownerOf(tokenId);
        require(currentOwner != msg.sender, ErrorCodes.E002);
        uint256 existingBidIndex = bidIndexByBidder[msg.sender][tokenId];
        if (existingBidIndex > 0) {
            Bid storage existingBid = bidsForToken[tokenId][existingBidIndex - 1];
            require(existingBid.isActive, ErrorCodes.E202);
            require(existingBid.paymentToken == paymentToken, ErrorCodes.E302);

            uint256 oldAmount = existingBid.amount;
            require(bidAmount > oldAmount, ErrorCodes.E205);
            uint256 additionalAmount = bidAmount - oldAmount;
            IERC20 token = IERC20(paymentToken);
            require(token.allowance(msg.sender, address(this)) >= additionalAmount, ErrorCodes.E208);
            token.safeTransferFrom(msg.sender, address(this), additionalAmount);

        } else {
            IERC20 token = IERC20(paymentToken);
            require(token.allowance(msg.sender, address(this)) >= bidAmount, ErrorCodes.E208);
            token.safeTransferFrom(msg.sender, address(this), bidAmount);
        }

        require(bidAmount >= listing.price, ErrorCodes.E206);
        uint256 highestBid = 0;
        Bid[] storage bids = bidsForToken[tokenId];
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].amount > highestBid) {
                highestBid = bids[i].amount;
            }
        }

        if (highestBid > 0) {
            uint256 minBid = highestBid;
            require(bidAmount >= minBid, ErrorCodes.E205);
        }

        if (existingBidIndex > 0) {
            Bid storage existingBid = bidsForToken[tokenId][existingBidIndex - 1];
            existingBid.amount = bidAmount;
            existingBid.bidTimestamp = block.timestamp;
        } else {
            Bid memory newBid = Bid({
                tokenId: tokenId,
                bidder: msg.sender,
                amount: bidAmount,
                paymentToken: paymentToken,
                bidTimestamp: block.timestamp,
                isActive: true
            });

            bidsForToken[tokenId].push(newBid);
            bidIndexByBidder[msg.sender][tokenId] = bidsForToken[tokenId].length;
        }

        emit BidPlaced(tokenId, msg.sender, bidAmount, paymentToken);
    }

    function acceptBid(uint256 tokenId, uint256 bidIndex, address expectedBidder, uint256 expectedAmount, address expectedPaymentToken) external nonReentrant {
        PropertyListing storage listing = listings[tokenId];
        require(listing.status == PropertyStatus.LISTED, ErrorCodes.E103);
        require(nftiContract.ownerOf(tokenId) == msg.sender, ErrorCodes.E105);

        if (listing.seller != msg.sender) {
            listing.seller = msg.sender;
        }

        require(bidIndex > 0, ErrorCodes.E502);
        require(bidIndex <= bidsForToken[tokenId].length, ErrorCodes.E502);
        require(bidsForToken[tokenId].length > 0, ErrorCodes.E504);

        Bid storage bid = bidsForToken[tokenId][bidIndex - 1];
        require(bid.isActive, ErrorCodes.E202);
        require(bid.bidder == expectedBidder, ErrorCodes.E501);
        require(bid.amount == expectedAmount, ErrorCodes.E501);
        require(bid.paymentToken == expectedPaymentToken, ErrorCodes.E302);


        listing.status = PropertyStatus.SOLD;
        bid.isActive = false;
        bidIndexByBidder[bid.bidder][tokenId] = 0;
        _processPaymentFromBalance(listing.seller, bid.amount, bid.paymentToken);
        nftiContract.safeTransferFrom(listing.seller, bid.bidder, tokenId, "");
        emit BidAccepted(tokenId, listing.seller, bid.bidder, bid.amount, bid.paymentToken);
        
        _cancelOtherBids(tokenId, bid.bidder);
    }

    function _calculateMinimumIncrement(uint256 currentHighest, uint256 /* newBid */) private pure returns (uint256) {
        uint256 incrementPercent;
        if (currentHighest < 1 ether) {
            incrementPercent = 10;
        } else if (currentHighest < 10 ether) {
            incrementPercent = 5;
        } else {
            incrementPercent = 2;
        }

        uint256 multiplier = 100 + incrementPercent;
        require(currentHighest <= type(uint256).max / multiplier, ErrorCodes.E502);

        return (currentHighest * multiplier) / 100;
    }

    function _getHighestActiveBid(uint256 tokenId) private view returns (uint256) {
        uint256 highest = 0;
        Bid[] storage bids = bidsForToken[tokenId];
        for (uint256 i = 0; i < bids.length; i++) {
            if (bids[i].isActive && bids[i].amount > highest) {
                highest = bids[i].amount;
            }
        }
        return highest;
    }

    function updateListingBySeller(uint256 tokenId, uint256 newPrice, address newPaymentToken) external onlyValidAmount(newPrice) onlyAllowedToken(newPaymentToken) {
        PropertyListing storage listing = listings[tokenId];
        require(listing.status == PropertyStatus.LISTED, ErrorCodes.E103);
        require(nftiContract.ownerOf(tokenId) == msg.sender, ErrorCodes.E105);

        address currentOwner = msg.sender;
        if (listing.seller != currentOwner) {
            listing.seller = currentOwner;
        }
        if (newPaymentToken != listing.paymentToken) {
            Bid[] storage bids = bidsForToken[tokenId];
            for (uint256 i = 0; i < bids.length; i++) {
                require(!bids[i].isActive, ErrorCodes.E911);
            }
        }

        listing.price = newPrice;
        listing.paymentToken = newPaymentToken;
        listing.lastRenewed = block.timestamp;

        emit ListingUpdated(tokenId, newPrice, newPaymentToken);
        emit ListingPriceChanged(tokenId, newPrice);
    }

    function cancelBid(uint256 tokenId) external nonReentrant {
        uint256 bidIndex = bidIndexByBidder[msg.sender][tokenId];
        require(bidIndex > 0, ErrorCodes.E201);

        Bid storage bid = bidsForToken[tokenId][bidIndex - 1];
        require(bid.isActive, ErrorCodes.E202);
        require(bid.bidder == msg.sender, ErrorCodes.E203);
        uint256 refundAmount = bid.amount;
        address paymentToken = bid.paymentToken;

        bid.isActive = false;
        bidIndexByBidder[msg.sender][tokenId] = 0;
        IERC20 token = IERC20(paymentToken);
        token.safeTransfer(msg.sender, refundAmount);
        emit BidCancelled(tokenId, msg.sender, refundAmount);
    }

    function emergencyWithdrawToken(address token, uint256 amount, address recipient) onlyAdminControlAdmin() external {
        require(token != address(0), ErrorCodes.E915);
        require(recipient != address(0), ErrorCodes.E913);

        IERC20 tokenContract = IERC20(token);
        require(amount <= tokenContract.balanceOf(address(this)), ErrorCodes.E916);

        tokenContract.safeTransfer(recipient, amount);

        emit EmergencyTokenWithdrawal(token, recipient, amount);
    }

    //We don't want to allow direct eth transfers to the contract
    receive() external payable {
        revert DirectEthTransferNotAllowed();
    }

}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {AdminControl} from "../governance/AdminControl.sol";
import {PaymentProcessor} from "../libraries/PaymentProcessor.sol";
import {BiddingLibrary} from "../libraries/BiddingLibrary.sol";
import {ErrorCodes} from "../libraries/ErrorCodes.sol";

/**
 * @title PropertyMarketOptimized
 * @notice Optimized version of PropertyMarket with reduced contract size
 * @dev Key optimizations:
 * - Packed struct fields to reduce storage slots
 * - Extracted bidding logic to BiddingLibrary
 * - Merged similar events and validations
 * - Optimized modifiers and internal functions
 */
contract PropertyMarketOptimized is ReentrancyGuard {
    using SafeERC20 for IERC20;
    using BiddingLibrary for BiddingLibrary.Bid[];

    uint256 public constant PERCENTAGE_BASE = 10000;

    enum PropertyStatus {
        LISTED,                         // 0
        SOLD,                          // 1
        DELISTED,                      // 2
        PENDING_SELLER_CONFIRMATION    // 3
    }

    // Optimized PropertyListing structure with packed fields
    struct PropertyListing {
        address seller;                 // 20 bytes
        address paymentToken;           // 20 bytes
        uint256 price;                  // 32 bytes
        uint256 tokenId;                // 32 bytes
        uint64 listTimestamp;           // 8 bytes - packed
        uint64 lastRenewed;             // 8 bytes - packed
        uint32 confirmationPeriod;      // 4 bytes - packed (max ~136 years in seconds)
        uint8 status;                   // 1 byte - packed (PropertyStatus enum)
    }

    // Optimized PendingPurchase structure with packed fields
    struct PendingPurchase {
        address buyer;                  // 20 bytes
        address paymentToken;           // 20 bytes
        uint256 offerPrice;             // 32 bytes
        uint256 tokenId;                // 32 bytes
        uint64 purchaseTimestamp;       // 8 bytes - packed
        uint64 confirmationDeadline;    // 8 bytes - packed
        bool isActive;                  // 1 byte - packed
    }

    IERC721 public immutable nftiContract;
    IERC721 public immutable nftmContract;
    AdminControl public immutable adminControl;

    address public immutable governanceExecutor;

    // Function identifiers for fine-grained pause control
    uint256 public constant FN_LIST = 1;
    uint256 public constant FN_PURCHASE = 2;
    uint256 public constant FN_BID = 3;
    uint256 public constant FN_ACCEPT_BID = 4;
    uint256 public constant FN_CANCEL_BID = 5;
    uint256 public constant FN_CONFIRM = 6;
    uint256 public constant FN_REJECT = 7;
    uint256 public constant FN_CANCEL_EXPIRED = 8;
    uint256 public constant FN_DELIST = 9;
    uint256 public constant FN_ADMIN_UPDATE_LISTING = 100;
    uint256 public constant FN_ALLOWED_TOKEN_UPDATE = 101;

    mapping(address => bool) public allowedPaymentTokens;
    mapping(uint256 => PropertyListing) public listings;
    mapping(uint256 => PendingPurchase) public pendingPurchases;
    mapping(uint256 => BiddingLibrary.Bid[]) public bidsForToken;
    mapping(address => mapping(uint256 => uint256)) public bidIndexByBidder;
    mapping(address => mapping(address => uint256)) public refundableBalances; // bidder => token => amount

    // Active bids counter per tokenId (for O(1) checks)
    mapping(uint256 => uint256) public activeBidsCount;

    // Cap for active bids per token to prevent unbounded growth
    uint256 public maxActiveBidsPerToken = 200;
    event MaxActiveBidsPerTokenUpdated(uint256 oldValue, uint256 newValue);
    function setMaxActiveBidsPerToken(uint256 newMax) external onlyAdmin {
        require(newMax > 0, ErrorCodes.E501);
        uint256 old = maxActiveBidsPerToken;
        maxActiveBidsPerToken = newMax;
        emit MaxActiveBidsPerTokenUpdated(old, newMax);
    }


    // Merged events to reduce contract size
    event ListingEvent(
        uint256 indexed tokenId,
        address indexed seller,
        uint256 price,
        address paymentToken,
        uint8 eventType  // 0=NewListing, 1=Updated, 2=PriceChanged
    );

    event PropertySold(
        uint256 indexed tokenId,
        address indexed buyer,
        uint256 price,
        address paymentToken,
        bool wasCompetitive
    );

    event RefundClaimed(address indexed user, address indexed paymentToken, uint256 amount);

    event PurchaseStatusChanged(
        uint256 indexed tokenId,
        address indexed buyer,
        uint256 offerPrice,
        address paymentToken,
        uint64 deadline,
        uint8 statusType  // 0=Requested, 1=Confirmed, 2=Rejected, 3=Expired
    );

    event PaymentTokenUpdated(address indexed token, bool allowed);
    event EmergencyTokenWithdrawal(address indexed token, address indexed recipient, uint256 amount);
    event PropertyDelisted(uint256 indexed tokenId, address indexed seller);

    error DirectEthTransferNotAllowed();
    error InvalidInput();

    constructor(
        address _nfti,
        address _nftm,
        AdminControl _adminControl,
        address _governanceExecutor
    ) {
        if (
            _nfti == address(0) ||
            _nftm == address(0) ||
            address(_adminControl) == address(0) ||
            _governanceExecutor == address(0)
        ) {
            revert InvalidInput();
        }

        nftiContract = IERC721(_nfti);
        nftmContract = IERC721(_nftm);
        adminControl = _adminControl;
        governanceExecutor = _governanceExecutor;
    }

    // ========== Token Management ==========

    function addAllowedToken(address token) external whenSystemActive whenFunctionActive(FN_ALLOWED_TOKEN_UPDATE) onlyAdmin {
        require(token != address(0), ErrorCodes.E001);
        allowedPaymentTokens[token] = true;
        emit PaymentTokenUpdated(token, true);
    }

    function removeAllowedToken(address token) external whenSystemActive whenFunctionActive(FN_ALLOWED_TOKEN_UPDATE) onlyAdmin {
        require(token != address(0), ErrorCodes.E001);
        allowedPaymentTokens[token] = false;
        emit PaymentTokenUpdated(token, false);
    }

    // ========== Listing Functions ==========

    function listProperty(
        uint256 tokenId,
        uint256 price,
        address paymentToken
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_LIST) onlyKYCVerified {
        _listPropertyInternal(tokenId, price, paymentToken, 0);
    }

    function listPropertyWithConfirmation(
        uint256 tokenId,
        uint256 price,
        address paymentToken,
        uint256 period
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_LIST) onlyKYCVerified {
        require(period <= 7 days, ErrorCodes.E607);
        _listPropertyInternal(tokenId, price, paymentToken, period);
    }

    function _listPropertyInternal(
        uint256 tokenId,
        uint256 price,
        address paymentToken,
        uint256 period
    ) internal {
        // Combined validation
        require(
            price > 0 &&
            allowedPaymentTokens[paymentToken] &&
            nftiContract.ownerOf(tokenId) == msg.sender,
            ErrorCodes.E001
        );

        PropertyListing storage existingListing = listings[tokenId];

        // Cancel bids if listing exists and seller changed
        if (existingListing.seller != address(0) &&
            existingListing.seller != msg.sender &&
            existingListing.status == uint8(PropertyStatus.LISTED)) {
            BiddingLibrary.cancelAllBids(bidsForToken[tokenId], bidIndexByBidder, tokenId, refundableBalances, activeBidsCount);
        } else if (existingListing.seller == msg.sender) {
            require(existingListing.status != uint8(PropertyStatus.LISTED), ErrorCodes.E102);
        }

        // Create optimized listing
        listings[tokenId] = PropertyListing({
            seller: msg.sender,
            paymentToken: paymentToken,
            price: price,
            tokenId: tokenId,
            listTimestamp: uint64(block.timestamp),
            lastRenewed: uint64(block.timestamp),
            confirmationPeriod: uint32(period),
            status: uint8(PropertyStatus.LISTED)
        });

        emit ListingEvent(tokenId, msg.sender, price, paymentToken, 0);
    }

    function updateListingBySeller(
        uint256 tokenId,
        uint256 newPrice,
        address newPaymentToken
    ) external whenSystemActive whenFunctionActive(FN_LIST) {
        PropertyListing storage listing = listings[tokenId];
        require(
            newPrice > 0 &&
            allowedPaymentTokens[newPaymentToken] &&
            listing.status == uint8(PropertyStatus.LISTED) &&
            nftiContract.ownerOf(tokenId) == msg.sender,
            ErrorCodes.E001
        );

        // Update seller if ownership changed
        if (listing.seller != msg.sender) {
            listing.seller = msg.sender;
        }

        // Check for active bids if payment token changed (O(1) via counter)
        if (newPaymentToken != listing.paymentToken) {
            require(activeBidsCount[tokenId] == 0, ErrorCodes.E911);
        }

        listing.price = newPrice;
        listing.paymentToken = newPaymentToken;
        listing.lastRenewed = uint64(block.timestamp);

        emit ListingEvent(tokenId, msg.sender, newPrice, newPaymentToken, 1);
    }

    // ========== Purchase Functions ==========

    function purchaseProperty(
        uint256 tokenId,
        uint256 offerPrice
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_PURCHASE) onlyKYCVerified {
        PropertyListing storage listing = listings[tokenId];
        require(
            offerPrice > 0 &&
            listing.status == uint8(PropertyStatus.LISTED),
            ErrorCodes.E001
        );

        uint256 highestBid = BiddingLibrary.getHighestActiveBid(bidsForToken[tokenId]);
        uint256 minimumPrice = highestBid > 0 ? highestBid : listing.price;
        require(
            offerPrice >= minimumPrice &&
            allowedPaymentTokens[listing.paymentToken],
            ErrorCodes.E005
        );

        uint256 actualPrice = highestBid > 0 ? offerPrice : listing.price;

        if (listing.confirmationPeriod > 0) {
            _createPendingPurchase(tokenId, actualPrice, listing.paymentToken, listing.confirmationPeriod);
        } else {
            _completePurchase(tokenId, actualPrice, listing.paymentToken, highestBid > 0);
        }
    }

    function _createPendingPurchase(
        uint256 tokenId,
        uint256 actualPrice,
        address paymentToken,
        uint32 confirmationPeriod
    ) internal {
        PropertyListing storage listing = listings[tokenId];

        IERC20(paymentToken).safeTransferFrom(msg.sender, address(this), actualPrice);

        listing.status = uint8(PropertyStatus.PENDING_SELLER_CONFIRMATION);
        uint64 deadline = uint64(block.timestamp) + confirmationPeriod;

        pendingPurchases[tokenId] = PendingPurchase({
            buyer: msg.sender,
            paymentToken: paymentToken,
            offerPrice: actualPrice,
            tokenId: tokenId,
            purchaseTimestamp: uint64(block.timestamp),
            confirmationDeadline: deadline,
            isActive: true
        });

        emit PurchaseStatusChanged(tokenId, msg.sender, actualPrice, paymentToken, deadline, 0);
    }

    function _completePurchase(
        uint256 tokenId,
        uint256 actualPrice,
        address paymentToken,
        bool wasCompetitive
    ) internal {
        PropertyListing storage listing = listings[tokenId];

        listing.status = uint8(PropertyStatus.SOLD);
        BiddingLibrary.cancelAllBids(bidsForToken[tokenId], bidIndexByBidder, tokenId, refundableBalances, activeBidsCount);

        _processPayment(listing.seller, msg.sender, actualPrice, paymentToken);
        nftiContract.safeTransferFrom(listing.seller, msg.sender, tokenId, "");

        emit PropertySold(tokenId, msg.sender, actualPrice, paymentToken, wasCompetitive);
    }

    function confirmPurchase(uint256 tokenId) external nonReentrant whenSystemActive whenFunctionActive(FN_CONFIRM) {
        _handlePurchaseDecision(tokenId, true);
    }

    function rejectPurchase(uint256 tokenId) external nonReentrant whenSystemActive whenFunctionActive(FN_REJECT) {
        _handlePurchaseDecision(tokenId, false);
    }

    function _handlePurchaseDecision(uint256 tokenId, bool accept) internal {
        PropertyListing storage listing = listings[tokenId];
        PendingPurchase storage purchase = pendingPurchases[tokenId];

        require(
            listing.status == uint8(PropertyStatus.PENDING_SELLER_CONFIRMATION) &&
            purchase.isActive &&
            nftiContract.ownerOf(tokenId) == msg.sender &&
            block.timestamp <= purchase.confirmationDeadline,
            ErrorCodes.E602
        );

        purchase.isActive = false;

        if (accept) {
            listing.status = uint8(PropertyStatus.SOLD);
            BiddingLibrary.cancelAllBids(bidsForToken[tokenId], bidIndexByBidder, tokenId, refundableBalances, activeBidsCount);

            _processPaymentFromBalance(listing.seller, purchase.offerPrice, purchase.paymentToken);
            nftiContract.safeTransferFrom(listing.seller, purchase.buyer, tokenId, "");

            emit PurchaseStatusChanged(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken, 0, 1);
            emit PropertySold(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken, false);
        } else {
            // CEI: effects before interactions (refund)
            listing.status = uint8(PropertyStatus.LISTED);
            IERC20(purchase.paymentToken).safeTransfer(purchase.buyer, purchase.offerPrice);
            emit PurchaseStatusChanged(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken, 0, 2);
        }
    }

    function cancelExpiredPurchase(uint256 tokenId) external nonReentrant whenSystemActive whenFunctionActive(FN_CANCEL_EXPIRED) {
        PropertyListing storage listing = listings[tokenId];
        PendingPurchase storage purchase = pendingPurchases[tokenId];

        require(
            listing.status == uint8(PropertyStatus.PENDING_SELLER_CONFIRMATION) &&
            purchase.isActive &&
            block.timestamp > purchase.confirmationDeadline,
            ErrorCodes.E602
        );

        // CEI: effects before interactions (refund)
        purchase.isActive = false;
        listing.status = uint8(PropertyStatus.LISTED);
        IERC20(purchase.paymentToken).safeTransfer(purchase.buyer, purchase.offerPrice);

        emit PurchaseStatusChanged(tokenId, purchase.buyer, purchase.offerPrice, purchase.paymentToken, 0, 3);
    }

    /**
     * @notice Delist a property from the marketplace
     * @dev Only the current NFT owner can delist. Cancels all active bids.
     * @param tokenId The token ID of the property to delist
     */
    function delistProperty(uint256 tokenId) external nonReentrant whenSystemActive whenFunctionActive(FN_DELIST) {
        PropertyListing storage listing = listings[tokenId];

        require(
            listing.status == uint8(PropertyStatus.LISTED) &&
            nftiContract.ownerOf(tokenId) == msg.sender,
            ErrorCodes.E001
        );

        listing.status = uint8(PropertyStatus.DELISTED);

        // Cancel all active bids and add to refundable balances
        BiddingLibrary.cancelAllBids(bidsForToken[tokenId], bidIndexByBidder, tokenId, refundableBalances, activeBidsCount);

        emit PropertyDelisted(tokenId, msg.sender);
    }

    // Optional: batched bid cancellation to avoid single-tx O(n) with transfers
    function cancelBidsBatch(
        uint256 tokenId,
        uint256 start,
        uint256 count
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_BID) {
        BiddingLibrary.Bid[] storage bids = bidsForToken[tokenId];
        uint256 len = bids.length;
        require(start < len, ErrorCodes.E001);
        uint256 end = start + count;
        if (end > len) end = len;
        for (uint256 i = start; i < end; i++) {
            if (bids[i].isActive) {
                address bidder = bids[i].bidder;
                uint256 refundAmount = bids[i].amount;
                address paymentToken = bids[i].paymentToken;

                bids[i].isActive = false;
                bidIndexByBidder[bidder][tokenId] = 0;
                if (activeBidsCount[tokenId] > 0) {
                    activeBidsCount[tokenId] -= 1;
                }
                refundableBalances[bidder][paymentToken] += refundAmount;
                emit BiddingLibrary.BidCancelled(tokenId, bidder, refundAmount);
            }
        }
    }


    // ========== Bidding Functions ==========

    function placeBid(
        uint256 tokenId,
        uint256 bidAmount,
        address paymentToken
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_BID) onlyKYCVerified {
        PropertyListing storage listing = listings[tokenId];
        require(
            bidAmount > 0 &&
            allowedPaymentTokens[paymentToken] &&
            listing.status == uint8(PropertyStatus.LISTED) &&
            nftiContract.ownerOf(tokenId) != msg.sender,
            ErrorCodes.E001
        );

        uint256 existingIndex = bidIndexByBidder[msg.sender][tokenId];
        require(activeBidsCount[tokenId] < maxActiveBidsPerToken, ErrorCodes.E502);
        BiddingLibrary.placeBid(
            bidsForToken[tokenId],
            bidIndexByBidder,
            tokenId,
            msg.sender,
            bidAmount,
            paymentToken,
            listing.price
        );
        if (existingIndex == 0) {
            activeBidsCount[tokenId] += 1;
        }
    }

    function acceptBid(
        uint256 tokenId,
        uint256 bidIndex,
        address expectedBidder,
        uint256 expectedAmount,
        address expectedPaymentToken
    ) external nonReentrant whenSystemActive whenFunctionActive(FN_ACCEPT_BID) {
        PropertyListing storage listing = listings[tokenId];
        require(
            listing.status == uint8(PropertyStatus.LISTED) &&
            nftiContract.ownerOf(tokenId) == msg.sender &&
            bidIndex > 0 &&
            bidIndex <= bidsForToken[tokenId].length,
            ErrorCodes.E001
        );

        // Update seller if ownership changed
        if (listing.seller != msg.sender) {
            listing.seller = msg.sender;
        }

        BiddingLibrary.Bid storage bid = bidsForToken[tokenId][bidIndex - 1];
        require(
            bid.isActive &&
            bid.bidder == expectedBidder &&
            bid.amount == expectedAmount &&
            bid.paymentToken == expectedPaymentToken,
            ErrorCodes.E501
        );

        listing.status = uint8(PropertyStatus.SOLD);
        if (bid.isActive && activeBidsCount[tokenId] > 0) {
            activeBidsCount[tokenId] -= 1;
        }
        bid.isActive = false;
        bidIndexByBidder[bid.bidder][tokenId] = 0;

        _processPaymentFromBalance(listing.seller, bid.amount, bid.paymentToken);
        nftiContract.safeTransferFrom(listing.seller, bid.bidder, tokenId, "");

        emit PropertySold(tokenId, bid.bidder, bid.amount, bid.paymentToken, true);

        BiddingLibrary.cancelOtherBids(bidsForToken[tokenId], bidIndexByBidder, tokenId, bid.bidder, refundableBalances, activeBidsCount);
    }

    function cancelBid(uint256 tokenId) external nonReentrant whenSystemActive whenFunctionActive(FN_CANCEL_BID) {
        BiddingLibrary.cancelBid(bidsForToken[tokenId], bidIndexByBidder, tokenId, msg.sender, refundableBalances, activeBidsCount);
    }

    // ========== Payment Processing ==========

    function _processPayment(
        address seller,
        address buyer,
        uint256 amount,
        address paymentToken
    ) internal {
        (uint256 baseFee,, address feeCollector) = adminControl.feeConfig();

        PaymentProcessor.processPayment(
            PaymentProcessor.PaymentConfig({
                baseFee: baseFee,
                feeCollector: feeCollector,
                percentageBase: PERCENTAGE_BASE
            }),
            seller,
            buyer,
            amount,
            paymentToken
        );
    }

    function _processPaymentFromBalance(
        address seller,
        uint256 amount,
        address paymentToken
    ) internal {
        (uint256 baseFee,, address feeCollector) = adminControl.feeConfig();

        uint256 fees = (amount * baseFee) / PERCENTAGE_BASE;
        uint256 netValue = amount - fees;

        IERC20 token = IERC20(paymentToken);
        token.safeTransfer(seller, netValue);
        token.safeTransfer(feeCollector, fees);
    }

    // ========== Refund Claims ==========
    function claimRefund(address paymentToken) external nonReentrant {
        uint256 amount = refundableBalances[msg.sender][paymentToken];
        require(amount > 0, ErrorCodes.E001);
        refundableBalances[msg.sender][paymentToken] = 0;
        IERC20(paymentToken).safeTransfer(msg.sender, amount);
        emit RefundClaimed(msg.sender, paymentToken, amount);
    }


    // ========== View Functions ==========

    function getListingDetails(uint256 tokenId)
        external
        view
        returns (
            address seller,


            uint256 price,
            address paymentToken,
            uint8 status,
            uint64 listTimestamp,
            uint32 confirmationPeriod
        )
    {
        PropertyListing storage listing = listings[tokenId];
        return (
            listing.seller,
            listing.price,
            listing.paymentToken,
            listing.status,
            listing.listTimestamp,
            listing.confirmationPeriod
        );
    }

    function getHighestBid(uint256 tokenId) external view returns (uint256) {
        return BiddingLibrary.getHighestActiveBid(bidsForToken[tokenId]);
    }

    // ========== Admin Functions ==========

    function updateListing(
        uint256 tokenId,
        uint256 newPrice,
        address newPaymentToken
    ) external whenSystemActive whenFunctionActive(FN_ADMIN_UPDATE_LISTING) onlyAdmin {
        PropertyListing storage listing = listings[tokenId];
        require(
            listing.status == uint8(PropertyStatus.LISTED) &&
            newPrice > 0 &&
            allowedPaymentTokens[newPaymentToken],
            ErrorCodes.E103
        );

        listing.price = newPrice;

        listing.paymentToken = newPaymentToken;
        listing.lastRenewed = uint64(block.timestamp);

        emit ListingEvent(tokenId, listing.seller, newPrice, newPaymentToken, 1);
    }

    function emergencyWithdrawToken(
        address token,
        uint256 amount,
        address recipient
    ) external onlyGovernance {
        require(token != address(0) && recipient != address(0), ErrorCodes.E915);

        IERC20 tokenContract = IERC20(token);
        require(amount <= tokenContract.balanceOf(address(this)), ErrorCodes.E916);

        tokenContract.safeTransfer(recipient, amount);
        emit EmergencyTokenWithdrawal(token, recipient, amount);
    }

    // ========== Modifiers ==========

    modifier onlyAdmin() {
        require(adminControl.hasRole(adminControl.DEFAULT_ADMIN_ROLE(), msg.sender), ErrorCodes.E401);
        _;
    }

    modifier onlyKYCVerified() {
        require(adminControl.isKYCVerified(msg.sender), ErrorCodes.E403);
        _;
    }

    // Prevent direct ETH transfers
    receive() external payable {
        revert DirectEthTransferNotAllowed();
    }
    // ========== Pause & Governance Modifiers ==========
    modifier whenSystemActive() {
        require(!adminControl.paused(), "Global paused");
        _;
    }

    modifier whenFunctionActive(uint256 functionId) {
        require(!adminControl.functionPaused(functionId), "Function paused");
        _;
    }

    modifier onlyGovernance() {
        require(msg.sender == governanceExecutor, ErrorCodes.E401);
        _;
    }

}

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

/**
 * @title PropertyAuction
 * @notice On-chain English auction for high-ticket real-estate NFTs.
 *         – bids are on-chain but non-custodial (no funds pulled)
 *         – when auction ends, seller escrows the NFT, winner escrows funds
 *         – contract settles atomically (DvP) once both legs are present
 *         – if either side defaults past ESCROW_PERIOD, the other party can void
 */
contract PropertyAuction is
    ReentrancyGuard,
    Pausable,
    Ownable,
    IERC721Receiver
{
    using SafeERC20 for IERC20;

    /* -------------------------------------------------------------------------- */
    /*                                    ERRORS                                  */
    /* -------------------------------------------------------------------------- */

    error InvalidParams();
    error AuctionNotFound();
    error AuctionActive();
    error AuctionNotActive();
    error AuctionExpired();
    error NotSeller();
    error NotWinner();
    error BidTooLow(uint256 required);
    error NFTAlreadyDeposited();
    error FundsAlreadyDeposited();
    error NotSettleable();
    error NotVoidable();
    error BuyNowNotAvailable();
    error BidExceedsBuyNowPrice();
    error AuctionHasBids();
    error CannotWithdrawHighestBid();
    error NotABidder();
    error InvalidBidIndex();

    /* -------------------------------------------------------------------------- */
    /*                                  CONSTANTS                                 */
    /* -------------------------------------------------------------------------- */

    // WARNING: This value is hardcoded into the Auction struct's storage layout.
    // Changing it in future versions will cause storage collisions and break any
    // proxy-based upgrades, leading to critical state corruption.
    // DO NOT CHANGE THIS VALUE.
    uint8 private constant TOP_BIDS_COUNT = 10;

    /// @dev escrow grace period after auction end (seconds). Can be updated by owner.
    uint64 public escrowPeriod = 6 days;

    /* -------------------------------------------------------------------------- */
    /*                                 DATA MODEL                                 */
    /* -------------------------------------------------------------------------- */

    enum AuctionStatus {
        Active,     // Bidding is open or settlement is in progress.
        Settled,    // The auction concluded successfully with an asset swap.
        Voided,     // A party defaulted post-bidding; assets returned.
        Cancelled   // The seller cancelled the auction before any bids were placed.
    }

    struct Bid {
        address bidder;
        uint128 amount;
        uint64 timestamp;
    }

    struct Auction {
        // immutable listing data
        address   seller;
        IERC721   nft;
        uint256   tokenId;
        IERC20    payToken;
        uint128   minBid;
        uint128   buyNowPrice;      // 0 = disabled; kept for completeness
        uint64    biddingEnd;

        // dynamic bidding data
        address   highestBidder;
        uint128   highestBid;
        Bid[TOP_BIDS_COUNT] topBids;

        // escrow phase
        bool      nftDeposited;
        bool      fundsDeposited;

        AuctionStatus status;
    }

    mapping(uint256 => Auction) public auctions;
    uint256 public auctionCount;

    /* -------------------------------------------------------------------------- */
    /*                                    EVENTS                                  */
    /* -------------------------------------------------------------------------- */

    event AuctionCreated(
        uint256 indexed auctionId,
        address indexed seller,
        address indexed nft,
        uint256 tokenId,
        address payToken,
        uint256 minBid,
        uint128 buyNowPrice,
        uint256 biddingEnd
    );

    event BidPlaced(
        uint256 indexed auctionId,
        address indexed bidder,
        uint256 amount
    );

    event BidWithdrawn(uint256 indexed auctionId, address indexed bidder, uint256 amount);

    event NFTDeposited(uint256 indexed auctionId);
    event FundsDeposited(uint256 indexed auctionId);

    event AuctionSettled(
        uint256 indexed auctionId,
        address indexed buyer,
        uint256 amount
    );

    event AuctionCancelled(uint256 indexed auctionId);
    event AuctionVoided(uint256 indexed auctionId);

    event AuctionPurchased(uint256 indexed auctionId, address indexed buyer, uint256 price);

    event AuctionEndedBySeller(uint256 indexed auctionId, address indexed winner, uint256 price);

    event EscrowPeriodUpdated(uint64 oldPeriod, uint64 newPeriod);

    /* -------------------------------------------------------------------------- */
    /*                                   ADMIN                                    */
    /* -------------------------------------------------------------------------- */

    function pause() external onlyOwner { _pause(); }
    function unpause() external onlyOwner { _unpause(); }

    function setEscrowPeriod(uint64 newPeriod) external onlyOwner {
        uint64 old = escrowPeriod;
        escrowPeriod = newPeriod;
        emit EscrowPeriodUpdated(old, newPeriod);
    }

    /* -------------------------------------------------------------------------- */
    /*                                MAIN LOGIC                                  */
    /* -------------------------------------------------------------------------- */

    /**
     * @notice List a property-NFT for auction (NFT stays in wallet for now).
     * @param nft          ERC-721 collection
     * @param tokenId      NFT id
     * @param payToken     ERC-20 used for payment (e.g., USDC)
     * @param minBid       Minimum acceptable first bid (must > 0)
     * @param duration     Auction length in seconds
     */
    function createAuction(
        IERC721 nft,
        uint256 tokenId,
        IERC20  payToken,
        uint128 minBid,
        uint64  duration,
        uint128 buyNowPrice
    ) external whenNotPaused nonReentrant returns (uint256 auctionId) {
        if (
            address(nft) == address(0) ||
            address(payToken) == address(0) ||
            minBid == 0 ||
            duration == 0 ||
            (buyNowPrice != 0 && buyNowPrice <= minBid)
        ) revert InvalidParams();

        unchecked { auctionId = ++auctionCount; }

        auctions[auctionId] = Auction({
            seller: msg.sender,
            nft: nft,
            tokenId: tokenId,
            payToken: payToken,
            minBid: minBid,
            buyNowPrice: buyNowPrice,
            biddingEnd: uint64(block.timestamp) + duration,
            highestBidder: address(0),
            highestBid: 0,
            topBids: [
                Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0),
                Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0), Bid(address(0), 0, 0)
            ],
            nftDeposited: false,
            fundsDeposited: false,
            status: AuctionStatus.Active
        });

        emit AuctionCreated(
            auctionId,
            msg.sender,
            address(nft),
            tokenId,
            address(payToken),
            minBid,
            buyNowPrice,
            uint64(block.timestamp) + duration
        );
    }

    /**
     * @notice Place an on-chain bid (no funds pulled yet).
     * @param auctionId auction id
     * @param amount    bid amount (must beat current by +1)
     */
    function placeBid(uint256 auctionId, uint128 amount)
        external
        whenNotPaused
        nonReentrant
    {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (block.timestamp >= a.biddingEnd) revert AuctionExpired();
        if (a.buyNowPrice > 0 && amount >= a.buyNowPrice) revert BidExceedsBuyNowPrice();

        uint256 required =
            (a.highestBid == 0) ? uint256(a.minBid) : uint256(a.highestBid) + 1;
        if (amount < required) revert BidTooLow(required);

        // Shift existing bids down to make space for the new top bid.
        for (uint8 i = TOP_BIDS_COUNT - 1; i > 0; --i) {
            a.topBids[i] = a.topBids[i - 1];
        }

        // Insert the new highest bid at the top of the array
        a.topBids[0] = Bid({bidder: msg.sender, amount: amount, timestamp: uint64(block.timestamp)});

        // Update the auction's primary winner and bid amount.
        a.highestBidder = msg.sender;
        a.highestBid = amount;

        emit BidPlaced(auctionId, msg.sender, amount);
    }

    /**
     * @notice Withdraw a bid from an auction.
     * @dev Allows any bidder, except the current highest, to withdraw their bid.
     *      This prevents price manipulation (e.g., "bid chilling") by making the
     *      highest bid a firm commitment. It also allows outbid participants to
     *      opt-out of being promoted to winner if the top bidder defaults.
     * @param auctionId The ID of the auction.
     */
    function withdrawBid(uint256 auctionId) external nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (block.timestamp >= a.biddingEnd) revert AuctionExpired();

        // Find the bidder's bid in the top bids
        uint8 bidIndex = TOP_BIDS_COUNT; // Use count as a sentinel for "not found"
        uint128 withdrawnAmount = 0;
        for (uint8 i = 0; i < TOP_BIDS_COUNT; i++) {
            if (a.topBids[i].bidder == msg.sender) {
                bidIndex = i;
                withdrawnAmount = a.topBids[i].amount;
                break;
            }
        }

        if (bidIndex == TOP_BIDS_COUNT) revert NotABidder();
        if (bidIndex == 0) revert CannotWithdrawHighestBid();

        // Remove the bid by shifting lower bids up
        for (uint8 i = bidIndex; i < TOP_BIDS_COUNT - 1; i++) {
            a.topBids[i] = a.topBids[i + 1];
        }
        // Clear the last spot
        delete a.topBids[TOP_BIDS_COUNT - 1];

        emit BidWithdrawn(auctionId, msg.sender, withdrawnAmount);
    }

    /**
     * @notice Purchase the NFT immediately at its "Buy Now" price.
     * @dev This is only possible before any bids are placed.
     *      The buyer's funds are escrowed, and the auction ends. The seller
     *      must then deposit the NFT to trigger settlement.
     * @param auctionId The ID of the auction to purchase.
     */
    function buyNow(uint256 auctionId) external whenNotPaused nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (block.timestamp >= a.biddingEnd) revert AuctionExpired();
        if (a.buyNowPrice == 0) revert BuyNowNotAvailable();
        if (a.highestBid != 0) revert BuyNowNotAvailable();

        // Set winner and price
        a.highestBidder = msg.sender;
        a.highestBid = a.buyNowPrice;

        // End auction
        a.biddingEnd = uint64(block.timestamp);

        // Escrow funds from buyer
        a.fundsDeposited = true;
        a.payToken.safeTransferFrom(msg.sender, address(this), a.buyNowPrice);

        emit AuctionPurchased(auctionId, msg.sender, a.buyNowPrice);
        emit FundsDeposited(auctionId);
    }

    /**
     * @notice Seller can accept a bid to end the auction early.
     * @dev Moves the auction to the settlement phase. The chosen bidder becomes the winner.
     * @param auctionId The ID of the auction.
     * @param bidIndex The index (0-4) of the bid to accept from the top bids list.
     */
    function acceptBid(uint256 auctionId, uint256 bidIndex) external nonReentrant {
        Auction storage a = auctions[auctionId];
        
        // --- Validation ---
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (msg.sender != a.seller) revert NotSeller();
        if (block.timestamp >= a.biddingEnd) revert AuctionExpired();
        if (bidIndex >= TOP_BIDS_COUNT) revert InvalidBidIndex();

        Bid storage acceptedBid = a.topBids[bidIndex];
        if (acceptedBid.bidder == address(0)) revert InvalidBidIndex(); // Cannot accept an empty bid slot

        // --- State Changes ---
        // Set the winner and final price from the accepted bid
        a.highestBidder = acceptedBid.bidder;
        a.highestBid = acceptedBid.amount;

        // End the auction bidding period immediately
        a.biddingEnd = uint64(block.timestamp);

        // --- Events ---
        emit AuctionEndedBySeller(auctionId, a.highestBidder, a.highestBid);
    }

    /* -------------------------------- ESCROW ---------------------------------- */

    /** @notice Seller escrows the NFT **after** auctionEnd. */
    function depositNFT(uint256 auctionId) external nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (msg.sender != a.seller) revert NotSeller();
        if (a.nftDeposited) revert NFTAlreadyDeposited();
        if (block.timestamp < a.biddingEnd) revert AuctionActive();
        if (a.highestBidder == address(0)) revert AuctionExpired(); // no bids

        a.nftDeposited = true;
        a.nft.safeTransferFrom(msg.sender, address(this), a.tokenId);

        emit NFTDeposited(auctionId);
        _trySettle(auctionId);
    }

    /** @notice Winner escrows funds **after** auctionEnd. */
    function depositFunds(uint256 auctionId) external nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (msg.sender != a.highestBidder) revert NotWinner();
        if (a.fundsDeposited) revert FundsAlreadyDeposited();
        if (block.timestamp < a.biddingEnd) revert AuctionActive();

        a.fundsDeposited = true;
        a.payToken.safeTransferFrom(msg.sender, address(this), a.highestBid);

        emit FundsDeposited(auctionId);
        _trySettle(auctionId);
    }

    /** @dev Attempt atomic settlement when both escrow legs are present. */
    function _trySettle(uint256 auctionId) private {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) return;
        if (!a.nftDeposited || !a.fundsDeposited) return;

        // funds → seller
        a.payToken.safeTransfer(a.seller, a.highestBid);
        // NFT → buyer
        a.nft.safeTransferFrom(address(this), a.highestBidder, a.tokenId);

        a.status = AuctionStatus.Settled;
        emit AuctionSettled(auctionId, a.highestBidder, a.highestBid);
    }

    /* --------------------------- DEFAULT / VOID PATH -------------------------- */

    /**
     * @notice After `escrowPeriod`, either party may void if the other leg
     *         has not been deposited. Deposited assets are returned.
     */
    function voidAuction(uint256 auctionId) external nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (block.timestamp < a.biddingEnd + escrowPeriod) revert NotVoidable();

        // Only allow:
        //  – seller to void if buyer hasn't deposited funds
        //  – winner to void if seller hasn't deposited NFT
        if (
            (msg.sender == a.seller        && !a.fundsDeposited) ||
            (msg.sender == a.highestBidder && !a.nftDeposited)
        ) {
            // Return any deposited asset
            if (a.fundsDeposited) {
                a.payToken.safeTransfer(a.highestBidder, a.highestBid);
            }
            if (a.nftDeposited) {
                a.nft.safeTransferFrom(address(this), a.seller, a.tokenId);
            }

            a.status = AuctionStatus.Voided;
            emit AuctionVoided(auctionId);
        } else {
            revert NotVoidable();
        }
    }

    /* -------------------------- EARLY CANCEL (NO BIDS) ------------------------- */

    /** @notice Seller can cancel before the first bid and before endTime. */
    // To protect bidders, an auction becomes a binding commitment once the first bid is placed.
    function cancelAuction(uint256 auctionId) external nonReentrant {
        Auction storage a = auctions[auctionId];
        if (a.status != AuctionStatus.Active) revert AuctionNotActive();
        if (msg.sender != a.seller) revert NotSeller();
        if (a.highestBidder != address(0)) revert AuctionHasBids();
        if (block.timestamp >= a.biddingEnd) revert AuctionExpired();

        a.status = AuctionStatus.Cancelled;
        emit AuctionCancelled(auctionId);
    }

    /* -------------------------------------------------------------------------- */
    /*                              VIEW FUNCTIONS                                */
    /* -------------------------------------------------------------------------- */

    function isSettleable(uint256 auctionId) external view returns (bool) {
        Auction storage a = auctions[auctionId];
        return
            a.status == AuctionStatus.Active &&
            a.nftDeposited &&
            a.fundsDeposited;
    }

    /* -------------------------------------------------------------------------- */
    /*                           ERC-721 RECEIVER HOOK                            */
    /* -------------------------------------------------------------------------- */

    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external pure override returns (bytes4) {
        // Just accept – further checks are done in depositNFT
        return IERC721Receiver.onERC721Received.selector;
    }
}

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

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title DeflationaryToken
 * @dev A mock ERC20 token that charges a transfer fee (deflationary mechanism)
 * Used for testing deflationary token compatibility
 */
contract DeflationaryToken is ERC20, Ownable {
    uint256 public transferFeeRate; // Fee rate in basis points (e.g., 1000 = 10%)
    uint256 public constant MAX_FEE_RATE = 2000; // Maximum 20% fee
    
    event TransferFeeChanged(uint256 oldRate, uint256 newRate);
    event FeeCollected(address indexed from, address indexed to, uint256 amount, uint256 fee);
    
    constructor(
        string memory name,
        string memory symbol,
        uint8 /* decimals */,
        uint256 _transferFeeRate
    ) ERC20(name, symbol) {
        require(_transferFeeRate <= MAX_FEE_RATE, "Fee rate too high");
        transferFeeRate = _transferFeeRate;
        _transferOwnership(msg.sender);
    }
    
    /**
     * @dev Override transfer to implement deflationary mechanism
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transferWithFee(owner, to, amount);
        return true;
    }
    
    /**
     * @dev Override transferFrom to implement deflationary mechanism
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transferWithFee(from, to, amount);
        return true;
    }
    
    /**
     * @dev Internal transfer function with fee deduction
     */
    function _transferWithFee(address from, address to, uint256 amount) internal {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");
        
        uint256 fromBalance = balanceOf(from);
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        
        // Calculate fee
        uint256 fee = (amount * transferFeeRate) / 10000;
        uint256 transferAmount = amount - fee;
        
        // Perform transfers
        _burn(from, amount); // Remove full amount from sender
        _mint(to, transferAmount); // Give net amount to receiver
        
        // Fee is effectively burned (deflationary)
        
        emit FeeCollected(from, to, amount, fee);
    }
    
    /**
     * @dev Mint tokens (only owner)
     */
    function mint(address to, uint256 amount) external onlyOwner {
        _mint(to, amount);
    }
    
    /**
     * @dev Burn tokens (only owner)
     */
    function burn(uint256 amount) external onlyOwner {
        _burn(msg.sender, amount);
    }
    
    /**
     * @dev Set transfer fee rate (only owner)
     */
    function setTransferFeeRate(uint256 _transferFeeRate) external onlyOwner {
        require(_transferFeeRate <= MAX_FEE_RATE, "Fee rate too high");
        uint256 oldRate = transferFeeRate;
        transferFeeRate = _transferFeeRate;
        emit TransferFeeChanged(oldRate, _transferFeeRate);
    }
    
    /**
     * @dev Get effective transfer amount after fee
     */
    function getTransferAmountAfterFee(uint256 amount) external view returns (uint256) {
        uint256 fee = (amount * transferFeeRate) / 10000;
        return amount - fee;
    }
    
    /**
     * @dev Get transfer fee for a given amount
     */
    function getTransferFee(uint256 amount) external view returns (uint256) {
        return (amount * transferFeeRate) / 10000;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/// @title MockERC20
/// @notice Mock ERC20 contract for testing purposes
contract MockERC20 is ERC20, Ownable {
    uint8 private _decimals;
    
    constructor(
        string memory name,
        string memory symbol,
        uint8 decimals_
    ) ERC20(name, symbol) {
        _decimals = decimals_;
    }
    
    /// @notice Mint tokens to a specific address
    /// @param to Address to mint tokens to
    /// @param amount Amount of tokens to mint
    function mint(address to, uint256 amount) external onlyOwner {
        _mint(to, amount);
    }
    
    /// @notice Burn tokens from a specific address
    /// @param from Address to burn tokens from
    /// @param amount Amount of tokens to burn
    function burn(address from, uint256 amount) external onlyOwner {
        _burn(from, amount);
    }
    
    /// @notice Override decimals function
    /// @return Number of decimals
    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }
    
    /// @notice Mint tokens to caller (for testing convenience)
    /// @param amount Amount of tokens to mint
    function mintToSelf(uint256 amount) external {
        _mint(msg.sender, amount);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/// @title MockERC721
/// @notice Mock ERC721 contract for testing purposes
contract MockERC721 is ERC721, Ownable {
    uint256 private _tokenIdCounter;
    
    constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
    
    /// @notice Mint a new token to the specified address
    /// @param to Address to mint the token to
    /// @return tokenId The ID of the minted token
    function mint(address to) external onlyOwner returns (uint256) {
        uint256 tokenId = _tokenIdCounter++;
        _mint(to, tokenId);
        return tokenId;
    }
    
    /// @notice Mint a token with a specific ID
    /// @param to Address to mint the token to
    /// @param tokenId The specific token ID to mint
    function mintWithId(address to, uint256 tokenId) external onlyOwner {
        _mint(to, tokenId);
    }
    
    /// @notice Burn a token
    /// @param tokenId The token ID to burn
    function burn(uint256 tokenId) external {
        address owner = ownerOf(tokenId);
        require(
            msg.sender == owner ||
            isApprovedForAll(owner, msg.sender) ||
            getApproved(tokenId) == msg.sender,
            "Not approved or owner"
        );
        _burn(tokenId);
    }

    /// @notice Get the current token counter
    /// @return The next token ID that will be minted
    function getCurrentTokenId() external view returns (uint256) {
        return _tokenIdCounter;
    }
    
    /// @notice Check if a token exists
    /// @param tokenId The token ID to check
    /// @return True if the token exists
    function exists(uint256 tokenId) external view returns (bool) {
        // In OZ v5, internal helpers changed; use try/catch on ownerOf for a simple existence check
        try this.ownerOf(tokenId) returns (address owner) {
            return owner != address(0);
        } catch {
            return false;
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IAdminControl} from "../interfaces/IAdminControl.sol";
import {IManageLifePropertyNFTController} from "../interfaces/IManageLifePropertyNFTController.sol";

/// @title ManageLife Property NFT
/// @notice ERC-721 for ManageLife property tokens, minted and managed via an external controller.
/// @dev
/// - Minting and deed state updates are restricted to `propertyControllerContract`.
/// - Administrative wiring (admin/controller addresses, base URI) is restricted to `DEFAULT_ADMIN_ROLE` via `IAdminControl`.
/// - LLC/legal property information MUST live in the off-chain NFT metadata (e.g., tokenURI JSON), not on-chain:
///   - to minimize gas/storage costs
///   - and because such information is authored by the platform, not by end-users.
contract ManageLifePropertyNFT is ERC721 {
    using Strings for uint256;
    /// @dev Sequential token ID counter. Incremented on each mint.
    uint256 private _tokenIdCounter;

    /// @dev Normalized base URI (always ends with a single '/').
    string private _baseTokenURI;

    /// @notice The system’s admin control contract.
    IAdminControl public adminController;

    /// @notice Contract allowed to mint and update deed state.
    address public propertyControllerContract;

    /// @notice Whether the deed for a given tokenId is held at ManageLife.
    /// @dev Updated only by `propertyControllerContract`.
    mapping(uint256 => bool) public deedHeldAtManageLife;

    /// @notice Emitted when the base token URI is updated.
    /// @param baseTokenURI The new base URI
    event BaseTokenURISet(string indexed baseTokenURI);

    /// @notice Emitted when the admin control contract is updated.
    /// @param oldAdminContract Previous admin controller address
    /// @param newAdminContract New admin controller address
    event AdminContractUpdated(address oldAdminContract, address newAdminContract);

    /// @notice Emitted when the property controller contract is updated.
    /// @param oldController Previous controller address
    /// @param newController New controller address
    event ControllerContractUpdated(address oldController, address newController);

    /// @notice Emitted when the deed-held flag is updated for a token.
    /// @param tokenId Token ID whose deed-held flag was updated.
    /// @param deedHeldAtManageLife New deed-held flag value.
    event DeedHeldAtManageLifeUpdated(uint256 indexed tokenId, bool deedHeldAtManageLife);

    /// @dev Revert when a zero address is provided where non-zero is required.
    error ZeroAddress();

    /// @dev Revert when caller lacks `DEFAULT_ADMIN_ROLE`.
    error NotAdmin();

    /// @dev Revert when caller is not the configured `propertyControllerContract`.
    error NotController();

    /// @dev Revert when an empty base URI is provided.
    error EmptyMetadataURI();

    /// @notice Restricts caller to `DEFAULT_ADMIN_ROLE` from `adminController`.
    modifier onlyAdmin() {
        if (!adminController.hasRole(adminController.DEFAULT_ADMIN_ROLE(), msg.sender)) {
            revert NotAdmin();
        }
        _;
    }

    /// @notice Restricts caller to the configured `propertyControllerContract`.
    modifier onlyController() {
        if (propertyControllerContract != msg.sender) {
            revert NotController();
        }
        _;
    }

    /// @notice Deploys the collection with admin/controller wiring and an initial base URI.
    /// @dev `_baseUri` is normalized to a single trailing '/'.
    /// @param name ERC-721 name.
    /// @param symbol ERC-721 symbol.
    /// @param adminControlAddress Protocol's `IAdminControl` contract.
    /// @param _baseUri Base URI for token metadata (directory-like, with or without trailing slash).
    /// @param _controllerContract Address of the property controller authorized to mint and update deed state.
    constructor(
        string memory name,
        string memory symbol,
        IAdminControl adminControlAddress,
        string memory _baseUri,
        address _controllerContract
    ) ERC721(name, symbol) {
        if (bytes(_baseUri).length == 0) revert EmptyMetadataURI();
        if (address(adminControlAddress) == address(0)) revert ZeroAddress();
        if (_controllerContract == address(0)) revert ZeroAddress();
        adminController = adminControlAddress;
        propertyControllerContract = _controllerContract;
        _baseTokenURI = _normalizeBaseUri(_baseUri);
    }

    /// @notice Mints a new token to `to` and sets its deed-held flag.
    /// @dev Callable only by `propertyControllerContract`.
    /// @param to Recipient of the newly minted token.
    /// @param _deedHeldAtManageLife Whether the deed is held at ManageLife for the new property token.
    /// @return newTokenId The ID of the minted token.
    function mintPropertyNFT(address to, bool _deedHeldAtManageLife)
        external
        onlyController
        returns (uint256 newTokenId)
    {
        newTokenId = ++_tokenIdCounter;
        deedHeldAtManageLife[newTokenId] = _deedHeldAtManageLife;
        _safeMint(to, newTokenId);
    }

    /// @notice Updates the deed-held flag for a token.
    /// @dev Callable only by `propertyControllerContract`. Reverts if token does not exist.
    /// @param tokenId Token ID whose deed-held flag will be updated.
    /// @param _deedHeldAtManageLife New deed-held flag value.
    function setDeedHeldAtManageLife(uint256 tokenId, bool _deedHeldAtManageLife) external onlyController {
        require(_ownerOf(tokenId) != address(0), "Token does not exist");
        deedHeldAtManageLife[tokenId] = _deedHeldAtManageLife;
        emit DeedHeldAtManageLifeUpdated(tokenId, _deedHeldAtManageLife);
    }

    /// @notice Returns the token metadata URI for `tokenId` as base + tokenId + ".json".
    /// @dev Reverts if token does not exist.
    /// @param tokenId Token ID for the metadata lookup.
    /// @return uri Fully qualified token metadata URI.
    function tokenURI(uint256 tokenId) public view override returns (string memory uri) {
        require(_ownerOf(tokenId) != address(0), "Token does not exist");
        uri = string(abi.encodePacked(_baseTokenURI, tokenId.toString(), ".json"));
    }

    /// @notice Returns the current base token URI (normalized to a single trailing slash).
    function baseTokenURI() external view returns (string memory) {
        return _baseTokenURI;
    }

    /// @notice Sets the property controller contract address.
    /// @dev Only `DEFAULT_ADMIN_ROLE`. Reverts on zero address.
    /// @param newPropertyController The new controller address.
    function setPropertyControllerContract(address newPropertyController) external onlyAdmin {
        if (newPropertyController == address(0)) revert ZeroAddress();
        // Enforce controller <-> NFT mutual wiring and admin consistency
        IManageLifePropertyNFTController ctrl = IManageLifePropertyNFTController(newPropertyController);
        require(address(ctrl.manageLifePropertiesNftContract()) == address(this), "CTRL->NFT mismatch");
        require(address(ctrl.adminController()) == address(adminController), "CTRL admin mismatch");
        address oldPropertyController = propertyControllerContract;
        propertyControllerContract = newPropertyController;
        emit ControllerContractUpdated(oldPropertyController, newPropertyController);
    }

    /// @notice Sets the admin controller contract address.
    /// @dev Only `DEFAULT_ADMIN_ROLE`. Reverts on zero address.
    /// @param newAdminController The new admin controller address.
    function setAdminController(address newAdminController) external onlyAdmin {
        if (newAdminController == address(0)) revert ZeroAddress();
        // If a controller is set, require it uses the same AdminControl for consistency
        if (propertyControllerContract != address(0)) {
            require(
                address(IManageLifePropertyNFTController(propertyControllerContract).adminController())
                    == newAdminController,
                "CTRL admin mismatch"
            );
        }
        address oldAdminController = address(adminController);
        adminController = IAdminControl(newAdminController);
        emit AdminContractUpdated(oldAdminController, newAdminController);
    }

    /// @notice Updates the base token URI. Accepts inputs with or without trailing slashes.
    /// @dev Only `DEFAULT_ADMIN_ROLE`. Normalized to exactly one trailing '/' before storage.
    /// @param _baseUri New base URI string.
    function setBaseTokenURI(string memory _baseUri) external onlyAdmin {
        if (bytes(_baseUri).length == 0) revert EmptyMetadataURI();
        _baseTokenURI = _normalizeBaseUri(_baseUri);
        emit BaseTokenURISet(_baseTokenURI);
    }

    /// @dev Normalizes an input URI to exactly one trailing '/'.
    /// @param s Input URI (may have zero or multiple trailing slashes).
    /// @return normalized Normalized URI with exactly one trailing '/'.
    function _normalizeBaseUri(string memory s) internal pure returns (string memory normalized) {
        bytes memory b = bytes(s);
        if (b.length == 0) return s;

        uint256 end = b.length;
        while (end > 0 && b[end - 1] == bytes1("/")) {
            unchecked {
                end--;
            }
        }

        if (end == 0) return "/";

        bytes memory trimmed = new bytes(end);
        for (uint256 i = 0; i < end; i++) {
            trimmed[i] = b[i];
        }
        normalized = string(abi.encodePacked(trimmed, "/"));
    }

    /// @notice Total number of tokens minted so far.
    /// @dev This counts minted tokens and does not decrement on burn (if ever added).
    /// @return supply The current mint counter.
    function totalSupply() public view returns (uint256 supply) {
        supply = _tokenIdCounter;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import {IAdminControl} from "../interfaces/IAdminControl.sol";
import {IManageLifePropertyNFT} from "../interfaces/IManageLifePropertyNFT.sol";

/// @title ManageLifePropertyNFTController
/// @author Jose Herrera
/// @notice This contract is responsible for controlling the minting process of ManageLifePropertyNFTs.
/// It acts as a layer between the admin/managers and the NFT contract itself, enforcing specific roles for minting.
contract ManageLifePropertyNFTController{
    // ============ Immutable/State ============
    /// @notice The address of the AdminControl contract.
    IAdminControl public adminController;
    /// @notice The address of the ManageLifePropertyNFT contract that this controller manages.
    IManageLifePropertyNFT public manageLifePropertiesNftContract;
    /// @notice The maximum number of NFTs that can be minted in a single batch transaction.
    uint256 public immutable MAX_BATCH_SIZE = 25;

    // ============ Events ============
    /// @notice Emitted when a new property NFT is minted.
    /// @param to The address receiving the new NFT.
    /// @param tokenId The ID of the newly minted token.
    /// @param caller The address that initiated the minting.
    event PropertyMinted(address indexed to, uint256 tokenId, address indexed caller);
    /// @notice Emitted when the ManageLifePropertyNFT contract address is updated.
    /// @param newPropertyNFTContract The address of the new NFT contract.
    event ManageLifePropertyNFTContractUpdated(address oldPropertyNFTContract, address newPropertyNFTContract);
    /// @notice Emitted when the AdminControl contract address is updated.
    /// @param newAdminController The address of the new admin controller.
    event AdminControllerUpdated(address oldAdminController, address newAdminController);

    // ============ Errors ============
    /// @notice Thrown when a function is called with a zero address parameter where it is not allowed.
    error ZeroAddress();
    /// @notice Thrown when a function is called by an address that does not have the NFT_PROPERTY_MANAGER_ROLE.
    error NotNftPropertyManager();
    /// @notice Thrown when a function is called by an address that is not a default admin.
    error NotAdmin();
    /// @notice Thrown when a batch minting operation exceeds the maximum allowed batch size.
    /// @param batchSize The requested batch size.
    /// @param maxBatchSize The maximum allowed batch size.
    error InvalidBatchSize(uint256 batchSize, uint256 maxBatchSize);
    /// @notice Thrown when the input arrays for a batch operation do not have the same length.
    error InvalidBatchDataInputs();
    
    /// @notice Thrown when trying to set a new NFT contract that points to a different controller, when it should be this contract.
    /// @param controllerOnNftContract The controller address on the new NFT contract.
    error newNFTContractHasDifferentController(address controllerOnNftContract);
    /// @notice Thrown when trying to set a new NFT contract that points to a different admin controller.
    /// @param adminControllerOnNftContract The admin controller address on the new NFT contract.
    /// @param currentAdminController The address of the current admin controller in this contract.
    error newNFTContractHasDifferentAdminController(address adminControllerOnNftContract, address currentAdminController);

    // ============ Constructor ============
    /// @notice Initializes the controller with the addresses of the AdminControl and ManageLifePropertyNFT contracts.
    /// @param _adminControlAddress The address of the AdminControl contract.
    /// @param _manageLifePropertiesNftContract The address of the ManageLifePropertyNFT contract.
    constructor(IAdminControl _adminControlAddress, IManageLifePropertyNFT _manageLifePropertiesNftContract) {
        if (address(_adminControlAddress) == address(0)) {
            revert ZeroAddress();
        }
        if (address(_manageLifePropertiesNftContract) == address(0)) {
            revert ZeroAddress();
        }
        adminController = _adminControlAddress;

        _checkNftContractConnections(_manageLifePropertiesNftContract);

        manageLifePropertiesNftContract = _manageLifePropertiesNftContract;
    }

    // ============ Modifiers ============
    /// @notice Modifier to restrict function access to default admins only.
    modifier onlyAdmin() {
        if (!adminController.hasRole(adminController.DEFAULT_ADMIN_ROLE(), msg.sender)) {
            revert NotAdmin();
        }
        _;
    }
    
    /// @notice Modifier to restrict function access to NFT Property Managers only.
    modifier onlyNftPropertyManager() {
        if (!adminController.hasRole(adminController.NFT_PROPERTY_MANAGER_ROLE(), msg.sender)) {
            revert NotNftPropertyManager();
        }
        _;
    }

    // ============ Admin Functions ============
    /// @notice Updates the AdminControl contract address.
    /// @dev This function can only be called by a default admin.
    /// @param newController The new AdminControl contract instance.
    function setAdminController(IAdminControl newController) external onlyAdmin {
        if (address(newController) == address(0)) {
            revert ZeroAddress();
        }
        address oldAdminController = address(adminController);
        adminController = IAdminControl(newController);
        emit AdminControllerUpdated(oldAdminController,address(newController));
    }

    /// @notice Sets the `deedHeldAtManageLife` status for a specific property NFT.
    /// @dev This can only be called by an address with the NFT_PROPERTY_MANAGER_ROLE.
    /// @param tokenId The ID of the token to update.
    /// @param deedHeldAtManageLife The new boolean status.
    function setDeedHeldAtManageLife(uint256 tokenId, bool deedHeldAtManageLife) external onlyNftPropertyManager {
        manageLifePropertiesNftContract.setDeedHeldAtManageLife(tokenId, deedHeldAtManageLife);
    }

    /// @notice Updates the ManageLifePropertyNFT contract address.
    /// @dev This function can only be called by a default admin.
    /// The new NFT contract must have this contract as its controller and the same admin controller.
    /// @param newPropertyNFTContract The new ManageLifePropertyNFT contract instance.
    function setManageLifePropertyNFTContract(IManageLifePropertyNFT newPropertyNFTContract) external onlyAdmin {
        if (address(newPropertyNFTContract) == address(0)) {
            revert ZeroAddress();
        }
        _checkNftContractConnections(newPropertyNFTContract);

        address oldPropertyNFTContract = address(manageLifePropertiesNftContract);
        manageLifePropertiesNftContract = newPropertyNFTContract;
        emit ManageLifePropertyNFTContractUpdated(oldPropertyNFTContract, address(newPropertyNFTContract));
    }

    // ============ Minting ============
    /// @notice Mints a new property NFT and assigns it to a specified address.
    /// @dev Can only be called by an address with the NFT_PROPERTY_MANAGER_ROLE.
    /// @param to The address to mint the new NFT to.
    /// @param deedHeldAtManageLife A boolean indicating if the deed is held by ManageLife.
    /// @return tokenId The ID of the newly minted token.
    function mint(address to, bool deedHeldAtManageLife) external onlyNftPropertyManager returns (uint256) {
        uint256 tokenId = manageLifePropertiesNftContract.mintPropertyNFT(to, deedHeldAtManageLife);
        emit PropertyMinted(to, tokenId, msg.sender);
        return tokenId;
    }

    /// @notice Mints a batch of new property NFTs to specified addresses.
    /// @dev Can only be called by an address with the NFT_PROPERTY_MANAGER_ROLE.
    /// The length of `recipients` and `deedHeldAtManageLife` arrays must be equal.
    /// Batch size is limited by `MAX_BATCH_SIZE`.
    /// @param recipients An array of addresses to mint the new NFTs to.
    /// @param deedHeldAtManageLife An array of booleans indicating if the deeds are held by ManageLife.
    /// @return tokenIds An array of the newly minted token IDs.
    function mintBatch(address[] calldata recipients, bool[] calldata deedHeldAtManageLife) external onlyNftPropertyManager returns (uint256[] memory) {
 
        if (recipients.length > MAX_BATCH_SIZE) {
            revert InvalidBatchSize(recipients.length, MAX_BATCH_SIZE);
        }
        if(recipients.length != deedHeldAtManageLife.length) {
            revert InvalidBatchDataInputs();
        }
        uint256 length = recipients.length;
        uint256[] memory tokenIds = new uint256[](length);
        for (uint256 i = 0; i < length; ) {
            tokenIds[i] = manageLifePropertiesNftContract.mintPropertyNFT(recipients[i], deedHeldAtManageLife[i]);
            emit PropertyMinted(recipients[i], tokenIds[i], msg.sender);
            unchecked { ++i; }
        }
        return tokenIds;
    }


    /// @dev Checks that the new NFT contract is correctly wired to this controller and the correct admin controller.
    /// Reverts if the NFT contract's controller or admin controller do not match expectations.
    /// @param newPropertyNFTContract The new ManageLifePropertyNFT contract to check.
    function _checkNftContractConnections(IManageLifePropertyNFT newPropertyNFTContract) internal view {
        // Ensure the NFT contract's controller is this contract.
        if (newPropertyNFTContract.propertyControllerContract() != address(this)) {
            revert newNFTContractHasDifferentController(newPropertyNFTContract.propertyControllerContract());
        }
        // Ensure the NFT contract's admin controller matches this controller's admin controller.
        address adminControllerOnNftContract = address(newPropertyNFTContract.adminController());
        if (adminControllerOnNftContract != address(adminController)) {
            revert newNFTContractHasDifferentAdminController(adminControllerOnNftContract, address(adminController));
        }
    }

}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../../libraries/StakingConstants.sol";

// Admin control interface
interface IAdminControl {
    function getCommunityScore(address user) external view returns (uint256);
}

/// @title BaseRewards - Basic staking and reward distribution contract
/// @notice Implements a staking mechanism where users can stake tokens and earn rewards
/// @dev Inherits from Ownable for access control and ReentrancyGuard for security
contract BaseRewards is Ownable, ReentrancyGuard {
    uint256 public constant MIN_STAKING_PERIOD = StakingConstants.MIN_STAKING_PERIOD;
    uint256 public constant BASIS_POINTS = 10000;
    uint256 public constant MAX_STAKING_DAYS = 3650; // 10 years
    uint256 public constant MAX_REWARD_AMOUNT = 1e30; // Maximum reward cap
    
    // Decimal handling
    uint256 public immutable stakingTokenUnit;
    uint256 public immutable rewardsTokenUnit;
    
    ERC20 public immutable stakingToken;
    ERC20 public immutable rewardsToken;
    
    IAdminControl public adminControl;
    
    // Reward configuration
    struct RewardConfig {
        uint256 baseRewardRate;
        uint256 communityBonusRate;
        uint256 leaseBonusRate;
    }
    
    RewardConfig public rewardConfig;

    // Reward rate parameters
    struct RewardPeriod {
        uint256 rate;
        uint256 startTime;
        uint256 endTime;
    }
    
    RewardPeriod[] public rewardPeriods;
    uint256 public rewardPerTokenStored;
    uint256 public lastUpdateTime;

    // User configurations
    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;
    mapping(address => uint256) public rewardExpirationTimestamps;
    uint256 public constant MAX_CLAIM_PERIOD = 30 days;
    uint256 public constant MAX_REWARD_RATE = 1e20; // 100 tokens per second per staked token
    uint256 public constant MAX_PERIODS_PROCESSED = 100; // Maximum periods processed per call
    uint256 public constant RATE_CHANGE_COOLDOWN = 1 days;
    uint256 public lastRateChange;
    bool public rateChangePaused;
    event RewardExpired(address indexed user, uint256 amount);

    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;
    mapping(address => uint256) private _stakeTimestamps;
    mapping(address => uint256) private _snapshotBalances;
    uint256 public minStakingPeriod = MIN_STAKING_PERIOD;
    event MinStakingPeriodUpdated(uint256 newPeriod);

    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);
    event RewardRateUpdated(uint256 oldRate, uint256 newRate, address indexed admin);
    event TokensRescued(address indexed token, uint256 amount, address indexed admin);

    constructor(
        address _stakingToken,
        address _rewardsToken,
        address initialOwner
    ) Ownable() {
        require(_stakingToken != address(0), "Invalid staking token address");
        require(_rewardsToken != address(0), "Invalid rewards token address");
        
        stakingToken = ERC20(_stakingToken);
        rewardsToken = ERC20(_rewardsToken);
    
        // Initialize immutable variables directly in constructor without using try/catch
        uint256 _stakingTokenUnit;
        uint256 _rewardsTokenUnit;
        
        // Get token decimals using temporary variables
        try stakingToken.decimals() returns (uint8 decimals) {
            _stakingTokenUnit = 10 ** uint256(decimals);
        } catch {
            _stakingTokenUnit = 1e18;
        }
        
        try rewardsToken.decimals() returns (uint8 decimals) {
            _rewardsTokenUnit = 10 ** uint256(decimals);
        } catch {
            _rewardsTokenUnit = 1e18;
        }
        
        // Initialize immutable variables using temporary values
        stakingTokenUnit = _stakingTokenUnit;
        rewardsTokenUnit = _rewardsTokenUnit;
        
        // Transfer ownership
        if (initialOwner != address(0) && initialOwner != msg.sender) {
            _transferOwnership(initialOwner);
        }
    }

    /******************** Core Functions ********************/
    /// @notice Allows users to stake tokens
    /// @dev Updates rewards before processing stake
    /// @param amount Amount of tokens to stake
    function stake(uint256 amount) external nonReentrant updateReward(msg.sender) {
        require(amount > 0, "Cannot stake 0");
        
        // Check if rewards pool has sufficient tokens
        require(rewardsToken.balanceOf(address(this)) > 0, "Rewards pool is empty");
        
        // Transfer tokens first to ensure the transaction succeeds before updating state
        uint256 balanceBefore = stakingToken.balanceOf(address(this));
        require(stakingToken.transferFrom(msg.sender, address(this), amount), "Token transfer failed");
        uint256 balanceAfter = stakingToken.balanceOf(address(this));
        
        // Verify the actual amount received
        uint256 amountReceived = balanceAfter - balanceBefore;
        require(amountReceived == amount, "Incorrect amount received");
        
        // Update state variables
        _totalSupply = _totalSupply + amountReceived;
        _balances[msg.sender] = _balances[msg.sender] + amountReceived;
        _stakeTimestamps[msg.sender] = block.timestamp;
        
        emit Staked(msg.sender, amountReceived);
    }

    /// @notice Allows users to withdraw their staked tokens
    /// @dev Updates rewards before processing withdrawal
    /// @param amount Amount of tokens to withdraw
    function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) {
        require(block.timestamp >= _stakeTimestamps[msg.sender] + minStakingPeriod, "Minimum staking period not met");
        require(amount > 0, "Cannot withdraw 0");
        // Explicit balance check using SafeMath
        uint256 currentBalance = _balances[msg.sender];
        require(currentBalance >= amount, "Insufficient staked balance");
        
        // Native subtraction with automatic underflow protection in Solidity 0.8.20
        _balances[msg.sender] = currentBalance - amount;
        _totalSupply = _totalSupply - amount;
        
        // Maintain checks-effects-interactions pattern
        require(stakingToken.transfer(msg.sender, amount), "Token transfer failed");
        emit Withdrawn(msg.sender, amount);
    }

    /// @notice Allows users to claim their accumulated rewards
    /// @dev Updates rewards before processing claim
    function claimReward() public nonReentrant updateReward(msg.sender) {
        require(block.timestamp <= rewardExpirationTimestamps[msg.sender], "Reward claim period expired");
        uint256 reward = rewards[msg.sender];
        if (reward > 0) {
            rewards[msg.sender] = 0;
            require(rewardsToken.balanceOf(address(this)) >= reward, "Insufficient reward token balance");
            require(rewardsToken.transfer(msg.sender, reward), "Reward transfer failed");
            emit RewardPaid(msg.sender, reward);
        }
    }

    function clearExpiredRewards(address account) external nonReentrant {
        require(block.timestamp > rewardExpirationTimestamps[account], "Reward not expired");
        uint256 expiredAmount = rewards[account];
        rewards[account] = 0;
        emit RewardExpired(account, expiredAmount);
    }

    function setMinStakingPeriod(uint256 period) external onlyOwner {
        minStakingPeriod = period;
        emit MinStakingPeriodUpdated(period);
    }

    /******************** Management Functions ********************/
    /// @notice Sets the reward rate for the staking contract
    /// @dev Only callable by contract owner
    /// @param _rewardRate New reward rate per second
    function setRewardRate(uint256 _rewardRate) external onlyOwner updateReward(address(0)) {
        require(!rateChangePaused, "Circuit breaker active: rate changes paused");
        require(_rewardRate <= MAX_REWARD_RATE, "Reward rate exceeds maximum");
        require(block.timestamp >= lastRateChange + RATE_CHANGE_COOLDOWN, "Rate change cooldown active");
        
        uint256 oldRate = rewardPeriods.length > 0 ? rewardPeriods[rewardPeriods.length - 1].rate : 0;
        
        if (rewardPeriods.length > 0) {
            RewardPeriod storage lastPeriod = rewardPeriods[rewardPeriods.length - 1];
            if (lastPeriod.endTime > block.timestamp) {
                lastPeriod.endTime = block.timestamp;
            }
        }
        
        rewardPeriods.push(RewardPeriod({
            rate: _rewardRate,
            startTime: block.timestamp,
            endTime: type(uint256).max
        }));
        
        lastRateChange = block.timestamp;
        emit RewardRateUpdated(oldRate, _rewardRate, msg.sender);
    }

    function pauseRateChanges() external onlyOwner {
        rateChangePaused = true;
    }

    function unpauseRateChanges() external onlyOwner {
        rateChangePaused = false;
    }

    function rescueTokens(address token, uint256 amount) external onlyOwner {
        require(token != address(stakingToken), "Cannot rescue staking token");
        require(ERC20(token).transfer(msg.sender, amount), "Token transfer failed");
        emit TokensRescued(token, amount, msg.sender);
    }

    /******************** View Functions ********************/
    /// @notice Returns the total amount of tokens staked
    /// @return Total staked token amount
    function totalSupply() external view returns (uint256) {
        return _totalSupply;
    }

    /// @notice Returns the amount of tokens staked by a specific account
    /// @param account Address to check
    /// @return Staked token amount for the account
    function balanceOf(address account) external view returns (uint256) {
        return _balances[account];
    }

    /// @notice Calculates the current reward amount earned by an account
    /// @param account Address of the account to check
    /// @return Amount of rewards earned
    function earned(address account) public view returns (uint256) {
        return
            _snapshotBalances[account]
                * (rewardPerToken() - userRewardPerTokenPaid[account])
                / stakingTokenUnit
                 + rewards[account];
    }

    /// @notice Calculates the current reward per token stored
    /// @dev Used for reward distribution calculations
    /// @return Current reward per token rate
    function rewardPerToken() public view returns (uint256) {
        if (_totalSupply == 0 || lastUpdateTime == 0) {
            return rewardPerTokenStored;
        }
        
        uint256 totalAdditionalReward = 0;
        uint256 periodsLength = rewardPeriods.length;
        uint256 processedPeriods = 0;
        for (uint256 i = 0; i < periodsLength; i++) {
            RewardPeriod memory period = rewardPeriods[i];
            uint256 periodEndTime = period.endTime;
            uint256 periodStartTime = period.startTime;
            
            if (periodEndTime > lastUpdateTime) {
                uint256 periodStart = periodStartTime > lastUpdateTime ? periodStartTime : lastUpdateTime;
                uint256 periodEnd = periodEndTime < block.timestamp ? periodEndTime : block.timestamp;
                
                if (periodEnd > periodStart) {
                    uint256 periodDuration = periodEnd - periodStart;
                    uint256 periodRate = period.rate;
                    
                    totalAdditionalReward = totalAdditionalReward + (
                        periodRate * periodDuration * rewardsTokenUnit / _totalSupply
                    );
                    
                    if (++processedPeriods >= MAX_PERIODS_PROCESSED) {
                        break;
                    }
                }
            }
        }
        return rewardPerTokenStored + totalAdditionalReward;
    }

    /// @notice Calculates rewards for a user based on their staking and community participation
    /// @dev Uses safe math operations to prevent overflow and optimized calculations
    /// @param user The address of the user
    /// @param stakingAmount The amount of tokens staked by the user
    /// @param stakingDuration The duration of staking in seconds
    /// @return totalReward The total calculated reward amount
    function calculateRewards(
        address user,
        uint256 stakingAmount,
        uint256 stakingDuration
    ) external view returns (uint256 totalReward) {
        require(user != address(0), "Invalid user address");
        require(stakingAmount > 0, "Invalid staking amount");
        require(stakingDuration > 0, "Invalid staking duration");
        
        // Get base reward rate with overflow protection
        uint256 baseRate = rewardConfig.baseRewardRate;
        require(baseRate > 0, "Base reward rate not set");
        
        // Calculate base reward with overflow checks
        // Use intermediate calculations to prevent overflow
        uint256 timeMultiplier = stakingDuration / 1 days; // Convert to days
        require(timeMultiplier <= MAX_STAKING_DAYS, "Staking duration too long");
        
        // Enhanced safe multiplication with SafeMath and overflow protection
        uint256 baseReward;

        // Use SafeMath for all calculations to ensure maximum safety
        try this._safeCalculateBaseReward(stakingAmount, baseRate, timeMultiplier) returns (uint256 result) {
            baseReward = result;
        } catch {
            revert("Base reward calculation overflow");
        }
        
        // Get community bonus with safe calculations
        uint256 communityBonus = _calculateCommunityBonus(user, baseReward);
        
        // Get lease bonus with safe calculations
        uint256 leaseBonus = _calculateLeaseBonus(user, baseReward);
        
        // Safe addition with overflow check
        totalReward = baseReward;
        if (totalReward > type(uint256).max - communityBonus) {
            revert("Total reward calculation overflow");
        }
        totalReward += communityBonus;
        
        if (totalReward > type(uint256).max - leaseBonus) {
            revert("Total reward calculation overflow");
        }
        totalReward += leaseBonus;
        
        // Apply maximum reward cap
        if (totalReward > MAX_REWARD_AMOUNT) {
            totalReward = MAX_REWARD_AMOUNT;
        }
        
        return totalReward;
    }

    /// @notice Safe calculation helper for base rewards (external for try-catch)
    /// @dev Uses SafeMath for enhanced overflow protection
    /// @param stakingAmount The staking amount
    /// @param baseRate The base reward rate
    /// @param timeMultiplier The time multiplier
    /// @return result The calculated base reward
    function _safeCalculateBaseReward(uint256 stakingAmount, uint256 baseRate, uint256 timeMultiplier) external pure returns (uint256 result) {
        // Double-check inputs
        require(stakingAmount > 0, "Invalid staking amount");
        require(baseRate > 0, "Invalid base rate");
        require(timeMultiplier > 0, "Invalid time multiplier");

        // Use native checked arithmetic (Solidity 0.8+)
        uint256 intermediate = stakingAmount * baseRate;
        result = (intermediate * timeMultiplier) / BASIS_POINTS;

        // Additional sanity check
        require(result <= MAX_REWARD_AMOUNT, "Result exceeds maximum reward");

        return result;
    }

    /// @notice Calculates community participation bonus
    /// @dev Internal function with optimized calculations
    /// @param user The user address
    /// @param baseReward The base reward amount
    /// @return bonus The calculated community bonus
    function _calculateCommunityBonus(address user, uint256 baseReward) internal view returns (uint256 bonus) {
        uint256 communityScore = adminControl.getCommunityScore(user);
        if (communityScore == 0) {
            return 0;
        }
        
        uint256 bonusRate = rewardConfig.communityBonusRate;
        if (bonusRate == 0) {
            return 0;
        }
        
        // Safe calculation with overflow protection
        unchecked {
            if (baseReward > type(uint256).max / bonusRate) {
                return MAX_REWARD_AMOUNT; // Cap at maximum
            }
            bonus = (baseReward * bonusRate * communityScore) / (BASIS_POINTS * 100);
        }
        
        return bonus;
    }
    
    /// @notice Calculates lease participation bonus
    /// @dev Internal function with optimized calculations
    /// @param user The user address
    /// @param baseReward The base reward amount
    /// @return bonus The calculated lease bonus
    function _calculateLeaseBonus(address user, uint256 baseReward) internal view returns (uint256 bonus) {
        // Check if user has active leases (simplified check)
        bool hasActiveLeases = _hasActiveLeases(user);
        if (!hasActiveLeases) {
            return 0;
        }
        
        uint256 bonusRate = rewardConfig.leaseBonusRate;
        if (bonusRate == 0) {
            return 0;
        }
        
        // Safe calculation with overflow protection
        unchecked {
            if (baseReward > type(uint256).max / bonusRate) {
                return MAX_REWARD_AMOUNT; // Cap at maximum
            }
            bonus = (baseReward * bonusRate) / BASIS_POINTS;
        }
        
        return bonus;
    }
    
    /// @notice Checks if user has active leases
    /// @dev Internal helper function
    /// @param user The user address
    /// @return hasLeases True if user has active leases
    function _hasActiveLeases(address user) internal pure returns (bool hasLeases) {
        // This is a simplified implementation
        // In a real scenario, this would check against a lease registry
        return user != address(0); // Placeholder logic
    }

    /******************** Modifiers ********************/
    modifier updateReward(address account) {
        // Store current reward per token value
        uint256 currentRewardPerToken = rewardPerToken();
        
        // Update stored values
        rewardPerTokenStored = currentRewardPerToken;
        lastUpdateTime = block.timestamp;
        
        // Update account-specific reward data if account is valid
        if (account != address(0)) {
            // Calculate and store earned rewards
            rewards[account] = earned(account);
            // Update user's paid reward per token to current value
            userRewardPerTokenPaid[account] = currentRewardPerToken;
            _snapshotBalances[account] = _balances[account];
            rewardExpirationTimestamps[account] = block.timestamp + MAX_CLAIM_PERIOD;
        }
        _;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../../libraries/StakingConstants.sol";

contract DynamicRewards is AccessControl, ReentrancyGuard {
    bool private _paused;

    modifier whenNotPaused() {
        require(!_paused, "Contract is paused");
        _;
    }
    
    // ================== Constants ==================
    uint256 public constant TOKEN_UNIT = 1e18; // Precision unit for token calculations
    uint256 public constant MULTIPLIER = 1e18; // Multiplier for reward calculations
    uint256 public constant PERCENTAGE_BASE = 10000; // Base for percentage calculations (100% = 10000)

    bytes32 public constant REWARD_MANAGER = keccak256("REWARD_MANAGER");
    
    struct RewardSchedule {
        uint256 startTime;
        uint256 endTime;
        uint256 totalRewards;
        uint256 claimedRewards;
        address rewardsToken; // Supports multiple reward tokens
    }

    IERC20 public immutable stakingToken;
    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;
    mapping(address => uint256) private _snapshotBalances;
    mapping(address => uint256) private _stakeTimestamps;

    uint256 public constant MIN_STAKING_PERIOD = StakingConstants.MIN_STAKING_PERIOD;
    uint256 public minStakingPeriod = MIN_STAKING_PERIOD;
    event MinStakingPeriodUpdated(uint256 newPeriod);

    mapping(uint256 => RewardSchedule) public rewardSchedules;
    uint256 public currentScheduleId;
    mapping(address => mapping(uint256 => uint256)) private _userAccrued;

    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardScheduleAdded(uint256 scheduleId);
    event RewardClaimed(address indexed user, uint256 amount, address token);
    
    function setMinStakingPeriod(uint256 period) external onlyRole(REWARD_MANAGER) {
        minStakingPeriod = period;
        emit MinStakingPeriodUpdated(period);
    }

    constructor(address _stakingToken, address admin) {
        require(_stakingToken != address(0), "Invalid staking token");
        require(admin != address(0), "Invalid admin address");
        _paused = false;
        stakingToken = IERC20(_stakingToken);
        
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(REWARD_MANAGER, admin);
    }

    // ================== Core Functions ==================
    function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(msg.sender) {
        require(amount > 0, "Amount must be > 0");
        _updateRewards(msg.sender);
        
        _totalSupply = _totalSupply + amount;
        _balances[msg.sender] = _balances[msg.sender] + amount;
        _stakeTimestamps[msg.sender] = block.timestamp;
        
        bool success = stakingToken.transferFrom(msg.sender, address(this), amount);
        require(success, "Transfer failed");
        emit Staked(msg.sender, amount);
    }

    function withdraw(uint256 amount) external nonReentrant whenNotPaused updateReward(msg.sender) {
        require(block.timestamp >= _stakeTimestamps[msg.sender] + minStakingPeriod, "Minimum staking period not met");
        require(amount > 0, "Amount must be > 0");
        require(_balances[msg.sender] >= amount, "Insufficient balance");
        
        _updateRewards(msg.sender);
        _totalSupply = _totalSupply - amount;
        _snapshotBalances[msg.sender] = _balances[msg.sender];
        _balances[msg.sender] = _balances[msg.sender] - amount;
        
        bool success = stakingToken.transfer(msg.sender, amount);
        require(success, "Transfer failed");
        emit Withdrawn(msg.sender, amount);
    }

    // ================== Reward Management ==================
    function addRewardSchedule(
        uint256 startTime,
        uint256 duration,
        uint256 totalReward,
        address rewardsToken
    ) external onlyRole(REWARD_MANAGER) {
        require(startTime >= block.timestamp, "Start time in past");
        require(duration > 0, "Invalid duration");
        require(totalReward > 0, "Invalid reward amount");
        
        uint256 balance = IERC20(rewardsToken).balanceOf(address(this));
        require(balance >= totalReward, "Insufficient reward tokens");

        uint256 scheduleId = ++currentScheduleId;
        rewardSchedules[scheduleId] = RewardSchedule({
            startTime: startTime,
            endTime: startTime + duration,
            totalRewards: totalReward,
            claimedRewards: 0,
            rewardsToken: rewardsToken
        });

        emit RewardScheduleAdded(scheduleId);
    }

    // ================== Reward Calculation ==================
    uint256 public lastUpdateTime;
    uint256 public rewardPerTokenStored;
    mapping(address => uint256) public rewards;
    mapping(address => uint256) public userRewardPerTokenPaid;

    modifier updateReward(address account) {
        uint256 currentRewardPerToken = rewardPerToken();
        rewardPerTokenStored = currentRewardPerToken;
        lastUpdateTime = block.timestamp;
        
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = currentRewardPerToken;
            _snapshotBalances[account] = _balances[account];
        }
        _;
    }

    function earned(address account) public view returns (uint256 total) {
        for (uint256 i = 1; i <= currentScheduleId; i++) {
            total = total + _earnedPerSchedule(account, i);
        }
    }

    function _earnedPerSchedule(address account, uint256 scheduleId) private view returns (uint256) {
        RewardSchedule storage schedule = rewardSchedules[scheduleId];
        if (_snapshotBalances[account] == 0 || block.timestamp < schedule.startTime) return 0;
    
        // Additional boundary check
        uint256 totalDuration = schedule.endTime - schedule.startTime;
        require(totalDuration > 0, "Invalid schedule duration");
        
        uint256 timeElapsed = block.timestamp - schedule.startTime;
        if (timeElapsed > totalDuration) { // Time upper limit check
            timeElapsed = totalDuration;
        }
    
        // Enhanced precision calculations to prevent precision loss
        // Use higher precision intermediate calculations
        uint256 PRECISION_MULTIPLIER = 1e18;

        // Calculate multiplier with higher precision
        uint256 multiplier = (timeElapsed * MULTIPLIER * PRECISION_MULTIPLIER) / totalDuration;

        // Calculate available rewards with higher precision
        uint256 availableRewards = (schedule.totalRewards * timeElapsed * PRECISION_MULTIPLIER) / totalDuration;

        // Calculate user share with higher precision
        uint256 userShare = (_balances[account] * multiplier) / (_totalSupply * PRECISION_MULTIPLIER);

        // Final calculation with precision adjustment
        uint256 earnedAmount = (availableRewards * userShare) / (TOKEN_UNIT * PRECISION_MULTIPLIER);

        // Ensure we don't underflow
        uint256 alreadyAccrued = _userAccrued[account][scheduleId];
        return earnedAmount > alreadyAccrued ? earnedAmount - alreadyAccrued : 0;
    }

    // ================== Reward Claiming ==================
    function claimRewards() external nonReentrant whenNotPaused {
        _updateRewards(msg.sender);
        
        uint256 totalClaimed = 0;
        for (uint256 i = 1; i <= currentScheduleId; i++) {
            RewardSchedule storage schedule = rewardSchedules[i];
            uint256 amount = _userAccrued[msg.sender][i];
            if (amount == 0) continue;

            // Security checks
            require(amount > 0, "Nothing to claim");
            _userAccrued[msg.sender][i] = 0;
            schedule.claimedRewards = schedule.claimedRewards + amount;
            
            _sendReward(schedule.rewardsToken, msg.sender, amount);
            totalClaimed = totalClaimed + amount;
        }

        require(totalClaimed > 0, "No rewards");
        emit RewardClaimed(msg.sender, totalClaimed, address(stakingToken));
    }

    // ================== Internal Functions ==================
    function _updateRewards(address account) internal {
        for (uint256 i = 1; i <= currentScheduleId; i++) {
            // Only update rewards if the schedule is still active
            if (block.timestamp < rewardSchedules[i].endTime) {
                _userAccrued[account][i] = _userAccrued[account][i] + _earnedPerSchedule(account, i);
            }
        }
    }

    function _sendReward(address token, address to, uint256 amount) internal {
        require(
            IERC20(token).balanceOf(address(this)) >= amount,
            "Insufficient reward balance"
        );
        bool success = IERC20(token).transfer(to, amount);
        require(success, "Transfer failed");
    }

    // ================== Pause Functions ==================
    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _paused = true;
    }

    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _paused = false;
    }

    // ================== View Functions ==================
    function balanceOf(address account) public view returns (uint256) {
        return _balances[account];
    }

    function totalStaked() public view returns (uint256) {
        return _totalSupply;
    }

    function getActiveSchedules() public view returns (uint256[] memory) {
        uint256 count = 0;
        for (uint256 i = 1; i <= currentScheduleId; i++) {
            if (block.timestamp < rewardSchedules[i].endTime) {
                count++;
            }
        }

        uint256[] memory active = new uint256[](count);
        uint256 index = 0;
        for (uint256 i = 1; i <= currentScheduleId; i++) {
            if (block.timestamp < rewardSchedules[i].endTime) {
                active[index++] = i;
            }
        }
        return active;
    }

    function rewardPerToken() public view returns (uint256) {
        if (_totalSupply == 0) {
            return rewardPerTokenStored;
        }
        return rewardPerTokenStored + ((block.timestamp - lastUpdateTime) * MULTIPLIER * rewardPerTokenStored) / _totalSupply;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

/// @title RewardsManager
/// @notice Centralized rewards distribution contract for ManageLife stakeholders
/// @dev Holds $MLife tokens and distributes according to basis-point rules. Uses operator gating
contract RewardsManager is AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    // Roles
    bytes32 public constant REWARD_MANAGER = keccak256("REWARD_MANAGER");

    // Token
    IERC20 public immutable lifeToken;

    // Constants
    uint256 public constant BPS_DENOMINATOR = 10_000; // 100% = 10000 bps
    uint256 public constant MONTH_SECONDS = 30 days; // simplified month bucket

    // Default rates (bps)
    struct Rates {
        uint16 renterCashbackBps;       // 10% on rent (SC)
        uint16 ownerRentTopUpBps;       // 10% top-up when occupied (SC)
        uint16 ownerContribTopUpBps;    // 15% top-up when contributed (SC)
        uint16 buyerPurchaseRewardBps;  // 1% of purchase price (MP)
        uint16 buyerTxRebateBps;        // 1% of tx cost if MLIFE used (MP)
        uint16 referralMinBps;          // 1%
        uint16 referralMaxBps;          // 2%
        uint256 monthlyGasRebate;       // 100 MLIFE (18 decimals)
    }

    Rates public rates;

    // Claim guards
    mapping(address => uint64) public lastGasRebateMonth; // homeowner => last month index
    mapping(bytes32 => bool) public claimUsed;            // idempotency per-award-type using namespaced keys

    // Events
    event GasRebateAwarded(address indexed homeowner, uint256 monthIndex, uint256 amount);
    event RenterCashbackAwarded(address indexed renter, bytes32 indexed paymentId, uint256 rentPaid, uint256 reward);
    event OwnerRentTopUpAwarded(address indexed owner, bytes32 indexed paymentId, bool contributed, uint256 rentAmount, uint256 reward);
    event BuyerRewardAwarded(address indexed buyer, bytes32 indexed purchaseId, uint256 purchasePrice, uint256 purchaseReward, uint256 txRebate);
    event ReferralAwarded(address indexed referrer, bytes32 indexed referralId, uint256 baseAmount, uint16 bps, uint256 reward);
    event EngagementAwarded(address indexed user, bytes32 indexed engagementId, uint256 baseAmount, uint16 bps, uint256 reward);
    event RatesUpdated(Rates newRates);
    event TokensFunded(address indexed from, uint256 amount);
    event TokensRescued(address indexed to, uint256 amount);

    constructor(address _lifeToken, address admin) {
        require(_lifeToken != address(0), "Invalid token");
        require(admin != address(0), "Invalid admin");
        lifeToken = IERC20(_lifeToken);
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(REWARD_MANAGER, admin);

        // Set sensible defaults (values in bps)
        rates = Rates({
            renterCashbackBps: 1000,       // 10%
            ownerRentTopUpBps: 1000,       // 10%
            ownerContribTopUpBps: 1500,    // 15%
            buyerPurchaseRewardBps: 100,   // 1%
            buyerTxRebateBps: 100,         // 1%
            referralMinBps: 100,           // 1%
            referralMaxBps: 200,           // 2%
            monthlyGasRebate: 100 ether    // 100 MLIFE (18 decimals)
        });
    }

    // ========================= Key Namespacing =========================
    function _ns(bytes32 tag, bytes32 id) internal pure returns (bytes32) {
        return keccak256(abi.encode(tag, id));
    }

    bytes32 private constant TAG_RENTER = keccak256("RENTER");
    bytes32 private constant TAG_OWNER_TOPUP = keccak256("OWNER_TOPUP");
    bytes32 private constant TAG_BUYER = keccak256("BUYER");
    bytes32 private constant TAG_REFERRAL = keccak256("REFERRAL");
    bytes32 private constant TAG_ENGAGE = keccak256("ENGAGE");


    // ========================= Admin =========================
    function setRates(Rates calldata newRates) external onlyRole(DEFAULT_ADMIN_ROLE) {
        require(newRates.referralMinBps <= newRates.referralMaxBps, "ref bps range");
        require(newRates.renterCashbackBps <= BPS_DENOMINATOR, "renter bps");
        require(newRates.ownerRentTopUpBps <= BPS_DENOMINATOR, "owner bps");
        require(newRates.ownerContribTopUpBps <= BPS_DENOMINATOR, "owner contrib bps");
        require(newRates.buyerPurchaseRewardBps <= BPS_DENOMINATOR, "buyer bps");
        require(newRates.buyerTxRebateBps <= BPS_DENOMINATOR, "tx bps");
        rates = newRates;
        emit RatesUpdated(newRates);
    }

    function fund(uint256 amount) external nonReentrant {
        lifeToken.safeTransferFrom(msg.sender, address(this), amount);
        emit TokensFunded(msg.sender, amount);
    }

    function rescue(address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
        lifeToken.safeTransfer(to, amount);
        emit TokensRescued(to, amount);
    }

    // ========================= Award Functions =========================
    /// @notice Gas rebate to Homeowner for listing/tokenizing, once per calendar month bucket
    function awardHomeownerGasRebate(address homeowner) external onlyRole(REWARD_MANAGER) nonReentrant {
        require(homeowner != address(0), "zero addr");
        uint64 monthIndex = uint64(block.timestamp / MONTH_SECONDS);
        require(lastGasRebateMonth[homeowner] < monthIndex, "already claimed");
        lastGasRebateMonth[homeowner] = monthIndex;
        lifeToken.safeTransfer(homeowner, rates.monthlyGasRebate);
        emit GasRebateAwarded(homeowner, monthIndex, rates.monthlyGasRebate);
    }

    /// @notice Renter: 10% $MLife back on every rent payment (SC)
    function awardRenterRentCashback(address renter, uint256 rentPaid, bytes32 paymentId) external onlyRole(REWARD_MANAGER) nonReentrant {
        require(!claimUsed[paymentId], "claimed");
        require(renter != address(0) && rentPaid > 0, "bad args");
        claimUsed[paymentId] = true;
        uint256 reward = (rentPaid * rates.renterCashbackBps) / BPS_DENOMINATOR;
        lifeToken.safeTransfer(renter, reward);
        emit RenterCashbackAwarded(renter, paymentId, rentPaid, reward);
    }

    /// @notice Homeowner/Portfolio Manager: 10% on top of rent income when occupied; 15% if contributed (SC)
    function awardOwnerRentTopUp(address owner, uint256 rentAmount, bool contributed, bytes32 paymentId) external onlyRole(REWARD_MANAGER) nonReentrant {
        require(!claimUsed[paymentId], "claimed");
        require(owner != address(0) && rentAmount > 0, "bad args");
        claimUsed[paymentId] = true;
        uint16 bps = contributed ? rates.ownerContribTopUpBps : rates.ownerRentTopUpBps;
        uint256 reward = (rentAmount * bps) / BPS_DENOMINATOR;
        lifeToken.safeTransfer(owner, reward);
        emit OwnerRentTopUpAwarded(owner, paymentId, contributed, rentAmount, reward);
    }

    /// @notice Buyer: 1% of purchase price; optional 1% rebate on tx cost if MLIFE used (MP-driven call)
    function awardBuyerPurchaseReward(
        address buyer,
        uint256 purchasePrice,
        uint256 txCost,
        bool mLifeUsed,
        bytes32 purchaseId
    ) external onlyRole(REWARD_MANAGER) nonReentrant {
        bytes32 key = _ns(TAG_BUYER, purchaseId);
        require(!claimUsed[key], "claimed");
        require(buyer != address(0) && purchasePrice > 0, "bad args");
        claimUsed[key] = true;
        uint256 baseReward = (purchasePrice * rates.buyerPurchaseRewardBps) / BPS_DENOMINATOR;
        uint256 txRebate = mLifeUsed ? (txCost * rates.buyerTxRebateBps) / BPS_DENOMINATOR : 0;
        uint256 total = baseReward + txRebate;
        if (total > 0) {
            lifeToken.safeTransfer(buyer, total);
        }
        emit BuyerRewardAwarded(buyer, purchaseId, purchasePrice, baseReward, txRebate);
    }

    /// @notice Referral: 1-2% on payment amount (MP)
    function awardReferral(address referrer, uint256 amount, uint16 bps, bytes32 referralId) external onlyRole(REWARD_MANAGER) nonReentrant {
        bytes32 key = _ns(TAG_REFERRAL, referralId);
        require(!claimUsed[key], "claimed");
        require(referrer != address(0) && amount > 0, "bad args");
        require(bps >= rates.referralMinBps && bps <= rates.referralMaxBps, "bps out of range");
        claimUsed[key] = true;
        uint256 reward = (amount * bps) / BPS_DENOMINATOR;
        lifeToken.safeTransfer(referrer, reward);
        emit ReferralAwarded(referrer, referralId, amount, bps, reward);
    }

    /// @notice Platform engagement: e.g., monthly tasks, bps applied on base (MP)
    function awardEngagement(address user, uint256 baseAmount, uint16 bps, bytes32 engagementId) external onlyRole(REWARD_MANAGER) nonReentrant {
        bytes32 key = _ns(TAG_ENGAGE, engagementId);
        require(!claimUsed[key], "claimed");
        require(user != address(0) && baseAmount > 0, "bad args");
        require(bps <= BPS_DENOMINATOR, "bps high");
        claimUsed[key] = true;
        uint256 reward = (baseAmount * bps) / BPS_DENOMINATOR;
        lifeToken.safeTransfer(user, reward);
        emit EngagementAwarded(user, engagementId, baseAmount, bps, reward);
    }
}

File 63 of 63 : StakingConstants.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;

library StakingConstants {
    uint256 public constant MIN_STAKING_PERIOD = 7 days;
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "viaIR": true,
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"initialMintDestination_","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegator","type":"address"},{"indexed":true,"internalType":"address","name":"fromDelegate","type":"address"},{"indexed":true,"internalType":"address","name":"toDelegate","type":"address"}],"name":"DelegateChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegate","type":"address"},{"indexed":false,"internalType":"uint256","name":"previousBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"DelegateVotesChanged","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"CLOCK_MODE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_SUPPLY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint32","name":"pos","type":"uint32"}],"name":"checkpoints","outputs":[{"components":[{"internalType":"uint32","name":"fromBlock","type":"uint32"},{"internalType":"uint224","name":"votes","type":"uint224"}],"internalType":"struct ERC20Votes.Checkpoint","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"clock","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"delegatee","type":"address"}],"name":"delegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"delegatee","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"delegateBySig","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"delegates","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"timepoint","type":"uint256"}],"name":"getPastTotalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"timepoint","type":"uint256"}],"name":"getPastVotes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getVotes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"numCheckpoints","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]

6101608060405234620000dd57620031e180380380916200002082620000f8565b833960608183019112620000dd578151906001600160a01b0382168203620000dd57610180516001600160401b039390848111620000dd57826200006691830162000176565b916101a051948511620000dd576200008b9462000084920162000176565b91620001dc565b6040516120d79081620010ea823960805181611adf015260a05181611b9a015260c05181611aa9015260e05181611b2e01526101005181611b540152610120518161083b015261014051816108640152f35b600080fd5b634e487b7160e01b600052604160045260246000fd5b601f01601f1916610160908101906001600160401b038211908210176200011e57604052565b620000e2565b604081019081106001600160401b038211176200011e57604052565b604051906200014f8262000124565b565b60005b838110620001655750506000910152565b818101518382015260200162000154565b81601f82011215620000dd5780516001600160401b03928382116200011e5760405193601f8301601f19908116603f01168501908111858210176200011e5760405281845260208284010111620000dd57620001d9916020808501910162000151565b90565b909291604051620001ed8162000124565b600194858252602080830193603160f81b855282519760018060401b0389116200011e5762000229896200022360035462000347565b62000384565b82601f8a11600114620002b9579880806200026594936200014f9b9c600093620002ad575b501b916000199060031b1c191617600355620004e8565b6200027082620005db565b610120526200027f83620006eb565b61014052815191012060e052519020610100524660a052620002a06200086a565b6080523060c0526200093c565b8801519250386200024e565b600360005298601f1981167fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b9060005b818110620003315750906200014f9a9b8362000265969594931062000317575b5050811b01600355620004e8565b87015160001960f88460031b161c19169055388062000309565b878d015183559b86019b918401918601620002e9565b90600182811c9216801562000379575b60208310146200036357565b634e487b7160e01b600052602260045260246000fd5b91607f169162000357565b601f811162000391575050565b6000906003825260208220906020601f850160051c83019410620003d2575b601f0160051c01915b828110620003c657505050565b818155600101620003b9565b9092508290620003b0565b601f8111620003ea575050565b6000906004825260208220906020601f850160051c830194106200042b575b601f0160051c01915b8281106200041f57505050565b81815560010162000412565b909250829062000409565b601f811162000443575050565b6000906005825260208220906020601f850160051c8301941062000484575b601f0160051c01915b8281106200047857505050565b8181556001016200046b565b909250829062000462565b601f81116200049c575050565b6000906006825260208220906020601f850160051c83019410620004dd575b601f0160051c01915b828110620004d157505050565b818155600101620004c4565b9092508290620004bb565b80519091906001600160401b0381116200011e5762000514816200050e60045462000347565b620003dd565b602080601f831160011462000553575081929360009262000547575b50508160011b916000199060031b1c191617600455565b01519050388062000530565b6004600052601f198316949091907f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b926000905b878210620005c2575050836001959610620005a8575b505050811b01600455565b015160001960f88460031b161c191690553880806200059d565b8060018596829496860151815501950193019062000587565b9081516020808210600014620005f957505090620001d990620007fb565b6001600160401b0382116200011e5762000620826200061a60055462000347565b62000436565b80601f831160011462000660575081929360009262000654575b50508160011b916000199060031b1c19161760055560ff90565b0151905038806200063a565b6005600052601f198316949091907f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0926000905b878210620006d2575050836001959610620006b8575b505050811b0160055560ff90565b015160001960f88460031b161c19169055388080620006aa565b8060018596829496860151815501950193019062000694565b90815160208082106000146200070957505090620001d990620007fb565b6001600160401b0382116200011e5762000730826200072a60065462000347565b6200048f565b80601f831160011462000770575081929360009262000764575b50508160011b916000199060031b1c19161760065560ff90565b0151905038806200074a565b6006600052601f198316949091907ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f926000905b878210620007e2575050836001959610620007c8575b505050811b0160065560ff90565b015160001960f88460031b161c19169055388080620007ba565b80600185968294968601518155019501930190620007a4565b601f8151116200082957602081519101516020821062000819571790565b6000198260200360031b1b161790565b6044604051809263305a27a960e01b8252602060048301526200085c815180928160248601526020868601910162000151565b601f01601f19168101030190fd5b60e051610100516040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815260c0810181811060018060401b038211176200011e5760405251902090565b15620008de57565b60405162461bcd60e51b815260206004820152603060248201527f4552433230566f7465733a20746f74616c20737570706c79207269736b73206f60448201526f766572666c6f77696e6720766f74657360801b6064820152608490fd5b6001600160a01b03811690811562000a0d57600254916b1027e72f1f1281308800000080840180941162000a075762000978620009e194600255565b6001600160a01b038316600090815260208190526040902090815401905560007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60405180620009d881906b1027e72f1f12813088000000602083019252565b0390a362000fbb565b600254620009f9906001600160e01b031015620008d6565b62000a0362000b72565b5050565b62000a52565b60405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606490fd5b634e487b7160e01b600052601160045260246000fd5b604080519192919081016001600160401b038111828210176200011e57604052602081935463ffffffff81168352811c910152565b600b5490680100000000000000008210156200011e576001820180600b5582101562000b0b57600b600052805160209182015190911b63ffffffff191663ffffffff91909116177f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db990910155565b634e487b7160e01b600052603260045260246000fd5b908154680100000000000000008110156200011e576001810180845581101562000b0b57600092835260209283902082519284015190931b63ffffffff191663ffffffff9290921691909117910155565b600b5490811590811562000cb95762000b8a62000140565b6000815260006020820152925b602084015162000bb7906001600160e01b03165b6001600160e01b031690565b9362000bc385620010b4565b9315908162000c92575b501562000c2a576200014f9062000c1362000be88562000e83565b600b600052917f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db80190565b9063ffffffff82549181199060201b169116179055565b506200014f62000c5362000c4d62000c424362000eed565b65ffffffffffff1690565b62000f55565b62000c8c62000c628562000e83565b62000c7c62000c7062000140565b63ffffffff9094168452565b6001600160e01b03166020830152565b62000a9d565b5163ffffffff16905063ffffffff62000caf62000c424362000eed565b9116143862000bcd565b600b60005262000cf17f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db8840162000a68565b62000a68565b9262000b97565b805491821591821562000df85762000d0f62000140565b6000815260006020820152935b602085015162000d35906001600160e01b031662000bab565b9462000d4186620010ce565b9415908162000dd1575b501562000d785762000c136200014f9262000d668662000e83565b92600019019060005260206000200190565b506200014f9062000d9162000c4d62000c424362000eed565b9062000dcb62000da18662000e83565b62000dbb62000daf62000140565b63ffffffff9095168552565b6001600160e01b03166020840152565b62000b21565b5163ffffffff16905063ffffffff62000dee62000c424362000eed565b9116143862000d4b565b62000e1262000ceb60001986018360005260206000200190565b9362000d1c565b805491821591821562000e625762000e3062000140565b6000815260006020820152935b602085015162000e56906001600160e01b031662000bab565b9462000d4186620010b4565b62000e7c62000ceb60001986018360005260206000200190565b9362000e3d565b6001600160e01b039081811162000e98571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b6064820152608490fd5b65ffffffffffff9081811162000f01571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203460448201526538206269747360d01b6064820152608490fd5b63ffffffff9081811162000f67571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b6064820152608490fd5b60096020527fec8156718a8372b1db44bb411437d0870f3e3790d4a08526d024ce1b0b668f6b546001600160a01b0391821660009081526040812054831692909116908183141580620010ab575b6200101357505050565b816200106c575b505080620010255750565b6001600160a01b0381166000908152600a60205260409020600080516020620031c183398151915290620010599062000e19565b60408051928352602083019190915290a2565b6200109260408284600080516020620031c18339815191529452600a6020522062000cf8565b60408051928352602083019190915290a238806200101a565b50600162001009565b6b1027e72f1f12813088000000810180911162000a075790565b6b1027e72f1f12813087ffffff19810190811162000a07579056fe6080604052600436101561001257600080fd5b60003560e01c806306fdde03146101b7578063095ea7b3146101b257806318160ddd146101ad57806323b872dd146101a8578063313ce567146101a357806332cb6b0c1461019e5780633644e5151461019957806339509351146101945780633a46b1a81461018f5780634bf5d7e91461018a578063587cde1e146101855780635c19a95c146101805780636fcfff451461017b57806370a08231146101765780637ecebe001461017157806384b0196e1461016c5780638e539e8c1461016757806391ddadf41461016257806395d89b411461015d5780639ab24eb014610158578063a457c2d714610153578063a9059cbb1461014e578063c3cda52014610149578063d505accf14610144578063dd62ed3e1461013f5763f1127ed81461013a57600080fd5b610f63565b610f0b565b610dc5565b610c9a565b610c54565b610ba6565b610b44565b610a9d565b610a71565b610918565b610820565b6107e6565b6107ac565b610764565b610740565b610705565b610653565b6104fe565b6104a6565b610483565b61045c565b610440565b610375565b610357565b610326565b610210565b919082519283825260005b8481106101e8575050826000602080949584010152601f8019910116010190565b6020818301810151848301820152016101c7565b90602061020d9281815201906101bc565b90565b346102f5576000806003193601126102f257604051908060035461023381610fea565b808552916001918083169081156102c8575060011461026d575b6102698561025d81870382611093565b604051918291826101fc565b0390f35b9250600383527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8284106102b057505050810160200161025d8261026961024d565b80546020858701810191909152909301928101610295565b8695506102699693506020925061025d94915060ff191682840152151560051b820101929361024d565b80fd5b600080fd5b600435906001600160a01b03821682036102f557565b602435906001600160a01b03821682036102f557565b346102f55760403660031901126102f55761034c6103426102fa565b602435903361129a565b602060405160018152f35b346102f55760003660031901126102f5576020600254604051908152f35b346102f55760603660031901126102f55761038e6102fa565b610396610310565b6001600160a01b0382166000908152600160209081526040808320338452909152902060443591905492600184016103df575b6103d3935061118c565b60405160018152602090f35b8284106103fb576103f6836103d39503338361129a565b6103c9565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b346102f55760003660031901126102f557602060405160128152f35b346102f55760003660031901126102f55760206040516b1027e72f1f128130880000008152f35b346102f55760003660031901126102f557602061049e611aa6565b604051908152f35b346102f55760403660031901126102f5576104bf6102fa565b3360009081526001602090815260408083206001600160a01b038516845290915290205460243581018091116104f95761034c913361129a565b6110b5565b346102f55760403660031901126102f5576105176102fa565b6024359061053665ffffffffffff61052e43611f89565b168310611473565b6001600160a01b03166000908152600a6020526040812080549290918360058111610602575b50905b8382106105ad57505081610586575050602060005b6040516001600160e01b039091168152f35b6105a16105a891602093600019019060005260206000200190565b5460201c90565b610574565b90926105b98185611db9565b90818363ffffffff6105df6105d5848960005260206000200190565b5463ffffffff1690565b1611156105f0575050925b9061055f565b9094506105fd91506110cb565b6105ea565b8061061261061892969396611dce565b906114bf565b908263ffffffff6106336105d5858860005260206000200190565b1611156106435750925b3861055c565b935061064e906110cb565b61063d565b346102f55760003660031901126102f5574365ffffffffffff61067543611f89565b16036106c05761026960405161068a8161103a565b601d81527f6d6f64653d626c6f636b6e756d6265722666726f6d3d64656661756c740000006020820152604051918291826101fc565b60405162461bcd60e51b815260206004820152601d60248201527f4552433230566f7465733a2062726f6b656e20636c6f636b206d6f64650000006044820152606490fd5b346102f55760203660031901126102f55760206001600160a01b03806107296102fa565b166000526009825260406000205416604051908152f35b346102f55760203660031901126102f55761076261075c6102fa565b33611518565b005b346102f55760203660031901126102f5576001600160a01b036107856102fa565b16600052600a602052602061079e604060002054611ff0565b63ffffffff60405191168152f35b346102f55760203660031901126102f5576001600160a01b036107cd6102fa565b1660005260006020526020604060002054604051908152f35b346102f55760203660031901126102f5576001600160a01b036108076102fa565b1660005260076020526020604060002054604051908152f35b346102f5576000806003193601126102f2576108ca9061085f7f0000000000000000000000000000000000000000000000000000000000000000611be6565b6108887f0000000000000000000000000000000000000000000000000000000000000000611cdf565b91604051916108968361105b565b818352604051948594600f60f81b86526108bc60209360e08589015260e08801906101bc565b9086820360408801526101bc565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061090157505050500390f35b8351855286955093810193928101926001016108f2565b346102f55760203660031901126102f55760043561094765ffffffffffff61093f43611f89565b168210611473565b600b549060008260058111610a0a575b50905b8282106109a7578280610974575060405160008152602090f35b600b6000526020906105a8907f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db8016105a1565b90916109b38184611db9565b600b600052908263ffffffff6109ea7f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db985016105d5565b1611156109fa5750915b9061095a565b9250610a05906110cb565b6109f4565b80610612610a1a92959395611dce565b600b600052908263ffffffff610a517f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db985016105d5565b161115610a615750915b38610957565b9250610a6c906110cb565b610a5b565b346102f55760003660031901126102f5576020610a8d43611f89565b65ffffffffffff60405191168152f35b346102f5576000806003193601126102f2576040519080600454610ac081610fea565b808552916001918083169081156102c85750600114610ae9576102698561025d81870382611093565b9250600483527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b828410610b2c57505050810160200161025d8261026961024d565b80546020858701810191909152909301928101610b11565b346102f55760203660031901126102f5576001600160a01b03610b656102fa565b16600052600a602052604060002080548015600014610b8c57505060405160008152602090f35b602091610b9d916000190190611423565b5054811c610574565b346102f55760403660031901126102f557610bbf6102fa565b60243590336000526001602052610bec8160406000209060018060a01b0316600052602052604060002090565b5491808310610c01576103d39203903361129a565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608490fd5b346102f55760403660031901126102f55761034c610c706102fa565b602435903361118c565b6064359060ff821682036102f557565b6084359060ff821682036102f557565b346102f55760c03660031901126102f557610cb36102fa565b60443590602435610cc2610c7a565b92804211610d8057610d52610d7b916107629560405190610d3a82610d2c6020820195898b8860609194939260808201957fe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf835260018060a01b0316602083015260408201520152565b03601f198101845283611093565b610d4d60a4359360843593519020611bc0565b6118c0565b6001600160a01b03811660009081526007602052604090208054600181019091559092146114cc565b611518565b60405162461bcd60e51b815260206004820152601d60248201527f4552433230566f7465733a207369676e617475726520657870697265640000006044820152606490fd5b346102f55760e03660031901126102f557610dde6102fa565b610de6610310565b6044359060643592610df6610c8a565b93804211610ec657610eae610ec191610d2c61076297610e9b610e348760018060a01b03166000526007602052604060002090815491600183019055565b604080517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9602082019081526001600160a01b03808c1693830193909352918b166060820152608081018c905260a081019290925260c082019590955292839060e0820190565b610d4d60c4359360a43593519020611bc0565b6001600160a01b038381169116146113ca565b61129a565b60405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606490fd5b346102f55760403660031901126102f5576020610f5a610f296102fa565b610f31610310565b6001600160a01b0391821660009081526001855260408082209290931681526020919091522090565b54604051908152f35b346102f55760403660031901126102f557610f7c6102fa565b63ffffffff60243581811681036102f557610fc6610fcc91604094600060208751610fa68161103a565b82815201526001600160a01b03166000908152600a602052859020611423565b50611451565b8251815190921682526020908101516001600160e01b031690820152f35b90600182811c9216801561101a575b602083101461100457565b634e487b7160e01b600052602260045260246000fd5b91607f1691610ff9565b634e487b7160e01b600052604160045260246000fd5b6040810190811067ffffffffffffffff82111761105657604052565b611024565b6020810190811067ffffffffffffffff82111761105657604052565b60c0810190811067ffffffffffffffff82111761105657604052565b90601f8019910116810190811067ffffffffffffffff82111761105657604052565b634e487b7160e01b600052601160045260246000fd5b90600182018092116104f957565b156110e057565b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b1561113857565b60405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b6001600160a01b03929190838116801561124757611245948316906111b28215156110d9565b6001600160a01b03831660009081526020819052604090208590546111d982821015611131565b036111f68460018060a01b03166000526000602052604060002090565b556001600160a01b0384166000908152602081815260409182902080548801905590518681527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9190a3612055565b565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fd5b6001600160a01b03808216929190831561137957821693841561132957806113137f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925946112fc6113249560018060a01b03166000526001602052604060002090565b9060018060a01b0316600052602052604060002090565b556040519081529081906020820190565b0390a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b156113d157565b60405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606490fd5b604051906112458261103a565b805482101561143b5760005260206000200190600090565b634e487b7160e01b600052603260045260246000fd5b9060405161145e8161103a565b602081935463ffffffff81168352811c910152565b1561147a57565b60405162461bcd60e51b815260206004820152601960248201527f4552433230566f7465733a20667574757265206c6f6f6b7570000000000000006044820152606490fd5b919082039182116104f957565b156114d357565b60405162461bcd60e51b815260206004820152601960248201527f4552433230566f7465733a20696e76616c6964206e6f6e6365000000000000006044820152606490fd5b6112459160018060a01b038092166000928184526009602052806040852054168092856020527f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f60408720549660096020526040812094871694856bffffffffffffffffffffffff60a01b82541617905580a45b6001600160a01b0380831693929116808414158061179f575b6115b0575b50505050565b8061161e575b50826115c3575b806115aa565b6001600160a01b03166000908152600a602052604090207fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a7249161160591611807565b60408051928352602083019190915290a23880806115bd565b80600052600a6020527fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a724604060002080548015918260001461177c57611662611416565b6000815260006020820152915b602083015161168e906001600160e01b03165b6001600160e01b031690565b926116998985612087565b94159081611759575b50156116f7576116ca6116e1926116b886611f20565b92600019019060005260206000200190565b9063ffffffff82549181199060201b169116179055565b604080519182526020820192909252a2386115b6565b506117549061171b61171661170b43611f89565b65ffffffffffff1690565b611ff0565b9061174f61172886611f20565b61173f611733611416565b63ffffffff9095168552565b6001600160e01b03166020840152565b6117a8565b6116e1565b5163ffffffff16905063ffffffff61177361170b43611f89565b911614386116a2565b61179961179460001984018360005260206000200190565b611451565b9161166f565b508215156115a5565b805468010000000000000000811015611056576117ca91600182018155611423565b6117f157815160209283015190921b63ffffffff191663ffffffff92909216919091179055565b634e487b7160e01b600052600060045260246000fd5b9091815491821592836000146118a35761181f611416565b60008152600060208201525b602081015161184d90611846906001600160e01b0316611682565b9687612094565b94159081611880575b501561186c576116ca611245926116b886611f20565b506112459061171b61171661170b43611f89565b5163ffffffff16905063ffffffff61189a61170b43611f89565b91161438611856565b6118bb61179460001983018460005260206000200190565b61182b565b9161020d93916118cf93611a17565b9190916118f7565b600511156118e157565b634e487b7160e01b600052602160045260246000fd5b611900816118d7565b806119085750565b611911816118d7565b6001810361195e5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606490fd5b611967816118d7565b600281036119b45760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606490fd5b806119c06003926118d7565b146119c757565b60405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608490fd5b9291907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311611a9a5791608094939160ff602094604051948552168484015260408301526060820152600093849182805260015afa15611a8d5781516001600160a01b03811615611a87579190565b50600190565b50604051903d90823e3d90fd5b50505050600090600390565b307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161480611b97575b15611b01577f000000000000000000000000000000000000000000000000000000000000000090565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f000000000000000000000000000000000000000000000000000000000000000060408201527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260a08152611b9181611077565b51902090565b507f00000000000000000000000000000000000000000000000000000000000000004614611ad8565b604290611bcb611aa6565b906040519161190160f01b8352600283015260228201522090565b60ff8114611c245760ff811690601f8211611c125760405191611c088361103a565b8252602082015290565b604051632cd44ac360e21b8152600490fd5b50604051600554816000611c3783610fea565b80835292600190818116908115611cbd5750600114611c5e575b5061020d92500382611093565b6005600090815291507f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db05b848310611ca2575061020d935050810160200138611c51565b81935090816020925483858901015201910190918492611c89565b90506020925061020d94915060ff191682840152151560051b82010138611c51565b60ff8114611d015760ff811690601f8211611c125760405191611c088361103a565b50604051600654816000611d1483610fea565b80835292600190818116908115611cbd5750600114611d3a575061020d92500382611093565b6006600090815291507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b848310611d7e575061020d935050810160200138611c51565b81935090816020925483858901015201910190918492611d65565b8115611da3570490565b634e487b7160e01b600052601260045260246000fd5b90808216911860011c81018091116104f95790565b8015611f085780611ea1611e9a611e90611e86611e7c611e72611e68611e5e600161020d9a6000908b60801c80611efc575b508060401c80611eef575b508060201c80611ee2575b508060101c80611ed5575b508060081c80611ec8575b508060041c80611ebb575b508060021c80611eae575b50821c611ea7575b811c1b611e57818b611d99565b0160011c90565b611e57818a611d99565b611e578189611d99565b611e578188611d99565b611e578187611d99565b611e578186611d99565b611e578185611d99565b8092611d99565b90611f0e565b8101611e4a565b6002915091019038611e42565b6004915091019038611e37565b6008915091019038611e2c565b6010915091019038611e21565b6020915091019038611e16565b6040915091019038611e0b565b91505060809038611e00565b50600090565b9080821015611f1b575090565b905090565b6001600160e01b0390818111611f34571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b6064820152608490fd5b65ffffffffffff90818111611f9c571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203460448201526538206269747360d01b6064820152608490fd5b63ffffffff90818111612001571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b6064820152608490fd5b6001600160a01b039081166000908152600960205260408082205493831682529020546112459392908216911661158c565b9081039081116104f95790565b9081018091116104f9579056fea2646970667358221220b16d6e1517aa679dd164097677a137b59abff27e07ca251f0de8494c1bdde5e064736f6c63430008140033dec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a72400000000000000000000000096d3fec8043978b59fd4d5ed1573c0aacfe39680000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000104d616e6167654c69666520546f6b656e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000054d4c494645000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x6080604052600436101561001257600080fd5b60003560e01c806306fdde03146101b7578063095ea7b3146101b257806318160ddd146101ad57806323b872dd146101a8578063313ce567146101a357806332cb6b0c1461019e5780633644e5151461019957806339509351146101945780633a46b1a81461018f5780634bf5d7e91461018a578063587cde1e146101855780635c19a95c146101805780636fcfff451461017b57806370a08231146101765780637ecebe001461017157806384b0196e1461016c5780638e539e8c1461016757806391ddadf41461016257806395d89b411461015d5780639ab24eb014610158578063a457c2d714610153578063a9059cbb1461014e578063c3cda52014610149578063d505accf14610144578063dd62ed3e1461013f5763f1127ed81461013a57600080fd5b610f63565b610f0b565b610dc5565b610c9a565b610c54565b610ba6565b610b44565b610a9d565b610a71565b610918565b610820565b6107e6565b6107ac565b610764565b610740565b610705565b610653565b6104fe565b6104a6565b610483565b61045c565b610440565b610375565b610357565b610326565b610210565b919082519283825260005b8481106101e8575050826000602080949584010152601f8019910116010190565b6020818301810151848301820152016101c7565b90602061020d9281815201906101bc565b90565b346102f5576000806003193601126102f257604051908060035461023381610fea565b808552916001918083169081156102c8575060011461026d575b6102698561025d81870382611093565b604051918291826101fc565b0390f35b9250600383527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8284106102b057505050810160200161025d8261026961024d565b80546020858701810191909152909301928101610295565b8695506102699693506020925061025d94915060ff191682840152151560051b820101929361024d565b80fd5b600080fd5b600435906001600160a01b03821682036102f557565b602435906001600160a01b03821682036102f557565b346102f55760403660031901126102f55761034c6103426102fa565b602435903361129a565b602060405160018152f35b346102f55760003660031901126102f5576020600254604051908152f35b346102f55760603660031901126102f55761038e6102fa565b610396610310565b6001600160a01b0382166000908152600160209081526040808320338452909152902060443591905492600184016103df575b6103d3935061118c565b60405160018152602090f35b8284106103fb576103f6836103d39503338361129a565b6103c9565b60405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606490fd5b346102f55760003660031901126102f557602060405160128152f35b346102f55760003660031901126102f55760206040516b1027e72f1f128130880000008152f35b346102f55760003660031901126102f557602061049e611aa6565b604051908152f35b346102f55760403660031901126102f5576104bf6102fa565b3360009081526001602090815260408083206001600160a01b038516845290915290205460243581018091116104f95761034c913361129a565b6110b5565b346102f55760403660031901126102f5576105176102fa565b6024359061053665ffffffffffff61052e43611f89565b168310611473565b6001600160a01b03166000908152600a6020526040812080549290918360058111610602575b50905b8382106105ad57505081610586575050602060005b6040516001600160e01b039091168152f35b6105a16105a891602093600019019060005260206000200190565b5460201c90565b610574565b90926105b98185611db9565b90818363ffffffff6105df6105d5848960005260206000200190565b5463ffffffff1690565b1611156105f0575050925b9061055f565b9094506105fd91506110cb565b6105ea565b8061061261061892969396611dce565b906114bf565b908263ffffffff6106336105d5858860005260206000200190565b1611156106435750925b3861055c565b935061064e906110cb565b61063d565b346102f55760003660031901126102f5574365ffffffffffff61067543611f89565b16036106c05761026960405161068a8161103a565b601d81527f6d6f64653d626c6f636b6e756d6265722666726f6d3d64656661756c740000006020820152604051918291826101fc565b60405162461bcd60e51b815260206004820152601d60248201527f4552433230566f7465733a2062726f6b656e20636c6f636b206d6f64650000006044820152606490fd5b346102f55760203660031901126102f55760206001600160a01b03806107296102fa565b166000526009825260406000205416604051908152f35b346102f55760203660031901126102f55761076261075c6102fa565b33611518565b005b346102f55760203660031901126102f5576001600160a01b036107856102fa565b16600052600a602052602061079e604060002054611ff0565b63ffffffff60405191168152f35b346102f55760203660031901126102f5576001600160a01b036107cd6102fa565b1660005260006020526020604060002054604051908152f35b346102f55760203660031901126102f5576001600160a01b036108076102fa565b1660005260076020526020604060002054604051908152f35b346102f5576000806003193601126102f2576108ca9061085f7f4d616e6167654c69666520546f6b656e00000000000000000000000000000010611be6565b6108887f3100000000000000000000000000000000000000000000000000000000000001611cdf565b91604051916108968361105b565b818352604051948594600f60f81b86526108bc60209360e08589015260e08801906101bc565b9086820360408801526101bc565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061090157505050500390f35b8351855286955093810193928101926001016108f2565b346102f55760203660031901126102f55760043561094765ffffffffffff61093f43611f89565b168210611473565b600b549060008260058111610a0a575b50905b8282106109a7578280610974575060405160008152602090f35b600b6000526020906105a8907f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db8016105a1565b90916109b38184611db9565b600b600052908263ffffffff6109ea7f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db985016105d5565b1611156109fa5750915b9061095a565b9250610a05906110cb565b6109f4565b80610612610a1a92959395611dce565b600b600052908263ffffffff610a517f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db985016105d5565b161115610a615750915b38610957565b9250610a6c906110cb565b610a5b565b346102f55760003660031901126102f5576020610a8d43611f89565b65ffffffffffff60405191168152f35b346102f5576000806003193601126102f2576040519080600454610ac081610fea565b808552916001918083169081156102c85750600114610ae9576102698561025d81870382611093565b9250600483527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b5b828410610b2c57505050810160200161025d8261026961024d565b80546020858701810191909152909301928101610b11565b346102f55760203660031901126102f5576001600160a01b03610b656102fa565b16600052600a602052604060002080548015600014610b8c57505060405160008152602090f35b602091610b9d916000190190611423565b5054811c610574565b346102f55760403660031901126102f557610bbf6102fa565b60243590336000526001602052610bec8160406000209060018060a01b0316600052602052604060002090565b5491808310610c01576103d39203903361129a565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608490fd5b346102f55760403660031901126102f55761034c610c706102fa565b602435903361118c565b6064359060ff821682036102f557565b6084359060ff821682036102f557565b346102f55760c03660031901126102f557610cb36102fa565b60443590602435610cc2610c7a565b92804211610d8057610d52610d7b916107629560405190610d3a82610d2c6020820195898b8860609194939260808201957fe48329057bfd03d55e49b547132e39cffd9c1820ad7b9d4c5307691425d15adf835260018060a01b0316602083015260408201520152565b03601f198101845283611093565b610d4d60a4359360843593519020611bc0565b6118c0565b6001600160a01b03811660009081526007602052604090208054600181019091559092146114cc565b611518565b60405162461bcd60e51b815260206004820152601d60248201527f4552433230566f7465733a207369676e617475726520657870697265640000006044820152606490fd5b346102f55760e03660031901126102f557610dde6102fa565b610de6610310565b6044359060643592610df6610c8a565b93804211610ec657610eae610ec191610d2c61076297610e9b610e348760018060a01b03166000526007602052604060002090815491600183019055565b604080517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9602082019081526001600160a01b03808c1693830193909352918b166060820152608081018c905260a081019290925260c082019590955292839060e0820190565b610d4d60c4359360a43593519020611bc0565b6001600160a01b038381169116146113ca565b61129a565b60405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e650000006044820152606490fd5b346102f55760403660031901126102f5576020610f5a610f296102fa565b610f31610310565b6001600160a01b0391821660009081526001855260408082209290931681526020919091522090565b54604051908152f35b346102f55760403660031901126102f557610f7c6102fa565b63ffffffff60243581811681036102f557610fc6610fcc91604094600060208751610fa68161103a565b82815201526001600160a01b03166000908152600a602052859020611423565b50611451565b8251815190921682526020908101516001600160e01b031690820152f35b90600182811c9216801561101a575b602083101461100457565b634e487b7160e01b600052602260045260246000fd5b91607f1691610ff9565b634e487b7160e01b600052604160045260246000fd5b6040810190811067ffffffffffffffff82111761105657604052565b611024565b6020810190811067ffffffffffffffff82111761105657604052565b60c0810190811067ffffffffffffffff82111761105657604052565b90601f8019910116810190811067ffffffffffffffff82111761105657604052565b634e487b7160e01b600052601160045260246000fd5b90600182018092116104f957565b156110e057565b60405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608490fd5b1561113857565b60405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608490fd5b6001600160a01b03929190838116801561124757611245948316906111b28215156110d9565b6001600160a01b03831660009081526020819052604090208590546111d982821015611131565b036111f68460018060a01b03166000526000602052604060002090565b556001600160a01b0384166000908152602081815260409182902080548801905590518681527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9190a3612055565b565b60405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608490fd5b6001600160a01b03808216929190831561137957821693841561132957806113137f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925946112fc6113249560018060a01b03166000526001602052604060002090565b9060018060a01b0316600052602052604060002090565b556040519081529081906020820190565b0390a3565b60405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608490fd5b60405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b156113d157565b60405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e617475726500006044820152606490fd5b604051906112458261103a565b805482101561143b5760005260206000200190600090565b634e487b7160e01b600052603260045260246000fd5b9060405161145e8161103a565b602081935463ffffffff81168352811c910152565b1561147a57565b60405162461bcd60e51b815260206004820152601960248201527f4552433230566f7465733a20667574757265206c6f6f6b7570000000000000006044820152606490fd5b919082039182116104f957565b156114d357565b60405162461bcd60e51b815260206004820152601960248201527f4552433230566f7465733a20696e76616c6964206e6f6e6365000000000000006044820152606490fd5b6112459160018060a01b038092166000928184526009602052806040852054168092856020527f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f60408720549660096020526040812094871694856bffffffffffffffffffffffff60a01b82541617905580a45b6001600160a01b0380831693929116808414158061179f575b6115b0575b50505050565b8061161e575b50826115c3575b806115aa565b6001600160a01b03166000908152600a602052604090207fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a7249161160591611807565b60408051928352602083019190915290a23880806115bd565b80600052600a6020527fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a724604060002080548015918260001461177c57611662611416565b6000815260006020820152915b602083015161168e906001600160e01b03165b6001600160e01b031690565b926116998985612087565b94159081611759575b50156116f7576116ca6116e1926116b886611f20565b92600019019060005260206000200190565b9063ffffffff82549181199060201b169116179055565b604080519182526020820192909252a2386115b6565b506117549061171b61171661170b43611f89565b65ffffffffffff1690565b611ff0565b9061174f61172886611f20565b61173f611733611416565b63ffffffff9095168552565b6001600160e01b03166020840152565b6117a8565b6116e1565b5163ffffffff16905063ffffffff61177361170b43611f89565b911614386116a2565b61179961179460001984018360005260206000200190565b611451565b9161166f565b508215156115a5565b805468010000000000000000811015611056576117ca91600182018155611423565b6117f157815160209283015190921b63ffffffff191663ffffffff92909216919091179055565b634e487b7160e01b600052600060045260246000fd5b9091815491821592836000146118a35761181f611416565b60008152600060208201525b602081015161184d90611846906001600160e01b0316611682565b9687612094565b94159081611880575b501561186c576116ca611245926116b886611f20565b506112459061171b61171661170b43611f89565b5163ffffffff16905063ffffffff61189a61170b43611f89565b91161438611856565b6118bb61179460001983018460005260206000200190565b61182b565b9161020d93916118cf93611a17565b9190916118f7565b600511156118e157565b634e487b7160e01b600052602160045260246000fd5b611900816118d7565b806119085750565b611911816118d7565b6001810361195e5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606490fd5b611967816118d7565b600281036119b45760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606490fd5b806119c06003926118d7565b146119c757565b60405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608490fd5b9291907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311611a9a5791608094939160ff602094604051948552168484015260408301526060820152600093849182805260015afa15611a8d5781516001600160a01b03811615611a87579190565b50600190565b50604051903d90823e3d90fd5b50505050600090600390565b307f0000000000000000000000005d4cb367eacdfeb9b42f86cd6f98f5a7c43bf9336001600160a01b03161480611b97575b15611b01577f8ccf4492adb54682069268e564760bd021a43202000941b647bf484df243c8c190565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527fbeafe64928eebd0a386a08d0b637d8ba7282218223efb1cf03755c033836885f60408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a08152611b9181611077565b51902090565b507f00000000000000000000000000000000000000000000000000000000000000014614611ad8565b604290611bcb611aa6565b906040519161190160f01b8352600283015260228201522090565b60ff8114611c245760ff811690601f8211611c125760405191611c088361103a565b8252602082015290565b604051632cd44ac360e21b8152600490fd5b50604051600554816000611c3783610fea565b80835292600190818116908115611cbd5750600114611c5e575b5061020d92500382611093565b6005600090815291507f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db05b848310611ca2575061020d935050810160200138611c51565b81935090816020925483858901015201910190918492611c89565b90506020925061020d94915060ff191682840152151560051b82010138611c51565b60ff8114611d015760ff811690601f8211611c125760405191611c088361103a565b50604051600654816000611d1483610fea565b80835292600190818116908115611cbd5750600114611d3a575061020d92500382611093565b6006600090815291507ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f5b848310611d7e575061020d935050810160200138611c51565b81935090816020925483858901015201910190918492611d65565b8115611da3570490565b634e487b7160e01b600052601260045260246000fd5b90808216911860011c81018091116104f95790565b8015611f085780611ea1611e9a611e90611e86611e7c611e72611e68611e5e600161020d9a6000908b60801c80611efc575b508060401c80611eef575b508060201c80611ee2575b508060101c80611ed5575b508060081c80611ec8575b508060041c80611ebb575b508060021c80611eae575b50821c611ea7575b811c1b611e57818b611d99565b0160011c90565b611e57818a611d99565b611e578189611d99565b611e578188611d99565b611e578187611d99565b611e578186611d99565b611e578185611d99565b8092611d99565b90611f0e565b8101611e4a565b6002915091019038611e42565b6004915091019038611e37565b6008915091019038611e2c565b6010915091019038611e21565b6020915091019038611e16565b6040915091019038611e0b565b91505060809038611e00565b50600090565b9080821015611f1b575090565b905090565b6001600160e01b0390818111611f34571690565b60405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e20326044820152663234206269747360c81b6064820152608490fd5b65ffffffffffff90818111611f9c571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203460448201526538206269747360d01b6064820152608490fd5b63ffffffff90818111612001571690565b60405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b6064820152608490fd5b6001600160a01b039081166000908152600960205260408082205493831682529020546112459392908216911661158c565b9081039081116104f95790565b9081018091116104f9579056fea2646970667358221220b16d6e1517aa679dd164097677a137b59abff27e07ca251f0de8494c1bdde5e064736f6c63430008140033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000096d3fec8043978b59fd4d5ed1573c0aacfe39680000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000104d616e6167654c69666520546f6b656e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000054d4c494645000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : initialMintDestination_ (address): 0x96d3Fec8043978B59fD4D5ED1573C0AACfE39680
Arg [1] : name_ (string): ManageLife Token
Arg [2] : symbol_ (string): MLIFE

-----Encoded View---------------
7 Constructor Arguments found :
Arg [0] : 00000000000000000000000096d3fec8043978b59fd4d5ed1573c0aacfe39680
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [2] : 00000000000000000000000000000000000000000000000000000000000000a0
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000010
Arg [4] : 4d616e6167654c69666520546f6b656e00000000000000000000000000000000
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000005
Arg [6] : 4d4c494645000000000000000000000000000000000000000000000000000000


Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.