GLMR Price: $0.020964 (-1.28%)

Contract

0x43A73988Fd1F05352D8261d4F858679d4FEdb9A6

Overview

GLMR Balance

Moonbeam Chain LogoMoonbeam Chain LogoMoonbeam Chain Logo0 GLMR

GLMR Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MarketplaceConfigFacet

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 175 runs

Other Settings:
default evmVersion
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {LibMarketAppStorage, AppStorage, Modifiers} from "../libraries/LibMarketAppStorage.sol";
import {LibMarketStorage, MarketStorage} from "../libraries/LibMarketStorage.sol";
import "../libraries/MarketErrors.sol";
import {LibMeta} from "../../diamond/libraries/LibMeta.sol";
import {TokenEscrow} from "../../erc20/EscroContract.sol";
import {EvrlootResources} from "../../Resources/EvrlootResources.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/** Evrloot Marketplace Facet Contract v0.5 -- Config functions + Setters/Getters
 *
 * @notice This contract is used to create trades and bids for Evrloot NFTs and resources
 * @notice Trades can be created with a buyout price in ether and/or erc20 tokens
 * @notice (if both ether+erc20 buyouts are provided, then either can be used to buy out the trade)
 * @dev Trades are stored with a bitmap of included item types. This is done for efficiency and to avoid stack depth issues.
 * @dev The bitmap indicates which item types are part of the trade, such that SLOADs are minimized to what is necessary.
 * @dev All item types (erc725, 1155, 20, etc) are stored in separate mappings and arrays.
 * @dev pulled in by the contract as required when a transfer is made.
 */
contract MarketplaceConfigFacet is Modifiers {
    event Paused(address account);
    event Unpaused(address account);

    constructor() {}

    /** ===== SETTERS ===== */

    /**
     * @dev Sets the supported tokens
     * @param _supportedTokens The addresses of the supported tokens
     */
    function setPermittedTokens(
        address[] memory _supportedTokens
    ) external onlyOwnerOrBackend {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint i = 0; i < _supportedTokens.length; i++) {
            ms.supportedTokens[_supportedTokens[i]] = true;
        }
    }

    /**
     * @dev Sets the supported resources (Evrloot ERC1155 Resource contract only)
     * @param _supportedResources The IDs of the supported resources
     */
    function setPermittedResources(
        uint16[] memory _supportedResources
    ) external onlyOwnerOrBackend {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint i = 0; i < _supportedResources.length; i++) {
            ms.supportedResources[_supportedResources[i]] = true;
        }
    }

    /**
     * @dev Sets trade fee by nft
     * @param _collectionAddress The collection address
     * @param _tradeFeePerNft The fee in wei per nft
     */
    function setTradeFeeByNft(
        address _collectionAddress,
        uint256 _tradeFeePerNft
    ) external onlyOwner {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        ms.collectionFeePerNftItem[_collectionAddress] = _tradeFeePerNft;
    }

    /**
     * @dev Sets trade fee by nft
     * @param _tradeFeePerResource The fee in wei per resource
     */
    function setTradeFeePerResource(
        uint256 _tradeFeePerResource
    ) external onlyOwner {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        ms.collectionFeePerResource = _tradeFeePerResource;
    }

    /**
     * @dev Sets trade fee by nft
     * @param _tradeCommissionRateBps Commission in bps (applied to erc20 and ether)
     */
    function setTradeCommissionRate(
        uint256 _tradeCommissionRateBps
    ) external onlyOwner {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        require(
            _tradeCommissionRateBps <= 10000,
            "Commission rate exceeds 10000"
        );
        ms.tradeCommissionRateBps = _tradeCommissionRateBps;
    }

    function setRoyaltyAddress(address _newRoyaltyAddress) internal {
        s.royaltyAddress = _newRoyaltyAddress;
    }

    function setResourceContract(
        EvrlootResources resourceContract
    ) external onlyOwner {
        s.evrlootResourceContract = resourceContract;
    }

    function setGameContract(address gameContract) external onlyOwner {
        s.gameContractAddress = gameContract;
    }

    function setEscrowContract(TokenEscrow _escrowContract) external onlyOwner {
        s.escrowedTokenContract = _escrowContract;
    }

    function viewEtherFeesCollected() external view returns (uint256) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        return ms.etherFeesCollected;
    }

    function withdrawFeesToRoyaltyAddress() external onlyOwner {
        if (s.royaltyAddress == address(0)) {
            revert RoyaltyAddressNotSet();
        }
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        uint256 amount = ms.etherFeesCollected;
        ms.etherFeesCollected = 0;

        (bool sent, ) = payable(s.royaltyAddress).call{value: amount}("");

        require(sent, "Marketplace: Withdraw failed");
    }

    function withdrawTokenFeesToRoyaltyAddress(
        address tokenAddress
    ) external onlyOwner {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        if (s.royaltyAddress == address(0)) {
            revert RoyaltyAddressNotSet();
        }

        uint256 amount = ms.tokenFeesCollected[tokenAddress];
        ms.tokenFeesCollected[tokenAddress] = 0;

        ERC20 token = ERC20(tokenAddress);
        token.transfer(s.royaltyAddress, amount);
    }

    function setTrustedForwarder(address _forwarder) external onlyOwner {
        LibMeta._setTrustedForwarder(_forwarder);
    }

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

    function pause() public onlyOwnerOrBackend {
        s.paused = true;
        emit Paused(LibMeta.msgSender());
    }

    function unpause() public onlyOwnerOrBackend {
        s.paused = false;
        emit Unpaused(LibMeta.msgSender());
    }
}

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

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    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);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).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 ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.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());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 4 of 49 : draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822ProxiableUpgradeable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

File 5 of 49 : IERC1967Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.0;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 *
 * _Available since v4.8.3._
 */
interface IERC1967Upgradeable {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

File 6 of 49 : IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

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

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import {Initializable} from "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    function __ERC1967Upgrade_init() internal onlyInitializing {
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

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

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

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
        return _IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeTo(address newImplementation) public virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data, true);
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeTo} and {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal override onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

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

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @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.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _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());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
    /**
     * @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) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * 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;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

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

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 IERC165Upgradeable {
    /**
     * @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 MathUpgradeable {
    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);
        }
    }
}

// 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 SignedMathUpgradeable {
    /**
     * @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/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 StorageSlotUpgradeable {
    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/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    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 = MathUpgradeable.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(SignedMathUpgradeable.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, MathUpgradeable.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.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 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.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.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

// 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/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/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: Apache-2.0

pragma solidity ^0.8.18;

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

/**
 * @title IERC6059
 * @author RMRK team
 * @notice Interface smart contract of the RMRK nestable module.
 */
interface IERC6059 is IERC165 {
    /**
     * @notice The core struct of RMRK ownership.
     * @dev The `DirectOwner` struct is used to store information of the next immediate owner, be it the parent token or
     *  the externally owned account.
     * @dev If the token is owned by the externally owned account, the `tokenId` should equal `0`.
     * @param tokenId ID of the parent token
     * @param ownerAddress Address of the owner of the token. If the owner is another token, then the address should be
     *  the one of the parent token's collection smart contract. If the owner is externally owned account, the address
     *  should be the address of this account
     * @param isNft A boolean value signifying whether the token is owned by another token (`true`) or by an externally
     *  owned account (`false`)
     */
    struct DirectOwner {
        uint256 tokenId;
        address ownerAddress;
    }

    /**
     * @notice Used to notify listeners that the token is being transferred.
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     * @param from Address of the previous immediate owner, which is a smart contract if the token was nested.
     * @param to Address of the new immediate owner, which is a smart contract if the token is being nested.
     * @param fromTokenId ID of the previous parent token. If the token was not nested before, the value should be `0`
     * @param toTokenId ID of the new parent token. If the token is not being nested, the value should be `0`
     * @param tokenId ID of the token being transferred
     */
    event NestTransfer(
        address indexed from,
        address indexed to,
        uint256 fromTokenId,
        uint256 toTokenId,
        uint256 indexed tokenId
    );

    /**
     * @notice Used to notify listeners that a new token has been added to a given token's pending children array.
     * @dev Emitted when a child NFT is added to a token's pending array.
     * @param tokenId ID of the token that received a new pending child token
     * @param childIndex Index of the proposed child token in the parent token's pending children array
     * @param childAddress Address of the proposed child token's collection smart contract
     * @param childId ID of the child token in the child token's collection smart contract
     */
    event ChildProposed(
        uint256 indexed tokenId,
        uint256 childIndex,
        address indexed childAddress,
        uint256 indexed childId
    );

    /**
     * @notice Used to notify listeners that a new child token was accepted by the parent token.
     * @dev Emitted when a parent token accepts a token from its pending array, migrating it to the active array.
     * @param tokenId ID of the token that accepted a new child token
     * @param childIndex Index of the newly accepted child token in the parent token's active children array
     * @param childAddress Address of the child token's collection smart contract
     * @param childId ID of the child token in the child token's collection smart contract
     */
    event ChildAccepted(
        uint256 indexed tokenId,
        uint256 childIndex,
        address indexed childAddress,
        uint256 indexed childId
    );

    /**
     * @notice Used to notify listeners that all pending child tokens of a given token have been rejected.
     * @dev Emitted when a token removes all a child tokens from its pending array.
     * @param tokenId ID of the token that rejected all of the pending children
     */
    event AllChildrenRejected(uint256 indexed tokenId);

    /**
     * @notice Used to notify listeners a child token has been transferred from parent token.
     * @dev Emitted when a token transfers a child from itself, transferring ownership to the root owner.
     * @param tokenId ID of the token that transferred a child token
     * @param childIndex Index of a child in the array from which it is being transferred
     * @param childAddress Address of the child token's collection smart contract
     * @param childId ID of the child token in the child token's collection smart contract
     * @param fromPending A boolean value signifying whether the token was in the pending child tokens array (`true`) or
     *  in the active child tokens array (`false`)
     * @param toZero A boolean value signifying whether the token is being transferred to the `0x0` address (`true`) or
     *  not (`false`)
     */
    event ChildTransferred(
        uint256 indexed tokenId,
        uint256 childIndex,
        address indexed childAddress,
        uint256 indexed childId,
        bool fromPending,
        bool toZero
    );

    /**
     * @notice The core child token struct, holding the information about the child tokens.
     * @return tokenId ID of the child token in the child token's collection smart contract
     * @return contractAddress Address of the child token's smart contract
     */
    struct Child {
        uint256 tokenId;
        address contractAddress;
    }

    /**
     * @notice Used to retrieve the *root* owner of a given token.
     * @dev The *root* owner of the token is an externally owned account (EOA). If the given token is child of another
     *  NFT, this will return an EOA address. Otherwise, if the token is owned by an EOA, this EOA wil be returned.
     * @param tokenId ID of the token for which the *root* owner has been retrieved
     * @return owner The *root* owner of the token
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @notice Used to retrieve the immediate owner of the given token.
     * @dev If the immediate owner is another token, the address returned, should be the one of the parent token's
     *  collection smart contract.
     * @param tokenId ID of the token for which the RMRK owner is being retrieved
     * @return Address of the given token's owner
     * @return The ID of the parent token. Should be `0` if the owner is an externally owned account
     * @return The boolean value signifying whether the owner is an NFT or not
     */
    function directOwnerOf(
        uint256 tokenId
    ) external view returns (address, uint256, bool);

    /**
     * @notice Used to burn a given token.
     * @dev When a token is burned, all of its child tokens are recursively burned as well.
     * @dev When specifying the maximum recursive burns, the execution will be reverted if there are more children to be
     *  burned.
     * @dev Setting the `maxRecursiveBurn` value to 0 will only attempt to burn the specified token and revert if there
     *  are any child tokens present.
     * @dev The approvals are cleared when the token is burned.
     * @dev Requirements:
     *
     *  - `tokenId` must exist.
     * @dev Emits a {Transfer} event.
     * @param tokenId ID of the token to burn
     * @param maxRecursiveBurns Maximum number of tokens to recursively burn
     * @return Number of recursively burned children
     */
    function burn(
        uint256 tokenId,
        uint256 maxRecursiveBurns
    ) external returns (uint256);

    /**
     * @notice Used to add a child token to a given parent token.
     * @dev This adds the child token into the given parent token's pending child tokens array.
     * @dev Requirements:
     *
     *  - `directOwnerOf` on the child contract must resolve to the called contract.
     *  - the pending array of the parent contract must not be full.
     * @param parentId ID of the parent token to receive the new child token
     * @param childId ID of the new proposed child token
     * @param data Additional data with no specified format
     */
    function addChild(
        uint256 parentId,
        uint256 childId,
        bytes memory data
    ) external;

    /**
     * @notice Used to accept a pending child token for a given parent token.
     * @dev This moves the child token from parent token's pending child tokens array into the active child tokens
     *  array.
     * @param parentId ID of the parent token for which the child token is being accepted
     * @param childIndex Index of a child tokem in the given parent's pending children array
     * @param childAddress Address of the collection smart contract of the child token expected to be located at the
     *  specified index of the given parent token's pending children array
     * @param childId ID of the child token expected to be located at the specified index of the given parent token's
     *  pending children array
     */
    function acceptChild(
        uint256 parentId,
        uint256 childIndex,
        address childAddress,
        uint256 childId
    ) external;

    /**
     * @notice Used to reject all pending children of a given parent token.
     * @dev Removes the children from the pending array mapping.
     * @dev This does not update the ownership storage data on children. If necessary, ownership can be reclaimed by the
     *  rootOwner of the previous parent.
     * @dev Requirements:
     *
     * Requirements:
     *
     * - `parentId` must exist
     * @param parentId ID of the parent token for which to reject all of the pending tokens.
     * @param maxRejections Maximum number of expected children to reject, used to prevent from rejecting children which
     *  arrive just before this operation.
     */
    function rejectAllChildren(
        uint256 parentId,
        uint256 maxRejections
    ) external;

    /**
     * @notice Used to transfer a child token from a given parent token.
     * @dev When transferring a child token, the owner of the token is set to `to`, or is not updated in the event of
     *  `to` being the `0x0` address.
     * @param tokenId ID of the parent token from which the child token is being transferred
     * @param to Address to which to transfer the token to
     * @param destinationId ID of the token to receive this child token (MUST be 0 if the destination is not a token)
     * @param childIndex Index of a token we are transferring, in the array it belongs to (can be either active array or
     *  pending array)
     * @param childAddress Address of the child token's collection smart contract.
     * @param childId ID of the child token in its own collection smart contract.
     * @param isPending A boolean value indicating whether the child token being transferred is in the pending array of
     *  the parent token (`true`) or in the active array (`false`)
     * @param data Additional data with no specified format, sent in call to `_to`
     */
    function transferChild(
        uint256 tokenId,
        address to,
        uint256 destinationId,
        uint256 childIndex,
        address childAddress,
        uint256 childId,
        bool isPending,
        bytes memory data
    ) external;

    /**
     * @notice Used to retrieve the active child tokens of a given parent token.
     * @dev Returns array of Child structs existing for parent token.
     * @dev The Child struct consists of the following values:
     *  [
     *      tokenId,
     *      contractAddress
     *  ]
     * @param parentId ID of the parent token for which to retrieve the active child tokens
     * @return An array of Child structs containing the parent token's active child tokens
     */
    function childrenOf(
        uint256 parentId
    ) external view returns (Child[] memory);

    /**
     * @notice Used to retrieve the pending child tokens of a given parent token.
     * @dev Returns array of pending Child structs existing for given parent.
     * @dev The Child struct consists of the following values:
     *  [
     *      tokenId,
     *      contractAddress
     *  ]
     * @param parentId ID of the parent token for which to retrieve the pending child tokens
     * @return An array of Child structs containing the parent token's pending child tokens
     */
    function pendingChildrenOf(
        uint256 parentId
    ) external view returns (Child[] memory);

    /**
     * @notice Used to retrieve a specific active child token for a given parent token.
     * @dev Returns a single Child struct locating at `index` of parent token's active child tokens array.
     * @dev The Child struct consists of the following values:
     *  [
     *      tokenId,
     *      contractAddress
     *  ]
     * @param parentId ID of the parent token for which the child is being retrieved
     * @param index Index of the child token in the parent token's active child tokens array
     * @return A Child struct containing data about the specified child
     */
    function childOf(
        uint256 parentId,
        uint256 index
    ) external view returns (Child memory);

    /**
     * @notice Used to retrieve a specific pending child token from a given parent token.
     * @dev Returns a single Child struct locating at `index` of parent token's active child tokens array.
     * @dev The Child struct consists of the following values:
     *  [
     *      tokenId,
     *      contractAddress
     *  ]
     * @param parentId ID of the parent token for which the pending child token is being retrieved
     * @param index Index of the child token in the parent token's pending child tokens array
     * @return A Child struct containting data about the specified child
     */
    function pendingChildOf(
        uint256 parentId,
        uint256 index
    ) external view returns (Child memory);

    /**
     * @notice Used to transfer the token into another token.
     * @param from Address of the direct owner of the token to be transferred
     * @param to Address of the receiving token's collection smart contract
     * @param tokenId ID of the token being transferred
     * @param destinationId ID of the token to receive the token being transferred
     * @param data Additional data with no specified format, sent in the addChild call
     */
    function nestTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        uint256 destinationId,
        bytes memory data
    ) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;
import {claimNftByItemId, NftByItemId} from "../interfaces/IEvrlootMissions.sol";

struct RequestedToken {
    address contractAddress;
    uint256 tokenId;
}

struct RollableAssets {
    uint64[] assetIds;
    uint16 itemId;
}

struct IdentifyQueueItem {
    address contractAddress;
    uint16 poolId;
    uint256 tokenId;
}

struct IdentifyQueueUnclaimedItem {
    address contractAddress;
    uint16 poolId;
    uint16 amount;
    bool doMint;
}

interface IIdentify {
    event RequestRNG(address playerAddress, uint256 tokenId);
    event IdentifiedNewToken(
        address playerAddress,
        address contractAddress,
        uint256 tokenId,
        uint16 itemId,
        uint64[] assetIds
    );
    event IdentifiedToken(
        address contractAddress,
        uint256 tokenId,
        uint16 itemId,
        uint64[] assetIds
    );

    event IdentifiedUnclaimed(
        address playerAddress,
        address contractAddress,
        uint16 itemId
    );

    event UpdatedRollableAssets(address contractAddress, uint16 poolId);

    function identifyRmrkTokens(
        RequestedToken[] calldata requestedTokens
    ) external payable;

    function identifyUnclaimedTokens(
        claimNftByItemId[] calldata requestedUnclaimedTokens,
        bool[] calldata doMint
    ) external payable;

    function isIdentifiable(
        address contractAddress,
        uint256 tokenId
    ) external view returns (bool);
}

File 31 of 49 : IEvrlootMissions.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

/**
 * @notice Struct used for claiming rewards (resources or nfts).
 * @param  id is the id of the reward to claim
 * @param  index is the index of the reward to claim
 * @param  amount is the amount of the reward to claim
 */
struct claimResource {
    uint16 id;
    uint16 amount;
}
struct claimNftByItemId {
    uint16 id;
    address contractAddress;
    uint16 amount;
}
struct claimItem {
    uint16 id;
    uint16 index;
    uint16 amount;
}
/**
 * @notice NFT Information used for supplying nfts to startMission function
 * @dev The player must provide approval for the contract to transfer the NFT
 * @param contractAddress is the address of the NFT contract
 * @param tokenId is the token id of the NFT
 */
struct InputNftData {
    address contractAddress;
    uint256 tokenId;
}

/**
 * @notice Each mission contains one or multiple NFT rewards with preset roll characteristics
 * @param contractAddress is the address of the NFT contract
 * @param itemId is the mint index of the NFT
 * @param amount is the amount of the NFT to mint
 * @param rollChance rollChance/100_000 chance of rolling this reward
 * @param maxRolls Player rolls until they fail, or up to maxRolls
 * @param attributeMultipliers array of 16 uint16s multiplied by soul attributes to determine roll benefit
 */
struct NFTRewardChance {
    // 2 slots total
    address contractAddress; // 160
    uint16 itemId; // 176
    uint16 amount; // 192
    uint32 rollChance; // 224
    uint16 maxRolls; // 240
    uint8 experienceBenefit; // 248
    uint256 attributeMultipliers; // 256
}

/**
 * @notice Each mission contains one or multiple NFT rewards with preset roll characteristics
 * @param contractAddress is the address of the NFT contract
 * @param itemId is the mint index of the NFT
 * @param amount is the amount of the NFT to mint
 * @param rollChance rollChance/100_000 chance of rolling this reward
 * @param maxRolls Player rolls until they fail, or up to maxRolls
 * @param attributeMultipliers array of 16 uint16s multiplied by soul attributes to determine roll benefit
 */
struct NFTRewardChanceV2 {
    // 2 slots total
    address contractAddress; // 160
    uint16 itemId; // 176
    uint8 amount; // 184
    uint24 rollChance; // 208
    uint8 maxRolls; // 216
    uint8 experienceBenefit; // 224
    uint16 timeMultiplier; // 240
    uint16 rarityDivisor; // 256
    uint256 attributeMultipliers; // 256
}
/**
 * @notice Each mission contains one or multiple NFT rewards with preset roll characteristics
 * @param contractAddress is the address of the NFT contract
 * @param itemId is the mint index of the NFT
 * @param amount is the amount of the NFT to mint
 * @param rollChance rollChance/100_000 chance of rolling this reward
 * @param maxRolls Player rolls until they fail, or up to maxRolls
 * @param experienceBenefit Larger value increases the effect of experience on roll chance
 * @param timeMultiplier Larger time multiplier increases the total chance of rolling the item
 * @param rarityDivisor Larger value decreases the chance of rolling higher rarity items
 * @param attributeMultipliers array of 25 6bit values multiplied by soul attributes to determine roll benefit
 * @param groupId if multiple rewards have the same groupId, only one can be won
 * @param specialId active specialId required to enable this reward -- use mappining of specialIds to bools
 * @param hourStart hour of the day that the reward becomes available
 * @param hourDuration duration in hours that the reward is available after hourStart
 * @param dowStart day of the week that the reward becomes available
 * @param dowDuration duration in days that the reward is available after dowStart
 * @param monthStart month of the year that the reward becomes available
 * @param monthDuration duration in months that the reward is available after monthStart
 * @param spareN 5 spare uint8s fills remainder of 2nd slot
 */
struct NFTRewardChanceV3 {
    // still 2 slots total
    address contractAddress; // 160
    uint16 itemId; // 176
    uint8 amount; // 184
    uint24 rollChance; // 208
    uint8 maxRolls; // 216
    uint8 experienceBenefit; // 224
    uint16 timeMultiplier; // 240
    uint16 rarityDivisor; // 256
    uint152 attributeMultipliers; // 152
    uint8 groupId;
    uint8 specialId;
    uint8 hourStart;
    uint8 hourDuration;
    uint8 dowStart;
    uint8 dowDuration;
    uint8 monthStart;
    uint8 monthDuration; // 216
    uint8 spare1; // 224
    uint8 spare2; // 232
    uint8 spare3; // 240
    uint8 spare4; // 248
    uint8 spare5; // 256
}

/**
 * @notice NFT Information use for minting and mission requirements
 * @param contractAddress is the address of the NFT contract
 * @param itemId is the mint index of the NFT
 * @param amount is the amount of the NFT to mint
 */
struct NftByItemId {
    // 1 slot
    address contractAddress; // 160
    uint16 itemId;
    uint16 amount; // 208
}

/**
 * @notice NFT Information use for mission requirements
 * @param contractAddress address of supported NFT contracts
 * @param itemId is the mint index of the NFT
 * @param amount is the amount of the NFT to mint
 */
struct NftByItemIdV2 {
    address[] contractAddress;
    uint16 itemId;
    uint16 amount;
}

struct NftByItemIdV3 {
    address contractAddress;
    uint16 itemId;
    uint16 amount;
    uint8 groupId; // if 0 then not grouped (AND). If >0 and matching another req item then its an OR, otherwise AND
}

/**
 * @notice Earned (already rolled) resource rewards
 * @param resourceId is the id of the resource
 * @param amount is the amount of the resource
 */
struct ResourceData {
    uint16 resourceId;
    uint16 amount;
}

/**
 * @notice Old version of ResourceRewardChance
 */
struct ResourceRewardChance {
    uint16 resourceId; //16
    uint16 amount; //32
    uint32 rollChance; //56
    uint8 maxRolls; //64
    uint8 experienceBenefit; // 72
    uint256 attributeMultipliers; // 256
}

/**
 * @notice Old version of ResourceRewardChance
 */
struct ResourceRewardChanceV2 {
    uint16 resourceId; //16
    uint8 amount; //24
    uint24 rollChance; //48
    uint8 maxRolls; //56
    uint8 experienceBenefit; // 64
    uint16 timeMultiplier; // 80
    uint16 rarityDivisor; // 96
    uint256 attributeMultipliers; // 256
}
/**
 * @notice Each mission contains one or multiple Resource rewards with preset roll characteristics
 * @param resourceId is the id of the resource
 * @param amount is the amount of the resource
 * @param rollChance rollChance/100_000 chance of rolling this reward
 * @param maxRolls Player rolls until they fail, or up to maxRolls
 * @param experienceBenefit Larger value increases the effect of experience on roll chance
 * @param timeMultiplier Larger time multiplier increases the total chance of rolling the item
 * @param rarityDivisor Larger value decreases the chance of rolling higher rarity items
 * @param attributeMultipliers Multiplier for each attribute -- stores up to 25 values of 2^6-1 (63) each
 * @dev note that attributeMultipliers
 */
struct ResourceRewardChanceV3 {
    uint16 resourceId; //16
    uint8 amount; //24
    uint24 rollChance; //48
    uint8 maxRolls; //56
    uint8 experienceBenefit; // 64
    uint16 timeMultiplier; // 80
    uint16 rarityDivisor; // 96
    uint152 attributeMultipliers; // 248
    uint8 specialId; // 256 active specialId required to enable this reward -- use mappining of specialIds to bools
}

/**
 * @notice Specific reward amount for an activity associated to a mission.
 * @dev ActivityRewards are stored by soul tokenId and incremented following mission completion.
 * @param enabled is a bool to enable/disable the mission
 * @param blockDuration is the duration of the mission in blocks
 * @param activityId is the id of the activity effected by this mission
 * @param baseExperience is the base experience reward for completing the mission
 * @param collectionId is the id of the supported collection within the staking contract
 */
struct ActivityData {
    bool enabled;
    uint32 blockDuration;
    uint16 activityId;
    uint32 baseExperience;
    uint32 collectionId; //120
    uint256 attributeMultipliers; // 256
}

/**
 * @notice Specific reward amount for an activity associated to a mission.
 * @dev ActivityRewards are stored by soul tokenId and incremented following mission completion.
 * @param enabled is a bool to enable/disable the mission
 * @param blockDuration is the duration of the mission in blocks
 * @param activityId is the id of the activity effected by this mission
 * @param baseExperience is the base experience reward for completing the mission
 * @param collectionId is the id of the supported collection within the staking contract
 */
struct ActivityDataV2 {
    bool enabled; //8
    uint32 durationSeconds; //40
    uint16 activityId; // 56
    uint32 baseExperience; // 88
    uint32 collectionId; //120
    uint32 blockWait; // 152
    uint32 spare1; // 184 //
    uint32 spare2; // 216
    uint32 requiresRng; // 240
    uint8 identifyNfts; // 256
    uint256 attributeMultipliers; // 256
}
/**
     * @notice PlayerMission struct
     * @dev Only the Most recent PlayerMission is stored. It is mapped to the soul tokenId which created it.
     * @param missionId is the id of the mission.
     * @param playerAddress is the address of the player who started the mission.
     * @param endBlock is the block the playerMission completes.

     */
struct PlayerMission {
    uint16 missionId; // 16
    address playerAddress; // 176
    uint32 endTimestamp; // 208
    uint32 rngIndex; // 240
}

interface IEvrlootMissions {
    //events
    event MissionAdded(uint256 indexed missionId);
    event MissionV3Added(uint256 indexed missionId);
    event MissionV4Added(uint256 indexed missionId);
    event MissionStarted(
        uint256 indexed tokenId,
        uint16 indexed missionId,
        uint256 rngIndex
    );
    event MissionEnded(uint256 indexed tokenId, uint16 indexed missionId);
    event MissionRoll(uint256 rngIndex, uint256 rolledValue);
    event MissionReward(
        uint256 indexed tokenId,
        uint16 indexed missionId,
        uint16 activityId,
        uint256 experienceGained,
        NftByItemId[] nftRewards,
        ResourceData[] resourceRewards
    );
    event CraftedNewToken(
        uint256 indexed estraTokenId,
        uint16 indexed missionId,
        address contractAddress,
        uint256 tokenId,
        uint16 itemId,
        uint64[] assetIds
    );
    event TradeMission(
        uint256 indexed tokenId,
        uint16 indexed missionId,
        NftByItemId[] nftRewards,
        ResourceData[] resourceRewards
    );
    event TradeMissionV2(
        uint256 indexed tokenId,
        uint16 indexed missionId,
        uint16 activityId,
        uint256 experienceGained,
        NftByItemId[] nftRewards,
        ResourceData[] resourceRewards
    );
    // event TradeMissionV2(
    //     uint256 indexed tokenId,
    //     uint16 indexed missionId,
    //     uint16 activityId,
    //     uint256 experienceGained,
    //     NftByItemId[] nftRewards,
    //     ResourceData[] resourceRewards
    // );
}

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

error ZeroAddress();

struct MetaStorage {
    address _trustedForwarder;
}

library LibMeta {
    bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
        keccak256(
            bytes(
                "EIP712Domain(string name,string version,uint256 salt,address verifyingContract)"
            )
        );
    bytes32 constant METASTORAGE_STRUCT_POSITION =
        keccak256("evrloot.metastorage.v1");

    function metaStorage() internal pure returns (MetaStorage storage es) {
        bytes32 position = METASTORAGE_STRUCT_POSITION;
        assembly {
            es.slot := position
        }
        return es;
    }

    function domainSeparator(
        string memory name,
        string memory version
    ) internal view returns (bytes32 domainSeparator_) {
        domainSeparator_ = keccak256(
            abi.encode(
                EIP712_DOMAIN_TYPEHASH,
                keccak256(bytes(name)),
                keccak256(bytes(version)),
                getChainID(),
                address(this)
            )
        );
    }

    function getChainID() internal view returns (uint256 id) {
        assembly {
            id := chainid()
        }
    }

    function getTrustedForwarder() public view returns (address forwarder) {
        MetaStorage storage es = LibMeta.metaStorage();
        return es._trustedForwarder;
    }

    function _setTrustedForwarder(address _forwarder) internal {
        MetaStorage storage es = LibMeta.metaStorage();
        es._trustedForwarder = _forwarder;
    }

    function isTrustedForwarder(address forwarder) public view returns (bool) {
        if (forwarder == address(0)) revert ZeroAddress();

        MetaStorage storage es = LibMeta.metaStorage();
        return forwarder == es._trustedForwarder;
    }

    function msgSender() internal view returns (address sender_) {
        if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
            bytes memory array = msg.data;
            uint256 index = msg.data.length;
            assembly {
                // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
                sender_ := and(
                    mload(add(array, index)),
                    0xffffffffffffffffffffffffffffffffffffffff
                )
                //     assembly {
                //     sender_ := shr(96,calldataload(sub(calldatasize(),20)))
                // }
            }
        } else {
            sender_ = msg.sender;
        }
    }

    function msgData() internal view returns (bytes calldata ret) {
        if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
            return msg.data[0:msg.data.length - 20];
        } else {
            return msg.data;
        }
    }
}

File 33 of 49 : IDiamond.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/

interface IDiamond {
    enum FacetCutAction {Add, Replace, Remove}
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

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

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/

import {IDiamond} from "./IDiamond.sol";
import {IERC165Updater} from "./IERC165Updater.sol";

interface IDiamondCut is IDiamond, IERC165Updater {
    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(
        FacetCut[] calldata _diamondCut,
        address _init,
        bytes calldata _calldata
    ) external;
}

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

/**
 * @title IERC165Updater
 * @author Multiple
 * @notice An extension of ERC165 Standard Interface Detection that allows contracts to add and remove supported interfaces.
 *
 * Users can check for interface support via `supportsInterface(bytes4 interfaceID)` as defined in ERC165. Users can add or remove interface support via [`updateSupportedInterfaces()`](#updatesupportedinterfaces).
 */
interface IERC165Updater {
    /// @notice Emitted when support for an interface is updated.
    event InterfaceSupportUpdated(bytes4 indexed interfaceID, bool supported);

    /**
     * @notice Adds or removes supported interfaces.
     * @dev Add access control in implementation.
     * @param interfaceIDs The list of interfaces to update.
     * @param support The list of true to signal support, false otherwise.
     */
    function updateSupportedInterfaces(
        bytes4[] calldata interfaceIDs,
        bool[] calldata support
    ) external payable;
}

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

import {NftByItemId, ResourceData} from "../../diamond/interfaces/IEvrlootMissions.sol";

interface IGameDiamond {
    function lookupEstraTokenId(
        address contractAddress,
        uint256 tokenId
    ) external view returns (uint256, address);

    function transferUnclaimedResourcesToMarket(
        address from,
        ResourceData[] memory resources
    ) external;

    function transferUnclaimedNftsToMarket(
        address from,
        NftByItemId[] memory unclaimedNfts
    ) external;

    function transferUnclaimedResourcesFromMarket(
        address to,
        ResourceData[] memory resources
    ) external;

    function transferUnclaimedNftsFromMarket(
        address to,
        NftByItemId[] memory unclaimedNfts
    ) external;
}

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

import {LibMarketDiamond} from "./LibMarketDiamond.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./MarketErrors.sol";
import "../../Errors.sol";
import {LibMeta} from "../../diamond/libraries/LibMeta.sol";
import {EvrlootResources} from "../../Resources/EvrlootResources.sol";
import {TokenEscrow} from "../../erc20/EscroContract.sol";

struct AppStorage {
    string name;
    bool paused;
    bool reentrantLock;
    /* ====== Transaction Signing (EIP 712) (future) ====== */
    bytes32 domainSeparator;
    mapping(address => uint256) metaNonces;
    /* ====== Game Contract (for managing trades with unclaimed rewards) ====== */
    address gameContractAddress;
    /* ====== Airnode Oracle Callback address (future, pending)====== */
    address airnodeAddress;
    /* ====== Resource Contract ====== */
    EvrlootResources evrlootResourceContract;
    /* ====== Token Escrow Contract ====== */
    TokenEscrow escrowedTokenContract;
    /* ====== Royalty address ====== */
    address royaltyAddress;
}

library LibMarketAppStorage {
    function diamondStorage() internal pure returns (AppStorage storage ds) {
        assembly {
            ds.slot := 0
        }
    }
}

/** ============ Modifiers ============ */

contract Modifiers {
    AppStorage internal s;

    modifier onlyOwner() {
        LibMarketDiamond.enforceIsContractOwner();
        _;
    }

    modifier onlyOwnerOrBackend() {
        LibMarketDiamond.enforceIsContractOwnerOrBackendAddress();
        _;
    }

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

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

    /**
     * @dev Make a function callable only by the QRNG contract
     */
    modifier onlyAirNode() {
        if (msg.sender != s.airnodeAddress) revert NotAirNode();
        _;
    }

    modifier NonReentrant() {
        if (s.reentrantLock == true) revert ReEntrancyLock();
        s.reentrantLock = true;
        _;
        s.reentrantLock = false;
    }
}

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

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
import {IDiamond} from "../interfaces/IDiamond.sol";
import {IDiamondCut} from "../interfaces/IDiamondCut.sol";

// Remember to add the loupe functions from DiamondLoupeFacet to the diamond.
// The loupe functions are required by the EIP2535 Diamonds standard

error NoSelectorsGivenToAdd();
error NotContractOwner(address _user, address _contractOwner);
error NotPermitted(
    address _user,
    address _contractOwner,
    address _backendAddress
);
error NoSelectorsProvidedForFacetForCut(address _facetAddress);
error CannotAddSelectorsToZeroAddress(bytes4[] _selectors);
error NoBytecodeAtAddress(address _contractAddress, string _message);
error IncorrectFacetCutAction(uint8 _action);
error CannotAddFunctionToDiamondThatAlreadyExists(bytes4 _selector);
error CannotReplaceFunctionsFromFacetWithZeroAddress(bytes4[] _selectors);
error CannotReplaceImmutableFunction(bytes4 _selector);
error CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(
    bytes4 _selector
);
error CannotReplaceFunctionThatDoesNotExists(bytes4 _selector);
error RemoveFacetAddressMustBeZeroAddress(address _facetAddress);
error CannotRemoveFunctionThatDoesNotExist(bytes4 _selector);
error CannotRemoveImmutableFunction(bytes4 _selector);
error InitializationFunctionReverted(
    address _initializationContractAddress,
    bytes _calldata
);

library LibMarketDiamond {
    bytes32 constant DIAMOND_STORAGE_POSITION =
        keccak256("diamond.standard.diamond.storage");

    struct FacetAddressAndSelectorPosition {
        address facetAddress;
        uint16 selectorPosition;
    }

    struct DiamondStorage {
        // function selector => facet address and selector position in selectors array
        mapping(bytes4 => FacetAddressAndSelectorPosition) facetAddressAndSelectorPosition;
        bytes4[] selectors;
        mapping(bytes4 => bool) supportedInterfaces;
        // owner of the contract
        address contractOwner;
        // backend address
        address backendAddress;
    }

    function diamondStorage()
        internal
        pure
        returns (DiamondStorage storage ds)
    {
        bytes32 position = DIAMOND_STORAGE_POSITION;
        assembly {
            ds.slot := position
        }
    }

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

    function setContractOwner(address _newOwner) internal {
        DiamondStorage storage ds = diamondStorage();
        address previousOwner = ds.contractOwner;
        ds.contractOwner = _newOwner;
        emit OwnershipTransferred(previousOwner, _newOwner);
    }

    function setBackend(address _newBackendAddress) internal {
        DiamondStorage storage ds = diamondStorage();
        ds.backendAddress = _newBackendAddress;
    }

    function backend() internal view returns (address backend_) {
        backend_ = diamondStorage().backendAddress;
    }

    function contractOwner() internal view returns (address contractOwner_) {
        contractOwner_ = diamondStorage().contractOwner;
    }

    function enforceIsContractOwner() internal view {
        if (msg.sender != diamondStorage().contractOwner) {
            revert NotContractOwner(msg.sender, diamondStorage().contractOwner);
        }
    }

    function enforceIsContractOwnerOrBackendAddress() internal view {
        DiamondStorage storage ds = diamondStorage();
        if (msg.sender != ds.backendAddress && msg.sender != ds.contractOwner) {
            revert NotPermitted(
                msg.sender,
                diamondStorage().contractOwner,
                diamondStorage().backendAddress
            );
        }
    }

    event DiamondCut(
        IDiamondCut.FacetCut[] _diamondCut,
        address _init,
        bytes _calldata
    );

    // Internal function version of diamondCut
    function diamondCut(
        IDiamondCut.FacetCut[] memory _diamondCut,
        address _init,
        bytes memory _calldata
    ) internal {
        for (
            uint256 facetIndex;
            facetIndex < _diamondCut.length;
            facetIndex++
        ) {
            bytes4[] memory functionSelectors = _diamondCut[facetIndex]
                .functionSelectors;
            address facetAddress = _diamondCut[facetIndex].facetAddress;
            if (functionSelectors.length == 0) {
                revert NoSelectorsProvidedForFacetForCut(facetAddress);
            }
            IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
            if (action == IDiamond.FacetCutAction.Add) {
                addFunctions(facetAddress, functionSelectors);
            } else if (action == IDiamond.FacetCutAction.Replace) {
                replaceFunctions(facetAddress, functionSelectors);
            } else if (action == IDiamond.FacetCutAction.Remove) {
                removeFunctions(facetAddress, functionSelectors);
            } else {
                revert IncorrectFacetCutAction(uint8(action));
            }
        }
        emit DiamondCut(_diamondCut, _init, _calldata);
        initializeDiamondCut(_init, _calldata);
    }

    function addFunctions(
        address _facetAddress,
        bytes4[] memory _functionSelectors
    ) internal {
        if (_facetAddress == address(0)) {
            revert CannotAddSelectorsToZeroAddress(_functionSelectors);
        }
        DiamondStorage storage ds = diamondStorage();
        uint16 selectorCount = uint16(ds.selectors.length);
        enforceHasContractCode(
            _facetAddress,
            "LibDiamondCut: Add facet has no code"
        );
        for (
            uint256 selectorIndex;
            selectorIndex < _functionSelectors.length;
            selectorIndex++
        ) {
            bytes4 selector = _functionSelectors[selectorIndex];
            address oldFacetAddress = ds
                .facetAddressAndSelectorPosition[selector]
                .facetAddress;
            if (oldFacetAddress != address(0)) {
                revert CannotAddFunctionToDiamondThatAlreadyExists(selector);
            }
            ds.facetAddressAndSelectorPosition[
                    selector
                ] = FacetAddressAndSelectorPosition(
                _facetAddress,
                selectorCount
            );
            ds.selectors.push(selector);
            selectorCount++;
        }
    }

    function replaceFunctions(
        address _facetAddress,
        bytes4[] memory _functionSelectors
    ) internal {
        DiamondStorage storage ds = diamondStorage();
        if (_facetAddress == address(0)) {
            revert CannotReplaceFunctionsFromFacetWithZeroAddress(
                _functionSelectors
            );
        }
        enforceHasContractCode(
            _facetAddress,
            "LibDiamondCut: Replace facet has no code"
        );
        for (
            uint256 selectorIndex;
            selectorIndex < _functionSelectors.length;
            selectorIndex++
        ) {
            bytes4 selector = _functionSelectors[selectorIndex];
            address oldFacetAddress = ds
                .facetAddressAndSelectorPosition[selector]
                .facetAddress;
            // can't replace immutable functions -- functions defined directly in the diamond in this case
            if (oldFacetAddress == address(this)) {
                revert CannotReplaceImmutableFunction(selector);
            }
            if (oldFacetAddress == _facetAddress) {
                revert CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(
                    selector
                );
            }
            if (oldFacetAddress == address(0)) {
                revert CannotReplaceFunctionThatDoesNotExists(selector);
            }
            // replace old facet address
            ds
                .facetAddressAndSelectorPosition[selector]
                .facetAddress = _facetAddress;
        }
    }

    function removeFunctions(
        address _facetAddress,
        bytes4[] memory _functionSelectors
    ) internal {
        DiamondStorage storage ds = diamondStorage();
        uint256 selectorCount = ds.selectors.length;
        if (_facetAddress != address(0)) {
            revert RemoveFacetAddressMustBeZeroAddress(_facetAddress);
        }
        for (
            uint256 selectorIndex;
            selectorIndex < _functionSelectors.length;
            selectorIndex++
        ) {
            bytes4 selector = _functionSelectors[selectorIndex];
            FacetAddressAndSelectorPosition
                memory oldFacetAddressAndSelectorPosition = ds
                    .facetAddressAndSelectorPosition[selector];
            if (oldFacetAddressAndSelectorPosition.facetAddress == address(0)) {
                revert CannotRemoveFunctionThatDoesNotExist(selector);
            }

            // can't remove immutable functions -- functions defined directly in the diamond
            if (
                oldFacetAddressAndSelectorPosition.facetAddress == address(this)
            ) {
                revert CannotRemoveImmutableFunction(selector);
            }
            // replace selector with last selector
            selectorCount--;
            if (
                oldFacetAddressAndSelectorPosition.selectorPosition !=
                selectorCount
            ) {
                bytes4 lastSelector = ds.selectors[selectorCount];
                ds.selectors[
                    oldFacetAddressAndSelectorPosition.selectorPosition
                ] = lastSelector;
                ds
                    .facetAddressAndSelectorPosition[lastSelector]
                    .selectorPosition = oldFacetAddressAndSelectorPosition
                    .selectorPosition;
            }
            // delete last selector
            ds.selectors.pop();
            delete ds.facetAddressAndSelectorPosition[selector];
        }
    }

    function initializeDiamondCut(
        address _init,
        bytes memory _calldata
    ) internal {
        if (_init == address(0)) {
            return;
        }
        enforceHasContractCode(
            _init,
            "LibDiamondCut: _init address has no code"
        );
        (bool success, bytes memory error) = _init.delegatecall(_calldata);
        if (!success) {
            if (error.length > 0) {
                // bubble up error
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(error)
                    revert(add(32, error), returndata_size)
                }
            } else {
                revert InitializationFunctionReverted(_init, _calldata);
            }
        }
    }

    function enforceHasContractCode(
        address _contract,
        string memory _errorMessage
    ) internal view {
        uint256 contractSize;
        assembly {
            contractSize := extcodesize(_contract)
        }
        if (contractSize == 0) {
            revert NoBytecodeAtAddress(_contract, _errorMessage);
        }
    }
}

File 39 of 49 : LibMarketStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {LibMarketDiamond} from "./LibMarketDiamond.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../../diamond/interfaces/IEvrlootIdentify.sol";
import "./MarketErrors.sol";
import "../../diamond/interfaces/IEvrlootMissions.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC6059} from "@rmrk-team/evm-contracts/contracts/RMRK/nestable/IERC6059.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import {AppStorage, LibMarketAppStorage} from "./LibMarketAppStorage.sol";
import {LibMeta} from "../../diamond/libraries/LibMeta.sol";
import {IEscro} from "../../erc20/IEscro.sol";
import {TokenEscrow} from "../../erc20/EscroContract.sol";
import {IGameDiamond} from '../interfaces/IGameDiamond.sol';

/** Marketplace Events */
event BidCreated(
        bytes32 bidId,
        NewBid bidData,
        uint256 offeredEther,
        address bidOwnerAddress
    );
event BidAccepted(bytes32 bidId, bytes32 tradeId);
event BidRejected(bytes32 bidId, bytes32 tradeId);
event BidWithdrawn(bytes32 bidId, bytes32 tradeId);  
event TradeCreated(
        bytes32 tradeId,
        NewTrade tradeData,
        address tradeOwnerAddress
    );
event TradeCancelled(bytes32 tradeId);
event WithdrawEscrow(
        address ownerAddress,
        NftByItemId[] unclaimedNfts,
        ResourceData[] unclaimedResources,
        NftByTokenId[] nfts,
        ResourceData[] resources,
        Erc20Token erc20Token,
        uint256 etherValue
    );

/** Marketplace storage structs */
struct NewTrade {
    NftByItemId[] unclaimedNfts;
    ResourceData[] unclaimedResources;
    NftByTokenId[] nfts;
    ResourceData[] resources;
    NftByItemId[] escrowedUnclaimedNfts;
    ResourceData[] escrowedUnclaimedResources;
    NftByTokenId[] escrowedNfts;
    ResourceData[] escrowedResources;
    Erc20Token buyOutErc20Token;
    uint256 buyOutEtherPrice; // wei
}

struct NewBid {
    bytes32 tradeId;
    NftByItemId[] unclaimedNfts;
    ResourceData[] unclaimedResources;
    NftByTokenId[] nfts;
    ResourceData[] resources;
    NftByItemId[] escrowedUnclaimedNfts;
    ResourceData[] escrowedUnclaimedResources;
    NftByTokenId[] escrowedNfts;
    ResourceData[] escrowedResources;
    Erc20Token offeredErc20Token;
    Erc20Token escrowedErc20Token;
    uint256 escrowedEtherValue; // wei
}

struct StoredTrade {
    address tradeOwnerAddress;
    uint32 creationBlock; // 192
    uint16 inclusionsBitmap; // 208 bitmap of included item types
    uint16 spare1; // 224
    uint16 spare2; // 240
    uint16 spare3; // 256
}

struct StoredBid {
    bytes32 tradeId; //256_
    address bidOwnerAddress; // 160
    uint32 creationBlock; // 192
    uint16 inclusionsBitmap; // 208 bitmap of included item types
    uint16 spare1; // 224
    uint16 spare2; // 240
    uint16 spare3; // 256
}

struct Erc20Token {
    address contractAddress;
    uint256 amount;
}
struct Erc1155Token {
    address contractAddress;
    uint256 tokenId;
    uint256 amount;
}
struct NftByTokenId {
    address contractAddress;
    uint256 tokenId;
}

/** Convenience bundle to avoid stack-too-depp */
struct BundledTradeIds {
    bytes32[] tradeIds;
    bytes32[] bidIds;
}

//inclusionsBitMap :
// Bits 1: has buyout ether price
// Bits 2: has buyout erc20 tokens
// Bits 3: has nft tokens
// Bits 4: has resource tokens
// Bits 5: has unclaimed nft tokens
// Bits 6: has unclaimed resource tokens
// Bits 7-16: spare
uint16 constant BUYOUT_ETHER_BIT = 1; //2**0
uint16 constant BUYOUT_ERC20_BIT = 2; //2**1
uint16 constant NFT_BIT = 4; //2**2
uint16 constant RESOURCE_BIT = 8; //2**3
uint16 constant UNCLAIMED_NFT_BIT = 16; //2**4
uint16 constant UNCLAIMED_RESOURCE_BIT = 32; //2**5

struct MarketStorage {
    bool paused;
    uint256 tradeCreationFee;
    uint256 tradeCompletionFeeRate; // As basis points 0-10000 (10000 = 100%)
    mapping(address => bool) supportedTokens;
    mapping(uint16 => bool) supportedResources;
    mapping(bytes32 => StoredTrade) trades;
    mapping(bytes32 => StoredBid) bids;
    mapping(bytes32 => bytes32[]) bidsByTradeId; // Note: To be deprecated in v2
    // Unclaimed Nfts
    mapping(bytes32 => NftByItemId[]) unclaimedNftsByTradeId;
    mapping(bytes32 => NftByItemId[]) unclaimedNftsByBidId;
    // Unclaimed Resources
    mapping(bytes32 => ResourceData[]) unclaimedResourcesByTradeId;
    mapping(bytes32 => ResourceData[]) unclaimedResourcesByBidId;
    // Nfts
    mapping(bytes32 => NftByTokenId[]) nftsByTradeId;
    mapping(bytes32 => NftByTokenId[]) nftsByBidId;
    // Erc1155 Resources
    mapping(bytes32 => ResourceData[]) resourcesByTradeId;
    mapping(bytes32 => ResourceData[]) resourcesByBidId;
    // Erc 20 tokens
    mapping(bytes32 => Erc20Token) erc20TokenByBidId;
    mapping(bytes32 => Erc20Token) erc20TokenByTradeId;
    // Ether buyouts/offers
    mapping(bytes32 => uint256) tradeBuyOutEtherPrice;
    mapping(bytes32 => uint256) etherByBidId;
    mapping(address => bytes32[]) tradesByTrader; // Note: To be deprecated in v2
    mapping(address => bytes32[]) bidsByBidder; // Note: To be deprecated in v2
    uint256 traderTradeCount;
    mapping(bytes32 => uint256) tradeCreationFeeHold;
    mapping(address => uint256) collectionFeePerNftItem;
    uint256 collectionFeePerResource;
    uint256 tradeCommissionRateBps;
    // Escrow Mapping stores escrowed nft data to player -- used to confirm escrowed nfts
    // Usage:
    //   unclaimedNft: keccek256(playerAddress,itemId) => amount
    //   nft: keccek256(playerAddress,contractAddress,tokenId) => 1
    //   resource: keccek256('RESOURCE',playerAddress,resourceId) => amount
    //   unclaimedResource: keccek256('UNCLAIMEDRESOURCE',playerAddress,resourceId) => amount
    mapping(bytes32 => uint256) escrowedNftsByHash;
    mapping(bytes32 => uint256) escrowedTokensByHash;
    mapping(address => uint256) escrowedEtherByAddress;
    mapping(address => uint256) tradersNonce;
    uint256 etherFeesCollected; // Total fees collected
    mapping(address => uint256) tokenFeesCollected;
}

library LibMarketStorage {
    bytes32 constant MARKETSTORAGE_STRUCT_POSITION =
        keccak256("evrloot.marketstorage.v1");

    function marketStorage() internal pure returns (MarketStorage storage ms) {
        bytes32 position = MARKETSTORAGE_STRUCT_POSITION;
        assembly {
            ms.slot := position
        }
        return ms;
    }

    /**
     * @notice Transfer bid items to participant
     * @dev Note: Calling function must clear the bid from storage
     * @param _toPlayerAddress The address to transfer to
     * @param _bid Stored bid data
     * @param bidId The ID of the bid
     */
    function _transferBidItemsToParticipant(
        address _toPlayerAddress,
        StoredBid memory _bid,
        bytes32 bidId,
        bool takeCommission
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        uint16 inclusionsBitmap = _bid.inclusionsBitmap;
        if (inclusionsBitmap & BUYOUT_ERC20_BIT != 0) {
            Erc20Token memory erc20Token = ms.erc20TokenByBidId[bidId];
            uint256 sellersTake;

            if (takeCommission == true) {
                uint256 _offeredTokenAmount = erc20Token.amount;
                uint256 tradeCommissionRateBps = ms.tradeCommissionRateBps;
                uint256 tradeCommission;
                unchecked {
                    tradeCommission = (_offeredTokenAmount * tradeCommissionRateBps) / 10_000;
                    sellersTake = _offeredTokenAmount - tradeCommission;
                }
                ms.tokenFeesCollected[erc20Token.contractAddress] += tradeCommission;
            } else {
                sellersTake = erc20Token.amount;
            }

            _clearEscrowedTokens(_bid.bidOwnerAddress, erc20Token, sellersTake);

            _transferEscrowedErcTokensToParticipant(
                _bid.bidOwnerAddress,
                _toPlayerAddress,
                erc20Token,
                sellersTake
            );
        }

        if (inclusionsBitmap & NFT_BIT != 0) {
            NftByTokenId[] memory nfts = ms.nftsByBidId[bidId];
            _clearEscrowedNfts(_bid.bidOwnerAddress, nfts);
            _transferNftsToParticipant(_toPlayerAddress, nfts);
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            ResourceData[] memory resources = ms.resourcesByBidId[bidId];
            _clearEscrowedResources(_bid.bidOwnerAddress, resources);
            _transferResourcesToParticipant(_toPlayerAddress, resources);
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            NftByItemId[] memory unclaimedNfts = ms.unclaimedNftsByBidId[bidId];
            _clearEscrowedUnclaimedNfts(_bid.bidOwnerAddress, unclaimedNfts);
            _transferUnclaimedNftsToParticipant(
                _toPlayerAddress,
                unclaimedNfts
            );
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            ResourceData[] memory unclaimedResources = ms
                .unclaimedResourcesByBidId[bidId];
            _clearEscrowedUnclaimedResources(
                _bid.bidOwnerAddress,
                unclaimedResources
            );
            _transferUnclaimedResourcesToParticipant(
                _toPlayerAddress,
                unclaimedResources
            );
        }

        // send ether value (if any)
        if (inclusionsBitmap & BUYOUT_ETHER_BIT != 0) {
            uint256 _etherByBidId = ms.etherByBidId[bidId];
            uint256 sellersTake;

            if (takeCommission == true) {
                uint256 tradeCommissionRateBps = ms.tradeCommissionRateBps;
                uint256 tradeCommission = (_etherByBidId * tradeCommissionRateBps) / 10000;

                unchecked {
                    ms.etherFeesCollected += tradeCommission;
                    sellersTake =
                        _etherByBidId -
                        tradeCommission;
                }
            } else {
                sellersTake = _etherByBidId;
            }

            _clearEscrowedEther(_bid.bidOwnerAddress, sellersTake);
            AppStorage storage s = LibMarketAppStorage.diamondStorage();
            s.escrowedTokenContract.retrieveEther(
                _bid.bidOwnerAddress, //from
                sellersTake,
                _toPlayerAddress //to
            );
        }
    }

    /**
     * @notice Transfer trade items to participant
     * @dev Note: Calling function must clear the trade from storage
     * @param _toPlayerAddress The address to transfer to
     * @param _trade Stored trade data
     * @param tradeId The ID of the trade
     */
    function _transferTradeItemsToParticipant(
        address _toPlayerAddress,
        StoredTrade memory _trade,
        bytes32 tradeId
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        uint16 inclusionsBitmap = _trade.inclusionsBitmap;

        if (inclusionsBitmap & NFT_BIT != 0) {
            NftByTokenId[] memory nfts = ms.nftsByTradeId[tradeId];
            _clearEscrowedNfts(_trade.tradeOwnerAddress, nfts);
            _transferNftsToParticipant(_toPlayerAddress, nfts);
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            ResourceData[] memory resources = ms.resourcesByTradeId[tradeId];

            _clearEscrowedResources(_trade.tradeOwnerAddress, resources);
            _transferResourcesToParticipant(_toPlayerAddress, resources);
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            NftByItemId[] memory unclaimedNfts = ms.unclaimedNftsByTradeId[
                tradeId
            ];
            _clearEscrowedUnclaimedNfts(
                _trade.tradeOwnerAddress,
                unclaimedNfts
            );
            _transferUnclaimedNftsToParticipant(
                _toPlayerAddress,
                unclaimedNfts
            );
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            ResourceData[] memory unclaimedResources = ms
                .unclaimedResourcesByTradeId[tradeId];
            _clearEscrowedUnclaimedResources(
                _trade.tradeOwnerAddress,
                unclaimedResources
            );
            _transferUnclaimedResourcesToParticipant(
                _toPlayerAddress,
                unclaimedResources
            );
        }
    }

    /**
     * @notice Transfer trade items to this contract (Escrow)
     * @param _trade Stored trade data
     * @param _newTrade New trade data
     */
    function _transferTradeItemsToContract(
        StoredTrade memory _trade,
        NewTrade memory _newTrade
    ) internal {
        uint16 inclusionsBitmap = _trade.inclusionsBitmap;

        if (inclusionsBitmap & NFT_BIT != 0) {
            _transferNftsToContract(_trade.tradeOwnerAddress, _newTrade.nfts);
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            _transferResourcesToContract(
                _trade.tradeOwnerAddress,
                _newTrade.resources
            );
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            _transferUnclaimedNftsToContract(
                _trade.tradeOwnerAddress,
                _newTrade.unclaimedNfts
            );
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            _transferUnclaimedResourcesToContract(
                _trade.tradeOwnerAddress,
                _newTrade.unclaimedResources
            );
        }
    }

    /**
     * @notice Transfer escrowed items back to participant
     * @dev Note: Calling function must clear the trade from storage
     * @param _toPlayerAddress The address to transfer to
     * @param unclaimedNfts The unclaimed NFTs to transfer
     * @param unclaimedResources The unclaimed resources to transfer
     * @param nfts The NFTs to transfer
     * @param resources The resources to transfer
     */
    function _transferEscrowedItemsToParticipant(
        address _toPlayerAddress,
        NftByItemId[] calldata unclaimedNfts,
        ResourceData[] calldata unclaimedResources,
        NftByTokenId[] calldata nfts,
        ResourceData[] calldata resources,
        Erc20Token calldata erc20Token,
        uint256 etherValue
    ) internal {
        if (nfts.length != 0) {
            _clearEscrowedNfts(_toPlayerAddress, nfts);
            _transferNftsToParticipant(_toPlayerAddress, nfts);
        }

        if (resources.length != 0) {
            _clearEscrowedResources(_toPlayerAddress, resources);
            _transferResourcesToParticipant(_toPlayerAddress, resources);
        }

        if (unclaimedNfts.length != 0) {
            _clearEscrowedUnclaimedNfts(_toPlayerAddress, unclaimedNfts);
            _transferUnclaimedNftsToParticipant(
                _toPlayerAddress,
                unclaimedNfts
            );
        }

        if (unclaimedResources.length != 0) {
            _clearEscrowedUnclaimedResources(
                _toPlayerAddress,
                unclaimedResources
            );
            _transferUnclaimedResourcesToParticipant(
                _toPlayerAddress,
                unclaimedResources
            );
        }
        if (erc20Token.amount != 0) {
            _clearEscrowedTokens(
                _toPlayerAddress,
                erc20Token,
                erc20Token.amount
            );
            _transferEscrowedErcTokensToParticipant(
                _toPlayerAddress,
                _toPlayerAddress,
                erc20Token,
                erc20Token.amount
            );
        }

        if (etherValue != 0) {
            _clearEscrowedEther(_toPlayerAddress, etherValue);
             AppStorage storage s = LibMarketAppStorage.diamondStorage();
            s.escrowedTokenContract.retrieveEther(
                _toPlayerAddress,
                etherValue,
                _toPlayerAddress
            );
        }
    }

    function _clearEscrowedEther(
        address ownerAddress,
        uint256 amount
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        uint256 existingEscrowed = ms.escrowedEtherByAddress[ownerAddress];
        if (existingEscrowed < amount) {
            revert InsufficientEscrowedEther();
        }

        ms.escrowedEtherByAddress[ownerAddress] = existingEscrowed - amount;
    }

    function _clearEscrowedTokens(
        address ownerAddress,
        Erc20Token memory erc20Token,
        uint256 amount
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        bytes32 hashEntry = keccak256(
            abi.encodePacked(ownerAddress, erc20Token.contractAddress)
        );
        uint256 existingEscrowed = ms.escrowedTokensByHash[hashEntry];
        if (existingEscrowed < amount) {
            revert InsufficientEscrowedTokens();
        }
        unchecked {
            ms.escrowedTokensByHash[hashEntry] = existingEscrowed - amount;
        }
    }

    function _clearEscrowedNfts(
        address ownerAddress,
        NftByTokenId[] memory nfts
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint256 i; i < nfts.length; ) {
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    ownerAddress,
                    nfts[i].contractAddress,
                    nfts[i].tokenId
                )
            );
            if (ms.escrowedNftsByHash[hashEntry] == 0) {
                revert NftNotEscrowed();
            }

            ms.escrowedNftsByHash[hashEntry] = 0;

            unchecked {
                ++i;
            }
        }
    }

    function _clearEscrowedResources(
        address ownerAddress,
        ResourceData[] memory resources
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint256 i; i < resources.length; ) {
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    ownerAddress,
                    "RESOURCES",
                    resources[i].resourceId
                )
            );
            uint256 existingEscrowed = ms.escrowedNftsByHash[hashEntry];

            if (existingEscrowed < resources[i].amount) {
                revert InsufficientEscrowedResource();
            }

            ms.escrowedNftsByHash[hashEntry] =
                existingEscrowed -
                resources[i].amount;

            unchecked {
                ++i;
            }
        }
    }

    function _clearEscrowedUnclaimedNfts(
        address ownerAddress,
        NftByItemId[] memory unclaimedNfts
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint256 i; i < unclaimedNfts.length; ) {
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    ownerAddress,
                    unclaimedNfts[i].contractAddress,
                    unclaimedNfts[i].itemId
                )
            );
            uint256 existingEscrowed = ms.escrowedNftsByHash[hashEntry];

            if (existingEscrowed < unclaimedNfts[i].amount) {
                revert InsufficientEscrowedUnclaimedNft();
            }

            ms.escrowedNftsByHash[hashEntry] =
                existingEscrowed -
                unclaimedNfts[i].amount;

            unchecked {
                ++i;
            }
        }
    }

    function _clearEscrowedUnclaimedResources(
        address ownerAddress,
        ResourceData[] memory unclaimedResources
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        for (uint256 i; i < unclaimedResources.length; ) {
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    ownerAddress,
                    "UNCLAIMEDRESOURCES",
                    unclaimedResources[i].resourceId
                )
            );
            uint256 existingEscrowed = ms.escrowedNftsByHash[hashEntry];

            if (existingEscrowed < unclaimedResources[i].amount) {
                revert InsufficientEscrowedResource();
            }

            ms.escrowedNftsByHash[hashEntry] =
                existingEscrowed -
                unclaimedResources[i].amount;

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Transfer bid items to contract address
     * @param _bid Stored bid data
     * @param _newBid New bid data
     */
    function _transferBidItemsToContract(
        StoredBid memory _bid,
        NewBid memory _newBid,
        uint256 etherValue
    ) internal {
        uint16 inclusionsBitmap = _bid.inclusionsBitmap;

        if (inclusionsBitmap & BUYOUT_ETHER_BIT != 0) {
            _transferEtherToEscrow(_bid.bidOwnerAddress, etherValue);
        }

        if (inclusionsBitmap & BUYOUT_ERC20_BIT != 0) {
            _transferErcTokensToContract(
                _bid.bidOwnerAddress,
                _newBid.offeredErc20Token
            );
        }

        if (inclusionsBitmap & NFT_BIT != 0) {
            _transferNftsToContract(_bid.bidOwnerAddress, _newBid.nfts);
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            _transferResourcesToContract(
                _bid.bidOwnerAddress,
                _newBid.resources
            );
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            _transferUnclaimedNftsToContract(
                _bid.bidOwnerAddress,
                _newBid.unclaimedNfts
            );
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            _transferUnclaimedResourcesToContract(
                _bid.bidOwnerAddress,
                _newBid.unclaimedResources
            );
        }
    }

    function _transferEtherToEscrow(address from, uint256 amount) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        s.escrowedTokenContract.storeEther{value: amount}(from);
        uint256 existingEscrowed = ms.escrowedEtherByAddress[from];
        ms.escrowedEtherByAddress[from] = existingEscrowed + amount;
    }

    function _transferErcTokensToContract(
        address bidOwner,
        Erc20Token memory erc20Token
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        s.escrowedTokenContract.storeTokens(
            bidOwner,
            erc20Token.contractAddress,
            erc20Token.amount
        );
        bytes32 hashEntry = keccak256(
            abi.encodePacked(bidOwner, erc20Token.contractAddress)
        );
        uint256 existingEscrowed = ms.escrowedTokensByHash[hashEntry];
        ms.escrowedTokensByHash[hashEntry] =
            existingEscrowed +
            erc20Token.amount;
    }

    function _transferErcTokensFromBidderToTrader(
        address bidOwner,
        address tradeOwner,
        Erc20Token memory erc20Token,
        uint256 amount
    ) internal {
        // This is used for "buy it now" settlement -- We can transfer directly from bidder to trader.
        ERC20(erc20Token.contractAddress).transferFrom(
            bidOwner,
            tradeOwner,
            amount
        );
    }

    function _transferEscrowedErcTokensToParticipant(
        address from,
        address participantAddress,
        Erc20Token memory erc20Token,
        uint256 amount
    ) internal {
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        s.escrowedTokenContract.retrieveTokens(
            from,
            erc20Token.contractAddress,
            amount,
            participantAddress
        );
    }

    function _transferNftsToParticipant(
        address participantAddress,
        NftByTokenId[] memory nfts
    ) internal {
        // Transfer Nfts
        for (uint256 i; i < nfts.length; ) {
            IERC721Enumerable(nfts[i].contractAddress).transferFrom(
                address(this),
                participantAddress,
                nfts[i].tokenId
            );

            unchecked {
                ++i;
            }
        }
    }

    function _transferUnclaimedNftsToParticipant(
        address participantAddress,
        NftByItemId[] memory unclaimedNfts
    ) internal {
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        IGameDiamond(s.gameContractAddress).transferUnclaimedNftsFromMarket(participantAddress,unclaimedNfts);
    }

    function _transferUnclaimedResourcesToParticipant(
        address participantAddress,
        ResourceData[] memory unclaimedResources
    ) internal {
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        IGameDiamond(s.gameContractAddress).transferUnclaimedResourcesFromMarket(participantAddress,unclaimedResources);
    }

    function _transferResourcesToParticipant(
        address participantAddress,
        ResourceData[] memory resources
    ) internal {
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        uint256[] memory resourceIds = new uint256[](resources.length);
        uint256[] memory resourceAmounts = new uint256[](resources.length);

        for (uint256 i = 0; i < resources.length; ) {
            resourceIds[i] = resources[i].resourceId;
            resourceAmounts[i] = resources[i].amount;

            unchecked {
                ++i;
            }
        }
        s.evrlootResourceContract.safeBatchTransferFrom(
            address(this),
            participantAddress,
            resourceIds,
            resourceAmounts,
            ""
        );
    }

    function _transferNftsToContract(
        address fromPlayerAddress,
        NftByTokenId[] memory nfts
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        // Transfer Nfts
        for (uint256 i; i < nfts.length; ) {
            if (
                IERC165(nfts[i].contractAddress).supportsInterface(0x42b0e56f) //ierc6059
            ) {
                // Check if rootOwner is the same as the msgSender
                (
                    address nftOwner,
                    uint256 parentTokenId,
                    bool isNft
                ) = IERC6059(nfts[i].contractAddress).directOwnerOf(
                        nfts[i].tokenId
                    );

                if (isNft == true) {
                    //May be staked -- get the estratokenId corresponding to tokenId
                    uint256 childIndex = _retrieveIERC6059ChildIndex(
                        nfts[i].contractAddress,
                        nfts[i].tokenId,
                        nftOwner,
                        parentTokenId
                    );

                    IERC6059(nftOwner).transferChild(
                        parentTokenId,
                        address(this),
                        0,
                        childIndex,
                        nfts[i].contractAddress, // childAddress,
                        nfts[i].tokenId, // childId,
                        false, //pending
                        ""
                    );
                } else {
                    IERC721Enumerable(nfts[i].contractAddress).transferFrom(
                        fromPlayerAddress,
                        address(this),
                        nfts[i].tokenId
                    );
                }
            } else {
                IERC721Enumerable(nfts[i].contractAddress).transferFrom(
                    fromPlayerAddress,
                    address(this),
                    nfts[i].tokenId
                );
            }

            // Add to escrowed nfts
            ms.escrowedNftsByHash[
                keccak256(
                    abi.encodePacked(
                        fromPlayerAddress,
                        nfts[i].contractAddress,
                        nfts[i].tokenId
                    )
                )
            ] = 1;

            unchecked {
                ++i;
            }
        }
    }

    function _retrieveIERC6059ChildIndex(
        address _contractAddress,
        uint256 _tokenId,
        address _parentAddress,
        uint256 _parentTokenId
    ) internal view returns (uint256) {
        // Need the childIndex
        IERC6059.Child[] memory childArray = IERC6059(_parentAddress)
            .childrenOf(_parentTokenId);

        for (uint256 j = 0; j < childArray.length; ) {
            if (
                childArray[j].tokenId == _tokenId &&
                childArray[j].contractAddress == _contractAddress
            ) {
                return j;
            }
            unchecked {
                ++j;
            }
        }
        revert ERC6059ChildNotFound();
    }

    function _transferUnclaimedNftsToContract(
        address fromPlayerAddress,
        NftByItemId[] memory unclaimedNfts
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        // Burn unclaimed nfts and store in escrow
        // LibUnclaimedRewards.burnBatchUnclaimedNfts(
        //     fromPlayerAddress,
        //     unclaimedNfts
        // );
        

        for (uint256 i = 0; i < unclaimedNfts.length; ) {
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    fromPlayerAddress,
                    unclaimedNfts[i].contractAddress,
                    unclaimedNfts[i].itemId
                )
            );
            uint256 existingEscrowed = ms.escrowedNftsByHash[hashEntry];
            ms.escrowedNftsByHash[hashEntry] =
                existingEscrowed +
                unclaimedNfts[i].amount;

            unchecked {
                ++i;
            }
        }
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        IGameDiamond(s.gameContractAddress).transferUnclaimedNftsToMarket(fromPlayerAddress,unclaimedNfts);
    }

    function _transferUnclaimedResourcesToContract(
        address fromPlayerAddress,
        ResourceData[] memory unclaimedResources
    ) internal {
        // Burn unclaimed resources and store as escrowed

        MarketStorage storage ms = LibMarketStorage.marketStorage();
        for (uint256 i = 0; i < unclaimedResources.length; ) {
            // LibUnclaimedRewards.burnUnclaimedResources(
            //     fromPlayerAddress,
            //     unclaimedResources[i].resourceId,
            //     unclaimedResources[i].amount
            // );
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    fromPlayerAddress,
                    "UNCLAIMEDRESOURCES",
                    unclaimedResources[i].resourceId
                )
            );
            uint256 existingEscrowed = ms.escrowedNftsByHash[hashEntry];
            ms.escrowedNftsByHash[hashEntry] =
                existingEscrowed +
                unclaimedResources[i].amount;

            unchecked {
                ++i;
            }
        }
        AppStorage storage s = LibMarketAppStorage.diamondStorage();
        IGameDiamond(s.gameContractAddress).transferUnclaimedResourcesToMarket(fromPlayerAddress,unclaimedResources);
    }

    function _transferResourcesToContract(
        address fromPlayerAddress,
        ResourceData[] memory resources
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        AppStorage storage s = LibMarketAppStorage.diamondStorage();

        uint256[] memory resourceIds = new uint256[](resources.length);
        uint256[] memory resourceAmounts = new uint256[](resources.length);

        for (uint256 i = 0; i < resources.length; ) {
            resourceIds[i] = resources[i].resourceId;
            resourceAmounts[i] = resources[i].amount;
            bytes32 hashentry = keccak256(
                abi.encodePacked(
                    fromPlayerAddress,
                    "RESOURCES",
                    resources[i].resourceId
                )
            );
            uint256 existingEscrowedAmount = ms.escrowedNftsByHash[hashentry];
            ms.escrowedNftsByHash[hashentry] =
                existingEscrowedAmount +
                resources[i].amount;

            unchecked {
                ++i;
            }
        }
        // Transfer 1155 Nfts
        if (resourceIds.length > 0)
            s.evrlootResourceContract.safeBatchTransferFrom(
                fromPlayerAddress,
                address(this),
                resourceIds,
                resourceAmounts,
                ""
            );
    }

    function _clearTradeData(bytes32 tradeId) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        StoredTrade memory _storedTrade = ms.trades[tradeId];
        if (_storedTrade.creationBlock == 0) revert MarketTradeDoesNotExist();

        delete ms.trades[tradeId];
        delete ms.unclaimedNftsByTradeId[tradeId];
        delete ms.unclaimedResourcesByTradeId[tradeId];
        delete ms.nftsByTradeId[tradeId];
        delete ms.resourcesByTradeId[tradeId];
        delete ms.erc20TokenByTradeId[tradeId];
        delete ms.tradeCreationFeeHold[tradeId];
    }

    function _clearBidData(bytes32 bidId) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        StoredBid memory _storedBid = ms.bids[bidId];
        if (_storedBid.creationBlock == 0) revert MarketBidDoesNotExist();

        delete ms.bids[bidId];
        delete ms.unclaimedNftsByBidId[bidId];
        delete ms.unclaimedResourcesByBidId[bidId];
        delete ms.nftsByBidId[bidId];
        delete ms.resourcesByBidId[bidId];
        delete ms.erc20TokenByBidId[bidId];
    }

    function _updateTradeWithNftData(
        NewTrade memory _newTrade,
        bytes32 tradeId
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        if (_newTrade.unclaimedNfts.length != 0) {
            for (uint256 i; i < _newTrade.unclaimedNfts.length; ) {
                ms.unclaimedNftsByTradeId[tradeId].push(
                    _newTrade.unclaimedNfts[i]
                );
                unchecked {
                    ++i;
                }
            }
        }

        if (_newTrade.unclaimedResources.length != 0) {
            for (uint256 i; i < _newTrade.unclaimedResources.length; ) {
                ms.unclaimedResourcesByTradeId[tradeId].push(
                    _newTrade.unclaimedResources[i]
                );
                unchecked {
                    ++i;
                }
            }
        }
        if (_newTrade.nfts.length != 0) {
            for (uint256 i; i < _newTrade.nfts.length; ) {
                ms.nftsByTradeId[tradeId].push(_newTrade.nfts[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newTrade.resources.length != 0) {
            for (uint256 i; i < _newTrade.resources.length; ) {
                ms.resourcesByTradeId[tradeId].push(_newTrade.resources[i]);
                unchecked {
                    ++i;
                }
            }
        }
        if (_newTrade.buyOutErc20Token.amount != 0)
            ms.erc20TokenByTradeId[tradeId] = _newTrade.buyOutErc20Token;

        if (_newTrade.buyOutEtherPrice != 0)
            ms.tradeBuyOutEtherPrice[tradeId] = _newTrade.buyOutEtherPrice;
    }

    function _updateBidWithNftData(
        NewBid memory _newBid,
        bytes32 bidId
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        if (_newBid.unclaimedNfts.length != 0) {
            for (uint256 i; i < _newBid.unclaimedNfts.length; ) {
                ms.unclaimedNftsByBidId[bidId].push(_newBid.unclaimedNfts[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.unclaimedResources.length != 0) {
            for (uint256 i; i < _newBid.unclaimedResources.length; ) {
                ms.unclaimedResourcesByBidId[bidId].push(
                    _newBid.unclaimedResources[i]
                );
                unchecked {
                    ++i;
                }
            }
        }
        if (_newBid.nfts.length != 0) {
            for (uint256 i; i < _newBid.nfts.length; ) {
                ms.nftsByBidId[bidId].push(_newBid.nfts[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.resources.length != 0) {
            for (uint256 i; i < _newBid.resources.length; ) {
                ms.resourcesByBidId[bidId].push(_newBid.resources[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.offeredErc20Token.amount != 0)
            ms.erc20TokenByBidId[bidId] = _newBid.offeredErc20Token;

        if (msg.value != 0) {
            ms.etherByBidId[bidId] = msg.value;
        }
    }

    function _updateTradeWithEscrowedNftData(
        NewTrade memory _newTrade,
        bytes32 tradeId
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        if (_newTrade.escrowedUnclaimedNfts.length != 0) {
            for (uint256 i; i < _newTrade.unclaimedNfts.length; ) {
                ms.unclaimedNftsByTradeId[tradeId].push(
                    _newTrade.unclaimedNfts[i]
                );
                unchecked {
                    ++i;
                }
            }
        }

        if (_newTrade.escrowedUnclaimedResources.length != 0) {
            for (uint256 i; i < _newTrade.unclaimedResources.length; ) {
                ms.unclaimedResourcesByTradeId[tradeId].push(
                    _newTrade.unclaimedResources[i]
                );
                unchecked {
                    ++i;
                }
            }
        }
        if (_newTrade.escrowedNfts.length != 0) {
            for (uint256 i; i < _newTrade.nfts.length; ) {
                ms.nftsByTradeId[tradeId].push(_newTrade.nfts[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newTrade.escrowedResources.length != 0) {
            for (uint256 i; i < _newTrade.resources.length; ) {
                ms.resourcesByTradeId[tradeId].push(_newTrade.resources[i]);
                unchecked {
                    ++i;
                }
            }
        }
    }

    function _updateBidWithEscrowedNftData(
        NewBid memory _newBid,
        bytes32 bidId
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        if (_newBid.escrowedUnclaimedNfts.length != 0) {
            for (uint256 i; i < _newBid.escrowedUnclaimedNfts.length; ) {
                ms.unclaimedNftsByBidId[bidId].push(
                    _newBid.escrowedUnclaimedNfts[i]
                );
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.escrowedUnclaimedResources.length != 0) {
            for (uint256 i; i < _newBid.escrowedUnclaimedResources.length; ) {
                ms.unclaimedResourcesByBidId[bidId].push(
                    _newBid.escrowedUnclaimedResources[i]
                );
                unchecked {
                    ++i;
                }
            }
        }
        if (_newBid.escrowedNfts.length != 0) {
            for (uint256 i; i < _newBid.escrowedNfts.length; ) {
                ms.nftsByBidId[bidId].push(_newBid.escrowedNfts[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.escrowedResources.length != 0) {
            for (uint256 i; i < _newBid.escrowedResources.length; ) {
                ms.resourcesByBidId[bidId].push(_newBid.escrowedResources[i]);
                unchecked {
                    ++i;
                }
            }
        }

        if (_newBid.escrowedErc20Token.amount != 0)
            ms.erc20TokenByBidId[bidId] = _newBid.escrowedErc20Token;

        if (_newBid.escrowedEtherValue != 0) {
            ms.etherByBidId[bidId] = _newBid.escrowedEtherValue;
        }
    }

    /**
     * @notice clears trade from existing trades for a trader
     */
    function _clearTradeFromTradersTrades(
        bytes32 tradeId,
        address traderAddress
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        bytes32[] storage tradersTrades = ms.tradesByTrader[traderAddress];
        for (uint256 i = 0; i < tradersTrades.length; ) {
            if (tradersTrades[i] == tradeId) {
                // Swap the found trade ID with the last one
                tradersTrades[i] = tradersTrades[tradersTrades.length - 1];
                // Delete the last one
                tradersTrades.pop();
                break;
            }
            unchecked {
                ++i;
            }
        }
    }

    function _clearBidFromBiddersBids(
        bytes32 bidId,
        address bidderAddress
    ) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        bytes32[] storage biddersBids = ms.bidsByBidder[bidderAddress];
        for (uint256 i = 0; i < biddersBids.length; ) {
            if (biddersBids[i] == bidId) {
                // Swap the found trade ID with the last one
                biddersBids[i] = biddersBids[biddersBids.length - 1];
                // Delete the last one
                biddersBids.pop();
                break;
            }
            unchecked {
                ++i;
            }
        }
    }

    function _clearBidFromTrade(bytes32 tradeId, bytes32 bidId) internal {
        MarketStorage storage ms = LibMarketStorage.marketStorage();

        bytes32[] storage bidsOnThisTrade = ms.bidsByTradeId[tradeId];

        for (uint256 i = 0; i < bidsOnThisTrade.length; ) {
            if (bidsOnThisTrade[i] == bidId) {
                // Swap the found bid ID with the last one
                bidsOnThisTrade[i] = bidsOnThisTrade[
                    bidsOnThisTrade.length - 1
                ];
                // Delete the last one
                bidsOnThisTrade.pop();
                break;
            }
            unchecked {
                ++i;
            }
        }
    }

    function _verifySuppliedEscrowedTokens(
        NftByItemId[] memory escrowedUnclaimedNfts,
        ResourceData[] memory escrowedUnclaimedResources,
        NftByTokenId[] memory escrowedNfts,
        ResourceData[] memory escrowedResources,
        Erc20Token memory erc20Token,
        uint256 etherValue,
        uint16 inclusionsBitmap
    ) internal view returns (uint16) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        address _msgSender = LibMeta.msgSender();
        bytes32 id;
        if (escrowedUnclaimedNfts.length > 0) {
            inclusionsBitmap |= UNCLAIMED_NFT_BIT;

            for (uint256 i = 0; i < escrowedUnclaimedNfts.length; ) {
                if (
                    ms.supportedTokens[
                        escrowedUnclaimedNfts[i].contractAddress
                    ] == false
                ) {
                    revert NftNotSupported();
                }

                if (escrowedUnclaimedNfts[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        escrowedUnclaimedNfts[i].contractAddress,
                        escrowedUnclaimedNfts[i].itemId
                    )
                );
                if (
                    ms.escrowedNftsByHash[id] < escrowedUnclaimedNfts[i].amount
                ) {
                    revert InsufficientEscrowedUnclaimedNft();
                }
                unchecked {
                    ++i;
                }
            }
        }
        if (escrowedNfts.length > 0) {
            inclusionsBitmap |= NFT_BIT;
            for (uint256 i = 0; i < escrowedNfts.length; ) {
                if (
                    ms.supportedTokens[escrowedNfts[i].contractAddress] == false
                ) {
                    revert NftNotSupported();
                }
                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        escrowedNfts[i].contractAddress,
                        escrowedNfts[i].tokenId
                    )
                );
                if (ms.escrowedNftsByHash[id] == 0) {
                    revert NftNotEscrowed();
                }
                unchecked {
                    ++i;
                }
            }
        }

        if (escrowedUnclaimedResources.length != 0) {
            inclusionsBitmap |= UNCLAIMED_RESOURCE_BIT;

            for (uint256 i = 0; i < escrowedUnclaimedResources.length; ) {
                if (
                    ms.supportedResources[
                        escrowedUnclaimedResources[i].resourceId
                    ] == false
                ) {
                    revert ResourceIdNotSupported();
                }

                if (escrowedUnclaimedResources[i].amount == 0)
                    revert AmountCannotBeZero();

                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        "UNCLAIMEDRESOURCES",
                        escrowedUnclaimedResources[i].resourceId
                    )
                );
                if (
                    ms.escrowedNftsByHash[id] <
                    escrowedUnclaimedResources[i].amount
                ) {
                    revert InsufficientEscrowedUnclaimedResource();
                }
                unchecked {
                    ++i;
                }
            }
        }
        if (escrowedResources.length != 0) {
            inclusionsBitmap |= RESOURCE_BIT;
            for (uint256 i = 0; i < escrowedResources.length; ) {
                if (
                    ms.supportedResources[escrowedResources[i].resourceId] ==
                    false
                ) {
                    revert ResourceIdNotSupported();
                }
                if (escrowedResources[i].amount == 0) {
                    revert AmountCannotBeZero();
                }
                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        "RESOURCES",
                        escrowedResources[i].resourceId
                    )
                );
                if (ms.escrowedNftsByHash[id] < escrowedResources[i].amount) {
                    revert InsufficientEscrowedResource();
                }
                unchecked {
                    ++i;
                }
            }
        }

        if (erc20Token.amount != 0) {
            inclusionsBitmap |= BUYOUT_ERC20_BIT;
            if (ms.supportedTokens[erc20Token.contractAddress] == false)
                revert Erc20AddressNotSupported();

            bytes32 hashEntry = keccak256(
                abi.encodePacked(_msgSender, erc20Token.contractAddress)
            );
            uint256 existingEscrowed = ms.escrowedTokensByHash[hashEntry];
            if (existingEscrowed < erc20Token.amount) {
                revert InsufficientEscrowedTokens();
            }
        }

        if (etherValue > 0) {
            inclusionsBitmap |= BUYOUT_ETHER_BIT;
            uint256 existingEscrowed = ms.escrowedEtherByAddress[_msgSender];
            if (existingEscrowed < etherValue)
                revert InsufficientEscrowedEther();
        }
        return inclusionsBitmap;
    }

    function _verifySuppliedEscrowedTokensTrade(
        NftByItemId[] memory escrowedUnclaimedNfts,
        ResourceData[] memory escrowedUnclaimedResources,
        NftByTokenId[] memory escrowedNfts,
        ResourceData[] memory escrowedResources,
        uint16 inclusionsBitmap
    ) internal view returns (uint16) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        address _msgSender = LibMeta.msgSender();
        bytes32 id;
        if (escrowedUnclaimedNfts.length > 0) {
            inclusionsBitmap |= UNCLAIMED_NFT_BIT;

            for (uint256 i = 0; i < escrowedUnclaimedNfts.length; ) {
                if (
                    ms.supportedTokens[
                        escrowedUnclaimedNfts[i].contractAddress
                    ] == false
                ) {
                    revert NftNotSupported();
                }
                if (escrowedUnclaimedNfts[i].amount == 0) {
                    revert AmountCannotBeZero();
                }
                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        escrowedUnclaimedNfts[i].contractAddress,
                        escrowedUnclaimedNfts[i].itemId
                    )
                );
                if (
                    ms.escrowedNftsByHash[id] < escrowedUnclaimedNfts[i].amount
                ) {
                    revert InsufficientEscrowedUnclaimedNft();
                }
                unchecked {
                    ++i;
                }
            }
        }
        if (escrowedNfts.length > 0) {
            inclusionsBitmap |= NFT_BIT;
            for (uint256 i = 0; i < escrowedNfts.length; ) {
                if (
                    ms.supportedTokens[escrowedNfts[i].contractAddress] == false
                ) {
                    revert NftNotSupported();
                }

                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        escrowedNfts[i].contractAddress,
                        escrowedNfts[i].tokenId
                    )
                );

                if (ms.escrowedNftsByHash[id] == 0) {
                    revert NftNotEscrowed();
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (escrowedUnclaimedResources.length != 0) {
            inclusionsBitmap |= UNCLAIMED_RESOURCE_BIT;

            for (uint256 i = 0; i < escrowedUnclaimedResources.length; ) {
                if (
                    ms.supportedResources[
                        escrowedUnclaimedResources[i].resourceId
                    ] == false
                ) {
                    revert ResourceIdNotSupported();
                }

                if (escrowedUnclaimedResources[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        "UNCLAIMEDRESOURCES",
                        escrowedUnclaimedResources[i].resourceId
                    )
                );

                if (
                    ms.escrowedNftsByHash[id] <
                    escrowedUnclaimedResources[i].amount
                ) {
                    revert InsufficientEscrowedUnclaimedResource();
                }
                unchecked {
                    ++i;
                }
            }
        }
        if (escrowedResources.length != 0) {
            inclusionsBitmap |= RESOURCE_BIT;
            for (uint256 i = 0; i < escrowedResources.length; ) {
                if (
                    ms.supportedResources[escrowedResources[i].resourceId] ==
                    false
                ) {
                    revert ResourceIdNotSupported();
                }

                if (escrowedResources[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                id = keccak256(
                    abi.encodePacked(
                        _msgSender,
                        "RESOURCES",
                        escrowedResources[i].resourceId
                    )
                );
                if (ms.escrowedNftsByHash[id] < escrowedResources[i].amount) {
                    revert InsufficientEscrowedResource();
                }
                unchecked {
                    ++i;
                }
            }
        }

        return inclusionsBitmap;
    }

    /**
     * @notice Confirm that supplied tokens are supported and valid
     */
    function _verifySuppliedBidTokens(
        NewBid calldata newBid,
        uint256 offeredEtherValue
    ) internal view returns (uint16 inclusionsBitmap) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        AppStorage storage s = LibMarketAppStorage.diamondStorage();

        address _msgSender = LibMeta.msgSender();
        if (newBid.unclaimedNfts.length > 0) {
            inclusionsBitmap |= UNCLAIMED_NFT_BIT;

            for (uint256 i = 0; i < newBid.unclaimedNfts.length; ) {
                if (
                    ms.supportedTokens[newBid.unclaimedNfts[i].contractAddress] ==
                    false
                ) {
                    revert NftNotSupported();
                }

                if (newBid.unclaimedNfts[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (newBid.unclaimedResources.length != 0) {
            inclusionsBitmap |= UNCLAIMED_RESOURCE_BIT;

            for (uint256 i = 0; i < newBid.unclaimedResources.length; ) {
                if (
                    ms.supportedResources[newBid.unclaimedResources[i].resourceId] ==
                    false
                ) revert ResourceIdNotSupported();

                if (newBid.unclaimedResources[i].amount == 0)
                    revert AmountCannotBeZero();

                unchecked {
                    ++i;
                }
            }
        }

        if (newBid.nfts.length != 0) {
            inclusionsBitmap |= NFT_BIT;

            for (uint256 i = 0; i < newBid.nfts.length; ) {
                if (ms.supportedTokens[newBid.nfts[i].contractAddress] == false)
                    revert NftNotSupported();

                // Confirm ownership (Check if type RMRKNestable)
                if (
                    IERC721(newBid.nfts[i].contractAddress).ownerOf(newBid.nfts[i].tokenId) !=
                    _msgSender
                ) {
                    if (
                        IERC165(newBid.nfts[i].contractAddress).supportsInterface(
                            0x42b0e56f //ERC6059
                        )
                    ) {
                        // Check if rootOwner is the same as the msgSender
                        (
                            address nftOwner,
                            uint256 tokenId,
                            bool isNft
                        ) = IERC6059(newBid.nfts[i].contractAddress).directOwnerOf(
                                newBid.nfts[i].tokenId
                            );

                        if (isNft == true) {
                            //May be staked -- get the estratokenId corresponding to tokenId
                            // uint256 estraTokenId = s.stakedSoulTokens[nftOwner][
                            //     tokenId
                            // ];
                            // if (estraTokenId == 0) {
                            //     if (
                            //         IERC6059(nftOwner).ownerOf(tokenId) !=
                            //         _msgSender
                            //     ) revert ERC6059NotOwner();
                            // } else if (
                            //     _msgSender != s.stakingTokenOwners[estraTokenId]
                            // ) {
                            //     revert ERC6059NotStakedOwner();
                            // }
                            //LibMarketDiamond.DiamondStorage storage ds = LibMarketDiamond.diamondStorage();
                            (uint256 estraTokenId, address ownerAddress) = IGameDiamond(s.gameContractAddress).lookupEstraTokenId(newBid.nfts[i].contractAddress, newBid.nfts[i].tokenId);
                            if(estraTokenId == 0){
                                if (
                                    IERC6059(nftOwner).ownerOf(tokenId) !=
                                    _msgSender
                                ) revert ERC6059NotOwner();
                            }
                            else if(
                                ownerAddress != _msgSender
                            ){
                                revert ERC6059NotStakedOwner();
                            }
                            // Check if msgSender is owner of estratokenId
                        } else {
                            if (nftOwner != _msgSender)
                                revert ERC6059NotOwner();
                        }
                    } else {
                        revert ERC721NotOwner();
                    }
                }
                unchecked {
                    ++i;
                }
            }
        }

        if (newBid.resources.length != 0) {
            inclusionsBitmap |= RESOURCE_BIT;
            for (uint256 i = 0; i < newBid.resources.length; ) {
                if (ms.supportedResources[newBid.resources[i].resourceId] == false) {
                    revert ResourceIdNotSupported();
                }

                if (newBid.resources[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (newBid.offeredErc20Token.amount != 0) {
            inclusionsBitmap |= BUYOUT_ERC20_BIT;

            if (ms.supportedTokens[newBid.offeredErc20Token.contractAddress] == false) {
                revert Erc20AddressNotSupported();
            }
        }

        if (offeredEtherValue > 0) {
            inclusionsBitmap |= BUYOUT_ETHER_BIT;
        }
    }

/**
     * @notice Confirm that supplied tokens are supported and valid
     */
    function _verifySuppliedTradeTokens(
        NewTrade calldata newTrade
    ) internal view returns (uint16 inclusionsBitmap) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        AppStorage storage s = LibMarketAppStorage.diamondStorage();

        address _msgSender = LibMeta.msgSender();
        if (newTrade.unclaimedNfts.length > 0) {
            inclusionsBitmap |= UNCLAIMED_NFT_BIT;

            for (uint256 i = 0; i < newTrade.unclaimedNfts.length; ) {
                if (
                    ms.supportedTokens[newTrade.unclaimedNfts[i].contractAddress] ==
                    false
                ) {
                    revert NftNotSupported();
                }

                if (newTrade.unclaimedNfts[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (newTrade.unclaimedResources.length != 0) {
            inclusionsBitmap |= UNCLAIMED_RESOURCE_BIT;

            for (uint256 i = 0; i < newTrade.unclaimedResources.length; ) {
                if (
                    ms.supportedResources[newTrade.unclaimedResources[i].resourceId] ==
                    false
                ) revert ResourceIdNotSupported();

                if (newTrade.unclaimedResources[i].amount == 0)
                    revert AmountCannotBeZero();

                unchecked {
                    ++i;
                }
            }
        }

        if (newTrade.nfts.length != 0) {
            inclusionsBitmap |= NFT_BIT;

            for (uint256 i = 0; i < newTrade.nfts.length; ) {
                if (ms.supportedTokens[newTrade.nfts[i].contractAddress] == false)
                    revert NftNotSupported();

                // Confirm ownership (Check if type RMRKNestable)
                if (
                    IERC721(newTrade.nfts[i].contractAddress).ownerOf(newTrade.nfts[i].tokenId) !=
                    _msgSender
                ) {
                    if (
                        IERC165(newTrade.nfts[i].contractAddress).supportsInterface(
                            0x42b0e56f //ERC6059
                        )
                    ) {
                        // Check if rootOwner is the same as the msgSender
                        (
                            address nftOwner,
                            uint256 tokenId,
                            bool isNft
                        ) = IERC6059(newTrade.nfts[i].contractAddress).directOwnerOf(
                                newTrade.nfts[i].tokenId
                            );

                        if (isNft == true) {
                            //May be staked -- get the estratokenId corresponding to tokenId
                            // uint256 estraTokenId = s.stakedSoulTokens[nftOwner][
                            //     tokenId
                            // ];
                            // if (estraTokenId == 0) {
                            //     if (
                            //         IERC6059(nftOwner).ownerOf(tokenId) !=
                            //         _msgSender
                            //     ) revert ERC6059NotOwner();
                            // } else if (
                            //     _msgSender != s.stakingTokenOwners[estraTokenId]
                            // ) {
                            //     revert ERC6059NotStakedOwner();
                            // }
                            //LibMarketDiamond.DiamondStorage storage ds = LibMarketDiamond.diamondStorage();
                            (uint256 estraTokenId, address ownerAddress) = IGameDiamond(s.gameContractAddress).lookupEstraTokenId(newTrade.nfts[i].contractAddress, newTrade.nfts[i].tokenId);
                            if(estraTokenId == 0){
                                if (
                                    IERC6059(nftOwner).ownerOf(tokenId) !=
                                    _msgSender
                                ) revert ERC6059NotOwner();
                            }
                            else if(
                                ownerAddress != _msgSender
                            ){
                                revert ERC6059NotStakedOwner();
                            }
                            // Check if msgSender is owner of estratokenId
                        } else {
                            if (nftOwner != _msgSender)
                                revert ERC6059NotOwner();
                        }
                    } else {
                        revert ERC721NotOwner();
                    }
                }
                unchecked {
                    ++i;
                }
            }
        }

        if (newTrade.resources.length != 0) {
            inclusionsBitmap |= RESOURCE_BIT;
            for (uint256 i = 0; i < newTrade.resources.length; ) {
                if (ms.supportedResources[newTrade.resources[i].resourceId] == false) {
                    revert ResourceIdNotSupported();
                }

                if (newTrade.resources[i].amount == 0) {
                    revert AmountCannotBeZero();
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (newTrade.buyOutErc20Token.amount != 0) {
            inclusionsBitmap |= BUYOUT_ERC20_BIT;

            if (ms.supportedTokens[newTrade.buyOutErc20Token.contractAddress] == false) {
                revert Erc20AddressNotSupported();
            }
        }

        if (newTrade.buyOutEtherPrice > 0) {
            inclusionsBitmap |= BUYOUT_ETHER_BIT;
        }


    }

    function _verifyTradeEscrow(
        StoredTrade memory _trade,
        bytes32 tradeId
    ) internal view returns (bool) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        uint16 inclusionsBitmap = _trade.inclusionsBitmap;

        if (inclusionsBitmap & NFT_BIT != 0) {
            NftByTokenId[] memory nfts = ms.nftsByTradeId[tradeId];
            for (uint256 i; i < nfts.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _trade.tradeOwnerAddress,
                        nfts[i].contractAddress,
                        nfts[i].tokenId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] == 0)
                    revert NftNotEscrowed();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            ResourceData[] memory resources = ms.resourcesByTradeId[tradeId];

            for (uint256 i; i < resources.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _trade.tradeOwnerAddress,
                        "RESOURCES",
                        resources[i].resourceId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] < resources[i].amount)
                    revert InsufficientEscrowedResource();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            NftByItemId[] memory unclaimedNfts = ms.unclaimedNftsByTradeId[
                tradeId
            ];
            for (uint256 i; i < unclaimedNfts.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _trade.tradeOwnerAddress,
                        unclaimedNfts[i].contractAddress,
                        unclaimedNfts[i].itemId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] < unclaimedNfts[i].amount)
                    revert InsufficientEscrowedUnclaimedNft();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            ResourceData[] memory unclaimedResources = ms
                .unclaimedResourcesByTradeId[tradeId];
            for (uint256 i; i < unclaimedResources.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _trade.tradeOwnerAddress,
                        "UNCLAIMEDRESOURCES",
                        unclaimedResources[i].resourceId
                    )
                );
                if (
                    ms.escrowedNftsByHash[hashEntry] <
                    unclaimedResources[i].amount
                ) revert InsufficientEscrowedUnclaimedResource();

                unchecked {
                    ++i;
                }
            }
        }
        return true;
    }

    function _verifyBidEscrow(
        StoredBid memory _bid,
        bytes32 bidId
    ) internal view returns (bool) {
        MarketStorage storage ms = LibMarketStorage.marketStorage();
        uint16 inclusionsBitmap = _bid.inclusionsBitmap;

        if (inclusionsBitmap & NFT_BIT != 0) {
            NftByTokenId[] memory nfts = ms.nftsByBidId[bidId];
            for (uint256 i; i < nfts.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _bid.bidOwnerAddress,
                        nfts[i].contractAddress,
                        nfts[i].tokenId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] == 0)
                    revert NftNotEscrowed();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & RESOURCE_BIT != 0) {
            ResourceData[] memory resources = ms.resourcesByBidId[bidId];

            for (uint256 i; i < resources.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _bid.bidOwnerAddress,
                        "RESOURCES",
                        resources[i].resourceId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] < resources[i].amount)
                    revert InsufficientEscrowedResource();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & UNCLAIMED_NFT_BIT != 0) {
            NftByItemId[] memory unclaimedNfts = ms.unclaimedNftsByBidId[bidId];
            for (uint256 i; i < unclaimedNfts.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _bid.bidOwnerAddress,
                        unclaimedNfts[i].contractAddress,
                        unclaimedNfts[i].itemId
                    )
                );
                if (ms.escrowedNftsByHash[hashEntry] < unclaimedNfts[i].amount)
                    revert InsufficientEscrowedUnclaimedNft();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & UNCLAIMED_RESOURCE_BIT != 0) {
            ResourceData[] memory unclaimedResources = ms
                .unclaimedResourcesByBidId[bidId];
            for (uint256 i; i < unclaimedResources.length; ) {
                bytes32 hashEntry = keccak256(
                    abi.encodePacked(
                        _bid.bidOwnerAddress,
                        "UNCLAIMEDRESOURCES",
                        unclaimedResources[i].resourceId
                    )
                );
                if (
                    ms.escrowedNftsByHash[hashEntry] <
                    unclaimedResources[i].amount
                ) revert InsufficientEscrowedUnclaimedResource();

                unchecked {
                    ++i;
                }
            }
        }

        if (inclusionsBitmap & BUYOUT_ERC20_BIT != 0) {
            Erc20Token memory erc20Token = ms.erc20TokenByBidId[bidId];
            bytes32 hashEntry = keccak256(
                abi.encodePacked(
                    _bid.bidOwnerAddress,
                    erc20Token.contractAddress
                )
            );
            if (ms.escrowedTokensByHash[hashEntry] < erc20Token.amount)
                revert InsufficientEscrowedTokens();
        }

        if (inclusionsBitmap & BUYOUT_ETHER_BIT != 0) {
            uint256 offeredEther = ms.etherByBidId[bidId];
            if (ms.escrowedEtherByAddress[_bid.bidOwnerAddress] < offeredEther)
                revert InsufficientEscrowedEther();
        }

        return true;
    }
}

File 40 of 49 : MarketErrors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

error MarketTradeDoesNotExist();
error NotTradeOwner();
error CreationFeeIncorrect();
error InsufficientUnclaimedNfts();
error CancellationFeeIncorrect();
error CannotCancelTradeYet();
error InsufficientUnclaimedResources();
error BuyOutEtherBidCannotContainOtherItems();
error InsufficientBid();
error NotBidOwner();
error MarketBidDoesNotExist();
error MarketBidDoesNotMatchTrade();
error CannotBidOnOwnTrade();
error BuyOutERC20BidCannotContainOtherItems();
error BidExceedsBuyoutPrice();
error NftNotEscrowed();
error InsufficientEscrowedUnclaimedNft();
error InsufficientEscrowedUnclaimedResource();
error InsufficientEscrowedResource();
error InsufficientEscrowedTokens();
error InsufficientEscrowedEther();
error AmountCannotBeZero();
error NftNotSupported();
error ResourceIdNotSupported();
error Erc20AddressNotSupported();
error ERC6059ChildNotFound();
error ERC6059NotOwner();
error ERC721NotOwner();
error ERC6059NotStakedOwner();
error EtherTransferFailed();
error ERC20AddressesMismatch();
error NoItemsSuppliedForTrade();
error RoyaltyAddressNotSet();

// SPDX-License-Identifier: MIT
// Compatible with OpenZeppelin Contracts ^5.0.0
pragma solidity ^0.8.20;

import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Erc20Token} from "../diamondMarket/libraries/LibMarketStorage.sol";

/**
 * @title Evrloot Market Escro Contract
 * @author Evrloot Team
 * @notice Used to escro fungible tokens and ether for Evrloot players involved in trading. This is to ensure separation between player fungible assets and game fungible assets.
 */
contract TokenEscrow is
    Initializable,
    PausableUpgradeable,
    AccessControlUpgradeable,
    UUPSUpgradeable
{
    event EscrowedTokens(
        address indexed owner,
        address indexed tokenAddress,
        uint256 amount
    );
    event EscrowedEther(address indexed owner, uint256 amount);
    event RetrievedTokens(
        address indexed to,
        address indexed tokenAddress,
        uint256 amount,
        address newOwner
    );
    event RetrievedEther(address indexed to, uint256 amount, address newOwner);

    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
    bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
    bytes32 public constant MARKET_CONTRACT_ROLE =
        keccak256("MARKET_CONTRACT_ROLE");

    mapping(address => mapping(address => uint256)) public escrowedTokens;
    mapping(address => uint256) public escrowedEther;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(
        address defaultAdmin,
        address pauser,
        address marketContract
    ) public initializer {
        __Pausable_init();
        __AccessControl_init();
        __UUPSUpgradeable_init();

        _grantRole(DEFAULT_ADMIN_ROLE, defaultAdmin);
        _grantRole(UPGRADER_ROLE, defaultAdmin);
        _grantRole(PAUSER_ROLE, pauser);
        _grantRole(MARKET_CONTRACT_ROLE, marketContract);
    }

    /**
     * @notice Store tokens in escrow
     * @param owner Token owner
     * @param tokenAddress Token address
     * @param amount Token amount
     */
    function storeTokens(
        address owner,
        address tokenAddress,
        uint256 amount
    ) public onlyRole(MARKET_CONTRACT_ROLE) whenNotPaused {
        ERC20(tokenAddress).transferFrom(owner, address(this), amount);
        uint256 current = escrowedTokens[owner][tokenAddress];
        escrowedTokens[owner][tokenAddress] = current + amount;
        emit EscrowedTokens(owner, tokenAddress, amount);
    }

    /**
     * @notice Retrieve tokens from escrow
     * @param owner Token owner
     * @param tokenAddress Token address
     * @param amount Token amount
     * @param newOwner New owner of tokens (use same as 'owner' to return to owner)
     */
    function retrieveTokens(
        address owner,
        address tokenAddress,
        uint256 amount,
        address newOwner
    ) public onlyRole(MARKET_CONTRACT_ROLE) whenNotPaused {
        uint256 storedAmount =escrowedTokens[owner][tokenAddress];
        require(
            storedAmount >= amount,
            "Insufficient funds in escrow"
        );
       
        unchecked{
            escrowedTokens[owner][tokenAddress] = storedAmount - amount;
        }

        ERC20(tokenAddress).transfer(newOwner, amount);
        emit RetrievedTokens(owner, tokenAddress, amount, newOwner);
    }

    /**
     * @notice Store ether in escrow
     * @param owner Ether owner
     */
    function storeEther(
        address owner
    ) public payable onlyRole(MARKET_CONTRACT_ROLE) whenNotPaused {
        // store ether in escrow
        escrowedEther[owner] += msg.value;
        emit EscrowedEther(owner, msg.value);
    }

    /**
     * @notice Retrieve ether from escrow
     * @param owner Ether owner
     * @param amount Ether amount
     * @param newOwner New owner of ether (use same as 'owner' to return to owner)
     */
    function retrieveEther(
        address owner,
        uint256 amount,
        address newOwner
    ) public onlyRole(MARKET_CONTRACT_ROLE) whenNotPaused {
        uint256 storedAmount = escrowedEther[owner];
        require(storedAmount >= amount, "Insufficient funds in escrow");

        unchecked{
            escrowedEther[owner] = storedAmount - amount;
        }
        
        (bool success, ) = newOwner.call{value: amount}("");
        require(success, "Retrieval failed.");

        emit RetrievedEther(owner, amount, newOwner);
    }

    function pause() public onlyRole(PAUSER_ROLE) {
        _pause();
    }

    function unpause() public onlyRole(PAUSER_ROLE) {
        _unpause();
    }
    
    // add a generic withdraw function to allow owner to withdraw tokens mistakenly sent to contract
    function withdrawTokens(
        address tokenAddress,
        uint256 amount
    ) public onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
        ERC20(tokenAddress).transfer(msg.sender, amount);
    }

    function _authorizeUpgrade(
        address newImplementation
    ) internal override onlyRole(UPGRADER_ROLE) {}

    // the default receive function should decline any ether sent to this contract
    receive() external payable {
        revert("Escro: must use storeEther");
    }

    // the default fallback function should decline any ether sent to this contract
    fallback() external payable {
        revert("Escro: must use storeEther");
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

/**
 * @title IEvrlootStakedSoulActivity
 * @dev the Evrloot StakedSoulActivity Interface defines all functions available within Evrloot game contracts for interacting with staked souls
 */
interface IEscro {
    function storeTokens(
        address owner,
        address tokenAddress,
        uint256 amount
    ) external;

    function retrieveTokens(
        address owner,
        address tokenAddress,
        uint256 amount,
        address newOwner
    ) external;

    function storeEther(address owner) external payable;

    function retrieveEther(
        address owner,
        uint256 amount,
        address newOwner
    ) external;
}

File 43 of 49 : Errors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

error ZeroAddress();
error UnsupportedMission();
error NotSoulCollection();
error NotSupportedCollection();
error CollectionAlreadyExists();
error MissionDoesNotExist();
error MissionNotEnabled();
error MissionNotStarted();
error MissionNotFinished();
error IncorrectMissionFee();
error InvalidRewardAmount();
error SenderIsNotOwnerOfStakedToken();
error SoulHasActiveOrUnclaimedMission();
error InsufficientSuppliedNfts();
error FeeNotSent();
error RequestedAmountZero();
error NotSoulTokenOwner();
error NotEstraTokenOwner();
error BadInputLengths();
error NoFeestoCollect();
error WithdrawalAddressNotSet();
error MaxRollsExceedsLimit();
error AlreadyIdentified();
error PoolIdNotSet();
error ContractNotSupported();
error NotTokenOwner();
error NoRngAvailable();
error WithdrawFailed();
error RMRKMintUnderpriced();
error RMRKMintZero();
error NotChildTokenOwner();
error MissionIdMismatch();
error ContractIsPaused();
error ContractIsNotPaused();
error NotAirNode();
error ResourceMetadataNotSet();
error InvalidTokenID();
error IdentifyQueueItemNotFound();
error IdentifySuppliedEmptyAssetIds();
error RequestedAmountTooLarge();
error IncorrectIdentifyFee();
error NoRollableAssets();
error RequestInProgress();
error CannotMintZeroItemId();
error InvalidRarityDivisor();
error CannotEquipWhileOnMission();
error IncorrectSuppliedNfts();
error SuppliedNftCannotBeOwnedByNft();
error SuppliedNftNotOwnedByPlayer();
error NoDefinedAssets();
error ItemMustBeIdentified();
error CannotTransferToSelf();
error CannotTransferToZeroAddress();
error IncorrectRewardTransferFee();
error IncorrectRewardsClaimFee();
error NotATradeMission();
error UnclaimedNftsInvalidBurnAmount();
error UnclaimedResourcesInvalidBurnAmount();
error MissionNotReady();
error ReEntrancyLock();
error InvalidRequestId();
error SoulHasActiveOrUnclaimedExpedition();
error BurnNotPermitted();
error NotBackendRelayer();
error NotBackend();
error MarketAddressNotSet();
error NotEvrlootMarketplace();

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC1155/extensions/ERC1155Burnable.sol)

pragma solidity ^0.8.0;

import "./ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 * @dev Extension of {ERC1155} that allows token holders to destroy both their
 * own tokens and those that they have been approved to use.
 *
 * _Available since v3.1._
 */
abstract contract ERC1155BurnableUpgradeable is
    Initializable,
    ERC1155Upgradeable
{
    function __ERC1155Burnable_init() internal onlyInitializing {}

    function __ERC1155Burnable_init_unchained() internal onlyInitializing {}

    function burn(address account, uint256 id, uint256 value) public virtual {
        require(
            account == _msgSender() || isApprovedForAll(account, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );

        _burn(account, id, value);
    }

    function burnBatch(
        address account,
        uint256[] memory ids,
        uint256[] memory values
    ) public virtual {
        require(
            account == _msgSender() || isApprovedForAll(account, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );

        _burnBatch(account, ids, values);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)

pragma solidity ^0.8.0;

import "./ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 * @dev Extension of ERC1155 that adds tracking of total supply per id.
 *
 * Useful for scenarios where Fungible and Non-fungible tokens have to be
 * clearly identified. Note: While a totalSupply of 1 might mean the
 * corresponding is an NFT, there is no guarantees that no other token with the
 * same id are not going to be minted.
 */
abstract contract ERC1155SupplyUpgradeable is
    Initializable,
    ERC1155Upgradeable
{
    function __ERC1155Supply_init() internal onlyInitializing {}

    function __ERC1155Supply_init_unchained() internal onlyInitializing {}

    mapping(uint256 => uint256) private _totalSupply;

    /**
     * @dev Total amount of tokens in with a given id.
     */
    function totalSupply(uint256 id) public view virtual returns (uint256) {
        return _totalSupply[id];
    }

    /**
     * @dev Indicates whether any token exist with a given id, or not.
     */
    function exists(uint256 id) public view virtual returns (bool) {
        return ERC1155SupplyUpgradeable.totalSupply(id) > 0;
    }

    /**
     * @dev See {ERC1155-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual override {
        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);

        if (from == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                _totalSupply[ids[i]] += amounts[i];
            }
        }

        if (to == address(0)) {
            for (uint256 i = 0; i < ids.length; ++i) {
                uint256 id = ids[i];
                uint256 amount = amounts[i];
                uint256 supply = _totalSupply[id];
                require(
                    supply >= amount,
                    "ERC1155: burn amount exceeds totalSupply"
                );
                unchecked {
                    _totalSupply[id] = supply - amount;
                }
            }
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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

pragma solidity ^0.8.0;

import "./IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "./IERC1155MetadataURIUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 *
 * _Available since v3.1._
 */
contract ERC1155Upgradeable is
    Initializable,
    ContextUpgradeable,
    ERC165Upgradeable,
    IERC1155Upgradeable,
    IERC1155MetadataURIUpgradeable
{
    using AddressUpgradeable for address;

    // Mapping from token ID to account balances
    mapping(uint256 => mapping(address => uint256)) private _balances;

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

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    function __ERC1155_init(string memory uri_) internal onlyInitializing {
        __ERC1155_init_unchained(uri_);
    }

    function __ERC1155_init_unchained(
        string memory uri_
    ) internal onlyInitializing {
        _setURI(uri_);
    }

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

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256) public view virtual override returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(
        address account,
        uint256 id
    ) public view virtual override returns (uint256) {
        require(
            account != address(0),
            "ERC1155: address zero is not a valid owner"
        );
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] memory accounts,
        uint256[] memory ids
    ) public view virtual override returns (uint256[] memory) {
        require(
            accounts.length == ids.length,
            "ERC1155: accounts and ids length mismatch"
        );

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }

        return batchBalances;
    }

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

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

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );
        _safeTransferFrom(from, to, id, amount, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public virtual override {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );
        _safeBatchTransferFrom(from, to, ids, amounts, data);
    }

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        uint256 fromBalance = _balances[id][from];
        require(
            fromBalance >= amount,
            "ERC1155: insufficient balance for transfer"
        );
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }
        _balances[id][to] += amount;

        emit TransferSingle(operator, from, to, id, amount);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(
            ids.length == amounts.length,
            "ERC1155: ids and amounts length mismatch"
        );
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(
                fromBalance >= amount,
                "ERC1155: insufficient balance for transfer"
            );
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
            _balances[id][to] += amount;
        }

        emit TransferBatch(operator, from, to, ids, amounts);

        _afterTokenTransfer(operator, from, to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(
            operator,
            from,
            to,
            ids,
            amounts,
            data
        );
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the amounts in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        _balances[id][to] += amount;
        emit TransferSingle(operator, address(0), to, id, amount);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeTransferAcceptanceCheck(
            operator,
            address(0),
            to,
            id,
            amount,
            data
        );
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(
            ids.length == amounts.length,
            "ERC1155: ids and amounts length mismatch"
        );

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; i++) {
            _balances[ids[i]][to] += amounts[i];
        }

        emit TransferBatch(operator, address(0), to, ids, amounts);

        _afterTokenTransfer(operator, address(0), to, ids, amounts, data);

        _doSafeBatchTransferAcceptanceCheck(
            operator,
            address(0),
            to,
            ids,
            amounts,
            data
        );
    }

    /**
     * @dev Destroys `amount` tokens of token type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `amount` tokens of token type `id`.
     */
    function _burn(address from, uint256 id, uint256 amount) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }

        emit TransferSingle(operator, from, address(0), id, amount);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     */
    function _burnBatch(
        address from,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        require(from != address(0), "ERC1155: burn from the zero address");
        require(
            ids.length == amounts.length,
            "ERC1155: ids and amounts length mismatch"
        );

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, address(0), ids, amounts, "");

        for (uint256 i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(
                fromBalance >= amount,
                "ERC1155: burn amount exceeds balance"
            );
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
        }

        emit TransferBatch(operator, from, address(0), ids, amounts);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @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, "ERC1155: setting approval status for self");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `ids` and `amounts` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `id` and `amount` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {}

    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try
                IERC1155ReceiverUpgradeable(to).onERC1155Received(
                    operator,
                    from,
                    id,
                    amount,
                    data
                )
            returns (bytes4 response) {
                if (
                    response !=
                    IERC1155ReceiverUpgradeable.onERC1155Received.selector
                ) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non-ERC1155Receiver implementer");
            }
        }
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) private {
        if (to.isContract()) {
            try
                IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(
                    operator,
                    from,
                    ids,
                    amounts,
                    data
                )
            returns (bytes4 response) {
                if (
                    response !=
                    IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector
                ) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non-ERC1155Receiver implementer");
            }
        }
    }

    function _asSingletonArray(
        uint256 element
    ) private pure returns (uint256[] memory) {
        uint256[] memory array = new uint256[](1);
        array[0] = element;

        return array;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[47] private __gap;
}

File 47 of 49 : IERC1155MetadataURIUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity ^0.8.0;

import "./IERC1155Upgradeable.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

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

pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";

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

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

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

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

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

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

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

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

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

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

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

import "./ERC1155/ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "./ERC1155/ERC1155BurnableUpgradeable.sol";
import "./ERC1155/ERC1155SupplyUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

error ResourceMetadataNotSet();
error ResourceUriAlreadySet();
error BadInputLengths();

contract EvrlootResources is
    Initializable,
    ERC1155Upgradeable,
    AccessControlUpgradeable,
    PausableUpgradeable,
    ERC1155BurnableUpgradeable,
    ERC1155SupplyUpgradeable,
    UUPSUpgradeable
{
    event NewResourceAdded(uint256 indexed id, string name, string uri);
    bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");

    // Resource types
    mapping(uint256 => string) private _tokenURI;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        //_disableInitializers();
    }

    function initialize() public initializer {
        __AccessControl_init();
        __Pausable_init();
        __ERC1155Burnable_init();
        __ERC1155Supply_init();
        __UUPSUpgradeable_init();

        _grantRole(OWNER_ROLE, msg.sender);
        _grantRole(MINTER_ROLE, msg.sender);
        _grantRole(UPGRADER_ROLE, msg.sender);
        _setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
        _setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
        _setRoleAdmin(UPGRADER_ROLE, OWNER_ROLE);
    }

    modifier onlyApprovedOrOwner(address from) {
        _isApprovedOrOwner(from);
        _;
    }

    function pause() public onlyRole(OWNER_ROLE) {
        _pause();
    }

    function unpause() public onlyRole(OWNER_ROLE) {
        _unpause();
    }

    function uri(uint256 id) public view override returns (string memory) {
        if (bytes(_tokenURI[id]).length == 0) revert ResourceMetadataNotSet();
        return _tokenURI[id];
    }

    /**
     * @notice Mint single resource type
     * @param account  address to mint to
     * @param id  resource ID
     * @param amount  resource amount
     * @param data  bytes data
     */
    function mint(
        address account,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) public onlyRole(MINTER_ROLE) {
        if (bytes(_tokenURI[id]).length == 0) revert ResourceMetadataNotSet();
        _mint(account, id, amount, data);
    }

    /**
     * @notice Mint multiple resource types / amounts
     * @dev Reverts if any of the resource IDs do not have metadata set
     * @param to  address to mint to
     * @param ids  array of resource IDs
     * @param amounts  array of resource amounts
     * @param data  bytes data
     */
    function mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) public onlyRole(MINTER_ROLE) {
        for (uint256 i = 0; i < ids.length; ) {
            if (bytes(_tokenURI[ids[i]]).length == 0)
                revert ResourceMetadataNotSet();
            unchecked {
                ++i;
            }
        }
        _mintBatch(to, ids, amounts, data);
    }

    /**
     * @notice Add new resource types to the contract
     * @param ids  array of resource IDs
     * @param tokenURIs array of resource URIs
     * @param names array of resource names (for indexing)
     */
    function addResources(
        uint256[] memory ids,
        string[] memory tokenURIs,
        string[] memory names
    ) public onlyRole(OWNER_ROLE) {
        if (ids.length != tokenURIs.length) revert BadInputLengths();
        for (uint256 i = 0; i < ids.length; ) {
            if (bytes(_tokenURI[ids[i]]).length != 0)
                revert ResourceUriAlreadySet();
            _tokenURI[ids[i]] = tokenURIs[i];

            emit NewResourceAdded(ids[i], names[i], tokenURIs[i]);
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Update resource metadata
     * @param ids  array of resource IDs
     * @param tokenURIs array of resource URIs
     * @param names array of resource names (for indexing)
     */
    function updateResources(
        uint256[] memory ids,
        string[] memory tokenURIs,
        string[] memory names
    ) public onlyRole(OWNER_ROLE) {
        if (ids.length != tokenURIs.length) revert BadInputLengths();
        for (uint256 i = 0; i < ids.length; ) {
            _tokenURI[ids[i]] = tokenURIs[i];
            emit NewResourceAdded(ids[i], names[i], tokenURIs[i]);
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Retrieves balance of multiple resource IDs for account
     * @param account address to retrieve balance for
     * @param ids array of resource IDs
     */
    function balanceOfBatchId(
        address account,
        uint256[] memory ids
    ) public view virtual returns (uint256[] memory) {
        uint256[] memory batchBalances = new uint256[](ids.length);

        for (uint256 i = 0; i < ids.length; ) {
            batchBalances[i] = balanceOf(account, ids[i]);
            unchecked {
                ++i;
            }
        }

        return batchBalances;
    }

    function supportsInterface(
        bytes4 interfaceId
    )
        public
        view
        override(ERC1155Upgradeable, AccessControlUpgradeable)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }

    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    )
        internal
        override(ERC1155Upgradeable, ERC1155SupplyUpgradeable)
        whenNotPaused
    {
        super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
    }

    function _authorizeUpgrade(
        address newImplementation
    ) internal override onlyRole(UPGRADER_ROLE) {}

    function _isApprovedOrOwner(address from) internal view {
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not token owner or approved"
        );
    }
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_contractOwner","type":"address"}],"name":"NotContractOwner","type":"error"},{"inputs":[{"internalType":"address","name":"_user","type":"address"},{"internalType":"address","name":"_contractOwner","type":"address"},{"internalType":"address","name":"_backendAddress","type":"address"}],"name":"NotPermitted","type":"error"},{"inputs":[],"name":"RoyaltyAddressNotSet","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract TokenEscrow","name":"_escrowContract","type":"address"}],"name":"setEscrowContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"gameContract","type":"address"}],"name":"setGameContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16[]","name":"_supportedResources","type":"uint16[]"}],"name":"setPermittedResources","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_supportedTokens","type":"address[]"}],"name":"setPermittedTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract EvrlootResources","name":"resourceContract","type":"address"}],"name":"setResourceContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tradeCommissionRateBps","type":"uint256"}],"name":"setTradeCommissionRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_collectionAddress","type":"address"},{"internalType":"uint256","name":"_tradeFeePerNft","type":"uint256"}],"name":"setTradeFeeByNft","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tradeFeePerResource","type":"uint256"}],"name":"setTradeFeePerResource","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_forwarder","type":"address"}],"name":"setTrustedForwarder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"viewEtherFeesCollected","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdrawFeesToRoyaltyAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress","type":"address"}],"name":"withdrawTokenFeesToRoyaltyAddress","outputs":[],"stateMutability":"nonpayable","type":"function"}]

608060405234801561001057600080fd5b50610bb2806100206000396000f3fe608060405234801561001057600080fd5b50600436106100e55760003560e01c80635c975abb11610097578063da74222811610066578063da742228146101a7578063efa3d2b1146101ba578063f42375b5146101cd578063f43f7677146101e057600080fd5b80635c975abb146101635780638456cb59146101795780638b8f703b14610181578063ced0cb0b1461019457600080fd5b80631f22980e146100ea57806326a86789146100ff5780632a7238981461011a5780633492ac1b1461012d57806337fd11f4146101355780633f4ba83a14610148578063405ebd4d14610150575b600080fd5b6100fd6100f836600461093a565b6101f3565b005b61010761021d565b6040519081526020015b60405180910390f35b6100fd61012836600461095e565b610232565b6100fd6102a3565b6100fd61014336600461095e565b610396565b6100fd6103b2565b6100fd61015e36600461093a565b61040a565b60015460ff166040519015158152602001610111565b6100fd610434565b6100fd61018f3660046109e2565b610471565b6100fd6101a2366004610a89565b6104e0565b6100fd6101b536600461093a565b610554565b6100fd6101c836600461093a565b61059c565b6100fd6101db36600461093a565b61066f565b6100fd6101ee366004610b18565b610699565b6101fb6106cc565b600680546001600160a01b0319166001600160a01b0392909216919091179055565b600080610228610752565b601f015492915050565b61023a6106cc565b6000610244610752565b905061271082111561029d5760405162461bcd60e51b815260206004820152601d60248201527f436f6d6d697373696f6e2072617465206578636565647320313030303000000060448201526064015b60405180910390fd5b601a0155565b6102ab6106cc565b6008546001600160a01b03166102d4576040516355316e1b60e01b815260040160405180910390fd5b60006102de610752565b601f8101805460009182905560085460405193945090926001600160a01b039091169083908381818185875af1925050503d806000811461033b576040519150601f19603f3d011682016040523d82523d6000602084013e610340565b606091505b50509050806103915760405162461bcd60e51b815260206004820152601c60248201527f4d61726b6574706c6163653a205769746864726177206661696c6564000000006044820152606401610294565b505050565b61039e6106cc565b60006103a8610752565b6019019190915550565b6103ba610776565b6001805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6103ed610859565b6040516001600160a01b03909116815260200160405180910390a1565b6104126106cc565b600480546001600160a01b0319166001600160a01b0392909216919091179055565b61043c610776565b6001805460ff1916811790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586103ed610859565b610479610776565b6000610483610752565b905060005b82518110156103915760018260040160008584815181106104ab576104ab610b44565b60209081029190910181015161ffff168252810191909152604001600020805460ff1916911515919091179055600101610488565b6104e8610776565b60006104f2610752565b905060005b825181101561039157600182600301600085848151811061051a5761051a610b44565b6020908102919091018101516001600160a01b03168252810191909152604001600020805460ff19169115159190911790556001016104f7565b61055c6106cc565b7fa58b0e7e5770dbcbf1f82b6bccb7e8e8575ed55b2db600e1987bb172f908be8580546001600160a01b0319166001600160a01b03831617905550565b50565b6105a46106cc565b60006105ae610752565b6008549091506001600160a01b03166105da576040516355316e1b60e01b815260040160405180910390fd5b6001600160a01b0382811660008181526020848101905260408082208054929055600854905163a9059cbb60e01b815293166004840152602483018190529184919063a9059cbb906044016020604051808303816000875af1158015610644573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106689190610b5a565b5050505050565b6106776106cc565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6106a16106cc565b60006106ab610752565b6001600160a01b039093166000908152601890930160205250604090912055565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c600301546001600160a01b03163314610750577fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f54604051600162bed83560e01b031981523360048201526001600160a01b039091166024820152604401610294565b565b7f9377616f5593ab73331d880ddc743bd3993c72966e3ad568028c9ceb09db255f90565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c1320547fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c906001600160a01b031633148015906107df575060038101546001600160a01b03163314155b15610599577fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f547fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c13205460405162a87e2b60e41b81523360048201526001600160a01b03928316602482015291166044820152606401610294565b6000601436108015906108705750610870336108c8565b156108c257600080368080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152505050503601516001600160a01b031691506108c59050565b50335b90565b60006001600160a01b0382166108f15760405163d92e233d60e01b815260040160405180910390fd5b507fa58b0e7e5770dbcbf1f82b6bccb7e8e8575ed55b2db600e1987bb172f908be85546001600160a01b0390811691161490565b6001600160a01b038116811461059957600080fd5b60006020828403121561094c57600080fd5b813561095781610925565b9392505050565b60006020828403121561097057600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109b6576109b6610977565b604052919050565b600067ffffffffffffffff8211156109d8576109d8610977565b5060051b60200190565b600060208083850312156109f557600080fd5b823567ffffffffffffffff811115610a0c57600080fd5b8301601f81018513610a1d57600080fd5b8035610a30610a2b826109be565b61098d565b81815260059190911b82018301908381019087831115610a4f57600080fd5b928401925b82841015610a7e57833561ffff81168114610a6f5760008081fd5b82529284019290840190610a54565b979650505050505050565b60006020808385031215610a9c57600080fd5b823567ffffffffffffffff811115610ab357600080fd5b8301601f81018513610ac457600080fd5b8035610ad2610a2b826109be565b81815260059190911b82018301908381019087831115610af157600080fd5b928401925b82841015610a7e578335610b0981610925565b82529284019290840190610af6565b60008060408385031215610b2b57600080fd5b8235610b3681610925565b946020939093013593505050565b634e487b7160e01b600052603260045260246000fd5b600060208284031215610b6c57600080fd5b8151801515811461095757600080fdfea2646970667358221220db1ce448619e2659398569de3799a2348ac1da85a1589a6924b86dd26870014764736f6c63430008180033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106100e55760003560e01c80635c975abb11610097578063da74222811610066578063da742228146101a7578063efa3d2b1146101ba578063f42375b5146101cd578063f43f7677146101e057600080fd5b80635c975abb146101635780638456cb59146101795780638b8f703b14610181578063ced0cb0b1461019457600080fd5b80631f22980e146100ea57806326a86789146100ff5780632a7238981461011a5780633492ac1b1461012d57806337fd11f4146101355780633f4ba83a14610148578063405ebd4d14610150575b600080fd5b6100fd6100f836600461093a565b6101f3565b005b61010761021d565b6040519081526020015b60405180910390f35b6100fd61012836600461095e565b610232565b6100fd6102a3565b6100fd61014336600461095e565b610396565b6100fd6103b2565b6100fd61015e36600461093a565b61040a565b60015460ff166040519015158152602001610111565b6100fd610434565b6100fd61018f3660046109e2565b610471565b6100fd6101a2366004610a89565b6104e0565b6100fd6101b536600461093a565b610554565b6100fd6101c836600461093a565b61059c565b6100fd6101db36600461093a565b61066f565b6100fd6101ee366004610b18565b610699565b6101fb6106cc565b600680546001600160a01b0319166001600160a01b0392909216919091179055565b600080610228610752565b601f015492915050565b61023a6106cc565b6000610244610752565b905061271082111561029d5760405162461bcd60e51b815260206004820152601d60248201527f436f6d6d697373696f6e2072617465206578636565647320313030303000000060448201526064015b60405180910390fd5b601a0155565b6102ab6106cc565b6008546001600160a01b03166102d4576040516355316e1b60e01b815260040160405180910390fd5b60006102de610752565b601f8101805460009182905560085460405193945090926001600160a01b039091169083908381818185875af1925050503d806000811461033b576040519150601f19603f3d011682016040523d82523d6000602084013e610340565b606091505b50509050806103915760405162461bcd60e51b815260206004820152601c60248201527f4d61726b6574706c6163653a205769746864726177206661696c6564000000006044820152606401610294565b505050565b61039e6106cc565b60006103a8610752565b6019019190915550565b6103ba610776565b6001805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6103ed610859565b6040516001600160a01b03909116815260200160405180910390a1565b6104126106cc565b600480546001600160a01b0319166001600160a01b0392909216919091179055565b61043c610776565b6001805460ff1916811790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586103ed610859565b610479610776565b6000610483610752565b905060005b82518110156103915760018260040160008584815181106104ab576104ab610b44565b60209081029190910181015161ffff168252810191909152604001600020805460ff1916911515919091179055600101610488565b6104e8610776565b60006104f2610752565b905060005b825181101561039157600182600301600085848151811061051a5761051a610b44565b6020908102919091018101516001600160a01b03168252810191909152604001600020805460ff19169115159190911790556001016104f7565b61055c6106cc565b7fa58b0e7e5770dbcbf1f82b6bccb7e8e8575ed55b2db600e1987bb172f908be8580546001600160a01b0319166001600160a01b03831617905550565b50565b6105a46106cc565b60006105ae610752565b6008549091506001600160a01b03166105da576040516355316e1b60e01b815260040160405180910390fd5b6001600160a01b0382811660008181526020848101905260408082208054929055600854905163a9059cbb60e01b815293166004840152602483018190529184919063a9059cbb906044016020604051808303816000875af1158015610644573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106689190610b5a565b5050505050565b6106776106cc565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6106a16106cc565b60006106ab610752565b6001600160a01b039093166000908152601890930160205250604090912055565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c600301546001600160a01b03163314610750577fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f54604051600162bed83560e01b031981523360048201526001600160a01b039091166024820152604401610294565b565b7f9377616f5593ab73331d880ddc743bd3993c72966e3ad568028c9ceb09db255f90565b7fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c1320547fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131c906001600160a01b031633148015906107df575060038101546001600160a01b03163314155b15610599577fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f547fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c13205460405162a87e2b60e41b81523360048201526001600160a01b03928316602482015291166044820152606401610294565b6000601436108015906108705750610870336108c8565b156108c257600080368080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152505050503601516001600160a01b031691506108c59050565b50335b90565b60006001600160a01b0382166108f15760405163d92e233d60e01b815260040160405180910390fd5b507fa58b0e7e5770dbcbf1f82b6bccb7e8e8575ed55b2db600e1987bb172f908be85546001600160a01b0390811691161490565b6001600160a01b038116811461059957600080fd5b60006020828403121561094c57600080fd5b813561095781610925565b9392505050565b60006020828403121561097057600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156109b6576109b6610977565b604052919050565b600067ffffffffffffffff8211156109d8576109d8610977565b5060051b60200190565b600060208083850312156109f557600080fd5b823567ffffffffffffffff811115610a0c57600080fd5b8301601f81018513610a1d57600080fd5b8035610a30610a2b826109be565b61098d565b81815260059190911b82018301908381019087831115610a4f57600080fd5b928401925b82841015610a7e57833561ffff81168114610a6f5760008081fd5b82529284019290840190610a54565b979650505050505050565b60006020808385031215610a9c57600080fd5b823567ffffffffffffffff811115610ab357600080fd5b8301601f81018513610ac457600080fd5b8035610ad2610a2b826109be565b81815260059190911b82018301908381019087831115610af157600080fd5b928401925b82841015610a7e578335610b0981610925565b82529284019290840190610af6565b60008060408385031215610b2b57600080fd5b8235610b3681610925565b946020939093013593505050565b634e487b7160e01b600052603260045260246000fd5b600060208284031215610b6c57600080fd5b8151801515811461095757600080fdfea2646970667358221220db1ce448619e2659398569de3799a2348ac1da85a1589a6924b86dd26870014764736f6c63430008180033

Block Transaction Gas Used Reward
view all blocks collator

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

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

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.