Contract Address Details

0x3D23641d0765C1618aFa660bFF48A9F681A0422D

Contract Name
NewbieVilla
Creator
0xe01c8d–e085f7 at 0x327a47–5a1e24
Balance
0 CSB
Tokens
Fetching tokens...
Transactions
1 Transactions
Transfers
0 Transfers
Gas Used
21,000
Last Balance Update
81779655
Contract name:
NewbieVilla




Optimization enabled
true
Compiler version
v0.8.18+commit.87f61d96




Optimization runs
200
EVM Version
default




Verified at
2023-10-16T08:06:49.378131Z

Contract source code

// SPDX-License-Identifier: MIT
// solhint-disable comprehensive-interface
pragma solidity 0.8.18;

// solhint-disable contract-name-camelcase

// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

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

/**
 * @title DataTypes
 * @notice A standard library of data types.
 */
library DataTypes {
    struct MigrateData {
        address account;
        string handle;
        string uri;
        address[] toAddresses;
        bytes32 linkType;
    }

    struct CreateCharacterData {
        address to;
        string handle;
        string uri;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct createThenLinkCharacterData {
        uint256 fromCharacterId;
        address to;
        bytes32 linkType;
    }

    struct linkNoteData {
        uint256 fromCharacterId;
        uint256 toCharacterId;
        uint256 toNoteId;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkNoteData {
        uint256 fromCharacterId;
        uint256 toCharacterId;
        uint256 toNoteId;
        bytes32 linkType;
    }

    struct linkCharacterData {
        uint256 fromCharacterId;
        uint256 toCharacterId;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkCharacterData {
        uint256 fromCharacterId;
        uint256 toCharacterId;
        bytes32 linkType;
    }

    struct linkERC721Data {
        uint256 fromCharacterId;
        address tokenAddress;
        uint256 tokenId;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkERC721Data {
        uint256 fromCharacterId;
        address tokenAddress;
        uint256 tokenId;
        bytes32 linkType;
    }

    struct linkAddressData {
        uint256 fromCharacterId;
        address ethAddress;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkAddressData {
        uint256 fromCharacterId;
        address ethAddress;
        bytes32 linkType;
    }

    struct linkAnyUriData {
        uint256 fromCharacterId;
        string toUri;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkAnyUriData {
        uint256 fromCharacterId;
        string toUri;
        bytes32 linkType;
    }

    struct linkLinklistData {
        uint256 fromCharacterId;
        uint256 toLinkListId;
        bytes32 linkType;
        bytes data;
    }

    struct unlinkLinklistData {
        uint256 fromCharacterId;
        uint256 toLinkListId;
        bytes32 linkType;
    }

    struct setLinkModule4CharacterData {
        uint256 characterId;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct setLinkModule4NoteData {
        uint256 characterId;
        uint256 noteId;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct setLinkModule4LinklistData {
        uint256 linklistId;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct setLinkModule4ERC721Data {
        address tokenAddress;
        uint256 tokenId;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct setLinkModule4AddressData {
        address account;
        address linkModule;
        bytes linkModuleInitData;
    }

    struct setMintModule4NoteData {
        uint256 characterId;
        uint256 noteId;
        address mintModule;
        bytes mintModuleInitData;
    }

    struct linkCharactersInBatchData {
        uint256 fromCharacterId;
        uint256[] toCharacterIds;
        bytes[] data;
        address[] toAddresses;
        bytes32 linkType;
    }

    struct LinkData {
        uint256 linklistId;
        uint256 linkItemType;
        uint256 linkingCharacterId;
        address linkingAddress;
        uint256 linkingLinklistId;
        bytes32 linkKey;
    }

    struct PostNoteData {
        uint256 characterId;
        string contentUri;
        address linkModule;
        bytes linkModuleInitData;
        address mintModule;
        bytes mintModuleInitData;
        bool locked;
    }

    struct MintNoteData {
        uint256 characterId;
        uint256 noteId;
        address to;
        bytes mintModuleData;
    }

    // character struct
    struct Character {
        uint256 characterId;
        string handle;
        string uri;
        uint256 noteCount;
        address socialToken;
        address linkModule;
    }

    /**
     * @dev A struct containing data associated with each new note.
     * @param linkItemType The link type of this note, if the note is a note with link.
     * @param linkKey If linkKey is not empty, it is a note with link(eg.a comment to a character or a note).
     * @param contentURI The URI associated with this note.
     * @param linkModule The address of the current link module of this note, can be empty.
     * @param mintModule  The address of the current mint module of this note, can be empty.
     * @param mintNFT The address of the mintNFT associated with this note, if any.
     * @param deleted Whether the note is deleted.
     * @param locked Whether the note is locked. If the note is locked, its owner can't set not uri anymore.
     */
    struct Note {
        bytes32 linkItemType;
        bytes32 linkKey;
        string contentUri;
        address linkModule;
        address mintModule;
        address mintNFT;
        bool deleted;
        bool locked;
    }

    struct CharacterLinkStruct {
        uint256 fromCharacterId;
        uint256 toCharacterId;
        bytes32 linkType;
    }

    struct NoteStruct {
        uint256 characterId;
        uint256 noteId;
    }

    struct ERC721Struct {
        address tokenAddress;
        uint256 erc721TokenId;
    }

    /**
     @param blocklist The list of blocklist addresses.
     @param allowlist The list of allowlist addresses.
     */
    struct Operators4Note {
        EnumerableSet.AddressSet blocklist;
        EnumerableSet.AddressSet allowlist;
    }

    /**
     * @dev A struct containing the necessary information to reconstruct an EIP-712 typed data signature.
     * @param signer The address of the signer.
     * @param v The signature's recovery parameter.
     * @param r The signature's r parameter.
     * @param s The signature's s parameter
     * @param deadline The signature's deadline.
     */
    struct EIP712Signature {
        address signer;
        uint8 v;
        bytes32 r;
        bytes32 s;
        uint256 deadline;
    }
}

interface IWeb3Entry {
    /**
     * @notice Initializes the Web3Entry.
     * @param name_ The name to set for the web3Entry character NFT.
     * @param symbol_ The symbol to set for the web3Entry character NFT.
     * @param linklist_ The address of linklist contract to set.
     * @param mintNFTImpl_ The address of mintNFTImpl contract to set.
     * @param periphery_ The address of periphery contract to set.
     * @param newbieVilla_ The address of newbieVilla contract to set.
     */
    function initialize(
        string calldata name_,
        string calldata symbol_,
        address linklist_,
        address mintNFTImpl_,
        address periphery_,
        address newbieVilla_
    ) external;

    /**
     * This method creates a character with the given parameters to the given address.
     *
     * @param vars The CreateCharacterData struct containing the following parameters:
     * `to`: The address receiving the character.<br>
     * `handle`: The handle to set for the character.<br>
     * `uri`: The URI to set for the character metadata.<br>
     * `linkModule`: The link module to use, can be the zero address.<br>
     * `linkModuleInitData`: The link module initialization data, if any.<br>
     */
    function createCharacter(
        DataTypes.CreateCharacterData calldata vars
    ) external returns (uint256 characterId);

    /**
     * @notice  Sets new handle for a given character.
     * @dev Owner permission only.
     * @param   characterId  The character id to set new handle for.
     * @param   newHandle  New handle to set.
     */
    function setHandle(uint256 characterId, string calldata newHandle) external;

    /**
     * @notice  Sets a social token for a given character.
     * @dev Owner permission only.
     * @param   characterId  The characterId to set social token for.
     * @param   tokenAddress  Token address to be set.
     */
    function setSocialToken(uint256 characterId, address tokenAddress) external;

    /**
     * @notice  Sets a new URI for a given character.
     * @param   characterId  The characterId to to be set.
     * @param   newUri  New URI to be set.
     */
    function setCharacterUri(uint256 characterId, string calldata newUri) external;

    /**
     * @notice  Sets a given character as primary.
     * @dev Only character owner can call this function.
     * @param   characterId  The character id to to be set.
     */
    function setPrimaryCharacterId(uint256 characterId) external;

    /**
     * @notice Grant an address as an operator and authorize it with custom permissions.
     * @param characterId ID of your character that you want to authorize.
     * @param operator Address to grant operator permissions to.
     * @param permissionBitMap Bitmap used for finer grained operator permissions controls.
     * @dev Every bit in permissionBitMap stands for a corresponding method in Web3Entry. more details in OP.sol.
     */
    function grantOperatorPermissions(
        uint256 characterId,
        address operator,
        uint256 permissionBitMap
    ) external;

    /**
     * @notice Grant an address as an operator and authorize it with custom permissions via signature.
     * @dev Only character owner can call.
     * @param characterId ID of your character that you want to authorize.
     * @param operator Address to grant operator permissions to.
     * @param permissionBitMap Bitmap used for finer grained operator permissions controls.
     * @param signature The EIP712Signature struct containing the character owner's signature.
     * @dev Every bit in permissionBitMap stands for a corresponding method in Web3Entry. more details in OP.sol.
     */
    function grantOperatorPermissionsWithSig(
        uint256 characterId,
        address operator,
        uint256 permissionBitMap,
        DataTypes.EIP712Signature calldata signature
    ) external;

    /**
     * @notice Grant operators allowlist and blocklist roles of a note.
     * @param characterId ID of character that you want to set.
     * @param noteId ID of note that you want to set.
     * @param blocklist blocklist addresses that you want to grant.
     * @param allowlist allowlist addresses that you want to grant.
     */
    function grantOperators4Note(
        uint256 characterId,
        uint256 noteId,
        address[] calldata blocklist,
        address[] calldata allowlist
    ) external;

    /**
     * @notice Sets a new metadataURI for a given link list.
     * @param linkListId The linklist id to set for.
     * @param uri The metadata uri to set.
     */
    function setLinklistUri(uint256 linkListId, string calldata uri) external;

    /**
     * @notice Sets a link type for a given linklist.
     * @dev Emits a {DetachLinklist} event and a {AttachLinklist} event from web3Entry contract..<br>
     * Emits a {LinkTypeSet} event from linklist contract.<br>
     * Linklist is the group of all linking objects with the same link type, like "like".<br>
     * Each character can only have one linklist for each link type.<br>
     * It will fail if you try to set a link type which is already set for some linklist owned by the same character.
     * @param linkListId The linklist ID to set for.
     * @param linkType The link type to set.
     */
    function setLinklistType(uint256 linkListId, bytes32 linkType) external;

    /**
     * @notice Links an address with the given parameters.
     * @param vars The linkAddressData struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `ethAddress`: The address to be linked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkAddress(DataTypes.linkAddressData calldata vars) external;

    /**
     * @notice Unlinks an address with the given parameters.
     * @param vars The unlinkAddressData struct containing the unlinking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `ethAddress`: The address to be unlinked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     */
    function unlinkAddress(DataTypes.unlinkAddressData calldata vars) external;

    /**
     * @notice Links a character with the given parameters.
     * @param vars The linkCharacterData struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `toCharacterId`: The character ID to be linked.<br>
     * `linkType`: The link type, like "follow", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkCharacter(DataTypes.linkCharacterData calldata vars) external;

    /**
     * @notice Unlinks a character with the given parameters.
     * @param vars The unlinkCharacterData struct containing the unlinking parameters:
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `toCharacterId`: The character ID to be unlinked.<br>
     * `linkType`: The link type, like "follow", which is a bytes32 format.<br>
     */
    function unlinkCharacter(DataTypes.unlinkCharacterData calldata vars) external;

    /**
     * @notice Create a character and then link it.
     * @param vars The createThenLinkCharacterData struct containing the parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `to`: The address to receive the new character nft.<br>
     * `linkType`: The link type, like "follow", which is a bytes32 format.<br>
     */
    function createThenLinkCharacter(
        DataTypes.createThenLinkCharacterData calldata vars
    ) external returns (uint256 characterId);

    /**
     * @notice Links a note with the given parameters.
     * @param vars The linkNoteData struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `toCharacterId`: The character ID of note to be linked.<br>
     * `toNoteId`: The note ID of note to be linked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkNote(DataTypes.linkNoteData calldata vars) external;

    /**
     * @notice UnLinks a note with the given parameters.
     * @param vars The unlinkNoteData struct containing the unlinking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `toCharacterId`: The character ID of note to be unlinked.<br>
     * `toNoteId`: The note ID of note to be unlinked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     */
    function unlinkNote(DataTypes.unlinkNoteData calldata vars) external;

    /**
     * @notice Links an ERC721 with the given parameters.
     * @param vars The linkERC721Data struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `tokenAddress`: The token address of ERC721 to be linked.<br>
     * `tokenId`: The token ID of ERC721 to be linked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkERC721(DataTypes.linkERC721Data calldata vars) external;

    /**
     * @notice Unlinks an ERC721 with the given parameters.
     * @param vars The unlinkERC721Data struct containing the unlinking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `tokenAddress`: The token address of ERC721 to be unlinked.<br>
     * `tokenId`: The token ID of ERC721 to be unlinked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     */
    function unlinkERC721(DataTypes.unlinkERC721Data calldata vars) external;

    /**
     * @notice Links any uri with the given parameters.
     * @param vars The linkAnyUriData struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `toUri`: The uri to be linked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkAnyUri(DataTypes.linkAnyUriData calldata vars) external;

    /**
     * @notice Unlinks any uri with the given parameters.
     * @param vars The unlinkAnyUriData struct containing the unlinking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `toUri`: The uri to be unlinked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     */
    function unlinkAnyUri(DataTypes.unlinkAnyUriData calldata vars) external;

    /**
     * @notice Links a linklist with the given parameters.
     * @param vars The linkLinklistData struct containing the linking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a link action.<br>
     * `toLinkListId`: The linklist ID to be linked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     * `data`: The data passed to the link module to use, if any.<br>
     */
    function linkLinklist(DataTypes.linkLinklistData calldata vars) external;

    /**
     * @notice Unlinks a linklist with the given parameters.
     * @param vars The unlinkLinklistData struct containing the unlinking parameters:<br>
     * `fromCharacterId`: The character ID to sponsor a unlink action.<br>
     * `toLinkListId`: The linklist ID to be unlinked.<br>
     * `linkType`: The link type, like "like", which is a bytes32 format.<br>
     */
    function unlinkLinklist(DataTypes.unlinkLinklistData calldata vars) external;

    /**
     * @notice Sets a link module for a given character.
     * @param vars The setLinkModule4CharacterData struct containing the parameters:<br>
     * `characterId`: The character ID to set for.<br>
     * `linkModule`: The address of link module contract to set.<br>
     * `linkModuleInitData`: The data passed to the link module to use, if any.<br>
     */
    function setLinkModule4Character(DataTypes.setLinkModule4CharacterData calldata vars) external;

    /**
     * @notice Sets a link module for a given note.
     * @param vars The setLinkModule4NoteData struct containing the parameters:<br>
     * `characterId`: The character ID to set for.<br>
     * `noteId`: The note ID to set for.<br>
     * `linkModule`: The address of link module contract to set.<br>
     * `linkModuleInitData`: The data passed to the link module to use, if any.<br>
     */
    function setLinkModule4Note(DataTypes.setLinkModule4NoteData calldata vars) external;

    /**
     * @notice Mints an nft with the given note.
     * @param vars The MintNoteData struct containing the minting parameters:<br>
     * `characterId`: The character ID of the note.<br>
     * `noteId`: The note ID of the note.<br>
     * `to`: The address to receive the minted nft.<br>
     * `data`: The data passed to the mint module to use, if any.<br>
     */
    function mintNote(DataTypes.MintNoteData calldata vars) external returns (uint256 tokenId);

    /**
     * @notice Sets a mint module for the given note.
     * @param vars The setMintModule4NoteData struct containing the setting parameters:<br>
     * `characterId`: The character ID of the note.<br>
     * `noteId`: The note ID of the note.<br>
     * `mintModule`: The address of mint module to set.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     */
    function setMintModule4Note(DataTypes.setMintModule4NoteData calldata vars) external;

    /**
     * @notice Posts a note with the given parameters.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     */
    function postNote(DataTypes.PostNoteData calldata vars) external returns (uint256 noteId);

    /**
     * @notice  Set URI for a note.
     * @param   characterId  The character ID of the note owner.
     * @param   noteId  The ID of the note to set.
     * @param   newUri  The new URI.
     */
    function setNoteUri(uint256 characterId, uint256 noteId, string calldata newUri) external;

    /**
     * @notice  Lock a note and put it into a immutable state where no modifications are 
     allowed. Locked notes are usually assumed as final versions.
     * @param   characterId  The character ID of the note owner.
     * @param   noteId  The ID of the note to lock.
     */
    function lockNote(uint256 characterId, uint256 noteId) external;

    /**
     * @notice  Delete a note.
     * @dev     Deleting a note doesn't essentially mean that the txs or contents are being removed due to the
     * immutability of blockchain itself, but the deleted notes will be tagged as `deleted` after calling `deleteNote`.
     * @param   characterId  The character ID of the note owner.
     * @param   noteId  The ID of the note to delete.
     */
    function deleteNote(uint256 characterId, uint256 noteId) external;

    /**
     * @notice Posts a note for a given character.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param toCharacterId The target character ID.
     * @return noteId The note ID of the new post.
     */
    function postNote4Character(
        DataTypes.PostNoteData calldata vars,
        uint256 toCharacterId
    ) external returns (uint256 noteId);

    /**
     * @notice Posts a note for a given address.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param ethAddress The target address.
     * @return noteId The note ID of the new post.
     */
    function postNote4Address(
        DataTypes.PostNoteData calldata vars,
        address ethAddress
    ) external returns (uint256 noteId);

    /**
     * @notice Posts a note for a given linklist.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param toLinklistId The target linklist.
     * @return noteId The note ID of the new post.
     */
    function postNote4Linklist(
        DataTypes.PostNoteData calldata vars,
        uint256 toLinklistId
    ) external returns (uint256 noteId);

    /**
     * @notice Posts a note for a given note.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param note The target note struct containing the parameters:<br>
     * `characterId`: The character ID of target note.<br>
     * `noteId`: The note ID of target note.
     * @return noteId The note ID of the new post.
     */
    function postNote4Note(
        DataTypes.PostNoteData calldata vars,
        DataTypes.NoteStruct calldata note
    ) external returns (uint256 noteId);

    /**
     * @notice Posts a note for a given ERC721.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param erc721 The target ERC721 struct containing the parameters:<br>
     * `tokenAddress`: The token address of target ERC721.<br>
     * `erc721TokenId`: The token ID of target ERC721.
     * @return noteId The note ID of the new post.
     */
    function postNote4ERC721(
        DataTypes.PostNoteData calldata vars,
        DataTypes.ERC721Struct calldata erc721
    ) external returns (uint256 noteId);

    /**
     * @notice Posts a note for a given uri.
     * @param vars The postNoteData struct containing the posting parameters:<br>
     * `characterId`: The character ID to post to.<br>
     * `contentUri`: The uri to set for the new post.<br>
     * `linkModule`: The address of link module to set for the new post.<br>
     * `linkModuleInitData`: The data passed to the link module to init, if any.<br>
     * `mintModule`: The address of mint module to set for the new post.<br>
     * `mintModuleInitData`: The data passed to the mint module to init, if any.<br>
     * @param uri The target uri(could be an url link).
     * @return noteId The note ID of the new post.
     */
    function postNote4AnyUri(
        DataTypes.PostNoteData calldata vars,
        string calldata uri
    ) external returns (uint256 noteId);

    /**
     * @notice Burns a linklist NFT.
     * @dev It will burn the linklist NFT and remove the links from a character.
     * @param linklistId The linklist ID to burn.
     */
    function burnLinklist(uint256 linklistId) external;

    /**
     * @notice Get operator list of a character. This operator list has only a sole purpose, which is
     * keeping records of keys of `operatorsPermissionBitMap`. Thus, addresses queried by this function
     * not always have operator permissions. Keep in mind don't use this function to check
     * authorizations!!!
     * @param characterId ID of your character that you want to check.
     * @return All keys of operatorsPermission4NoteBitMap.
     */
    function getOperators(uint256 characterId) external view returns (address[] memory);

    /**
     * @notice Get permission bitmap of an operator.
     * @param characterId ID of character that you want to check.
     * @param operator Address to grant operator permissions to.
     * @return Permission bitmap of this operator.
     */
    function getOperatorPermissions(
        uint256 characterId,
        address operator
    ) external view returns (uint256);

    /**
     * @notice Get operators blocklist and allowlist for a note.
     * @param characterId ID of character to query.
     * @param noteId ID of note to query.
     */
    function getOperators4Note(
        uint256 characterId,
        uint256 noteId
    ) external view returns (address[] memory blocklist, address[] memory allowlist);

    /**
     * @notice Query if a operator has permission for a note.
     * @param characterId ID of character that you want to query.
     * @param noteId ID of note that you want to query.
     * @param operator Address to query.
     * @return true if Operator has permission for a note, otherwise false.
     */
    function isOperatorAllowedForNote(
        uint256 characterId,
        uint256 noteId,
        address operator
    ) external view returns (bool);

    /**
     * @notice Returns primary character for a given account.
     * @param account The address to query.
     * @return uint256 The primary character ID, which will be 0 if not mapped.
     */
    function getPrimaryCharacterId(address account) external view returns (uint256);

    /**
     * @notice Returns whether or not a character is primary character.
     * @param characterId The character ID to query.
     * @return bool True if the character is primary, false otherwise.
     */
    function isPrimaryCharacter(uint256 characterId) external view returns (bool);

    /**
     * @notice Returns the full character struct associated with a given character token ID.
     * @param characterId The token ID of the character to query.
     * @return The full character struct of given character.
     */
    function getCharacter(uint256 characterId) external view returns (DataTypes.Character memory);

    /**
     * @notice Returns the full character struct associated with a given character handle.
     * @param handle The handle of the character to query.
     * @return The full character struct of given character.
     */
    function getCharacterByHandle(
        string calldata handle
    ) external view returns (DataTypes.Character memory);

    /**
     * @notice Returns the handle of character with a given character.
     * @param characterId The token ID of the character to query.
     * @return The handle of given character.
     */
    function getHandle(uint256 characterId) external view returns (string memory);

    /**
     * @notice Returns the uri of character with a given character.
     * @param characterId The token ID of the character to query.
     * @return The uri of given character.
     */
    function getCharacterUri(uint256 characterId) external view returns (string memory);

    /**
     * @notice Returns the full note struct associated with a given note.
     * @param characterId The token ID of the character to query.
     * @param noteId The token ID of the note to query.
     * @return The full note struct of given note.
     */
    function getNote(
        uint256 characterId,
        uint256 noteId
    ) external view returns (DataTypes.Note memory);

    /**
     * @notice Returns the uri of linklist with a given linklist.
     * @param tokenId The token ID of the linklist to query.
     * @return string The uri of given linklist.
     */
    function getLinklistUri(uint256 tokenId) external view returns (string memory);

    /**
     * @notice Returns the token ID of linklist with a given character and linkType.
     * @param characterId The token ID of the character to query.
     * @param linkType The linkType.
     * @return The token ID of linklist.
     */
    function getLinklistId(uint256 characterId, bytes32 linkType) external view returns (uint256);

    /**
     * @notice Returns the linkType of linklist with a given linklist.
     * @param linkListId The token ID of the linklist to query.
     * @return bytes32 The linkType of given linklist.
     */
    function getLinklistType(uint256 linkListId) external view returns (bytes32);

    /**
     * @notice Returns the address of linklist contract.
     * @return The address of linklist contract.
     */
    function getLinklistContract() external view returns (address);

    /**
     * @notice Returns the domain separator for this NFT contract.
     * @return bytes32 The domain separator.
     */
    function getDomainSeparator() external view returns (bytes32);

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

    /**
     * @notice Returns the revision number of web3Entry contract.
     * @return The the revision number of web3Entry contract.
     */
    function getRevision() external pure returns (uint256);
}

// solhint-disable private-vars-leading-underscore

/**
* In Crossbell's operator system, every uint8 stands for a single method in Web3Entry.sol. <br>
* For most cases, we recommend simply granting operators the `OPERATOR_SIGN_PERMISSION_BITMAP`,
* which gives operator full permissions aside from owner permissions and future permissions, but for
* those who're more aware of access control, the custom permission bitmap is all yours,
* and you can find every customizable methods below. <br>

* `OPERATOR_SIGN_PERMISSION_BITMAP` have access to all methods in `OPERATOR_SYNC_PERMISSION_BITMAP`
* plus more permissions for signing. <br>

* Permissions are laid out in a increasing order of power.
* so the bitmap looks like this:

<table>
    <colgroup>
        <col style="width: 25%">
        <col style="width: 25%">
        <col style="width: 25%">
        <col style="width: 25%">
    </colgroup>
    <tr>
        <td>operator sync</td>
        <td>operator sign</td>
        <td>future reserved</td>
        <td>owner</td>
    <tr>
    <tr>
        <td>[255 - 236]</td>
        <td>[235 - 176]</td>
        <td>[175 - 21]</td>
        <td>[20 - 0]</td>
    <tr>
</table>

*/

library OP {
    uint256 internal constant UINT256_MAX = ~uint256(0);

    // [0,20] for owner permissions
    uint8 internal constant SET_HANDLE = 0;
    uint8 internal constant SET_SOCIAL_TOKEN = 1;
    uint8 internal constant GRANT_OPERATOR_PERMISSIONS = 2;
    // uint8 internal constant GRANT_OPERATOR_PERMISSIONS_FOR_NOTE = 3;
    uint8 internal constant GRANT_OPERATORS_FOR_NOTE = 3;
    // set [0, 3] bit index
    uint256 internal constant OWNER_PERMISSION_BITMAP = ~(UINT256_MAX << 4);

    // [21, 175] are reserved for future

    // [176, 235] for operator sign permissions
    uint8 internal constant SET_CHARACTER_URI = 176;
    uint8 internal constant SET_LINKLIST_URI = 177;
    uint8 internal constant LINK_CHARACTER = 178;
    uint8 internal constant UNLINK_CHARACTER = 179;
    uint8 internal constant CREATE_THEN_LINK_CHARACTER = 180;
    uint8 internal constant LINK_NOTE = 181;
    uint8 internal constant UNLINK_NOTE = 182;
    uint8 internal constant LINK_ERC721 = 183;
    uint8 internal constant UNLINK_ERC721 = 184;
    uint8 internal constant LINK_ADDRESS = 185;
    uint8 internal constant UNLINK_ADDRESS = 186;
    uint8 internal constant LINK_ANYURI = 187;
    uint8 internal constant UNLINK_ANYURI = 188;
    uint8 internal constant LINK_LINKLIST = 189;
    uint8 internal constant UNLINK_LINKLIST = 190;
    uint8 internal constant SET_LINK_MODULE_FOR_CHARACTER = 191;
    uint8 internal constant SET_LINK_MODULE_FOR_NOTE = 192;
    uint8 internal constant SET_LINK_MODULE_FOR_LINKLIST = 193;
    uint8 internal constant SET_MINT_MODULE_FOR_NOTE = 194;
    uint8 internal constant SET_NOTE_URI = 195;
    uint8 internal constant LOCK_NOTE = 196;
    uint8 internal constant DELETE_NOTE = 197;
    // post note
    uint8 internal constant POST_NOTE_FOR_CHARACTER = 198;
    uint8 internal constant POST_NOTE_FOR_ADDRESS = 199;
    uint8 internal constant POST_NOTE_FOR_LINKLIST = 200;
    uint8 internal constant POST_NOTE_FOR_NOTE = 201;
    uint8 internal constant POST_NOTE_FOR_ERC721 = 202;
    uint8 internal constant POST_NOTE_FOR_ANYURI = 203;
    // set linklist type
    uint8 internal constant SET_LINKLIST_TYPE = 204;
    // set [176,204] bit index

    // [236, 255] for operator sync permissions
    uint8 internal constant POST_NOTE = 236;
    // set 236 bit index
    uint256 internal constant POST_NOTE_PERMISSION_BITMAP = 1 << POST_NOTE;

    // POST_NOTE_DEFAULT_PERMISSION_BITMAP has post note related permissions
    uint256 internal constant POST_NOTE_DEFAULT_PERMISSION_BITMAP =
        ((UINT256_MAX << 198) & ~(UINT256_MAX << 204)) | POST_NOTE_PERMISSION_BITMAP;

    // DEFAULT_PERMISSION_BITMAP has operator sign permissions and operator sync permissions
    uint256 internal constant DEFAULT_PERMISSION_BITMAP =
        ((UINT256_MAX << 176) & ~(UINT256_MAX << 205)) | POST_NOTE_PERMISSION_BITMAP;

    // bitmap mask with all current-in-use methods to 1
    uint256 internal constant ALLOWED_PERMISSION_BITMAP_MASK =
        OWNER_PERMISSION_BITMAP | DEFAULT_PERMISSION_BITMAP;
}

// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

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

// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)

// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

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

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

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

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

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

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

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

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

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

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

// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

// OpenZeppelin Contracts v4.4.1 (utils/Context.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 Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

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

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

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

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

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

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

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

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

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

        _revokeRole(role, account);
    }

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

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

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

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

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

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

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

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

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

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

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

// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

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

// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)

/**
 * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
 *
 * Accounts can be notified of {IERC777} tokens being sent to them by having a
 * contract implement this interface (contract holders can be their own
 * implementer) and registering it on the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
 *
 * See {IERC1820Registry} and {ERC1820Implementer}.
 */
interface IERC777Recipient {
    /**
     * @dev Called by an {IERC777} token contract whenever tokens are being
     * moved or created into a registered account (`to`). The type of operation
     * is conveyed by `from` being the zero address or not.
     *
     * This call occurs _after_ the token contract's state is updated, so
     * {IERC777-balanceOf}, etc., can be used to query the post-operation state.
     *
     * This function may revert to prevent the operation from being executed.
     */
    function tokensReceived(
        address operator,
        address from,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external;
}

// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.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);
}

// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC777/IERC777.sol)

/**
 * @dev Interface of the ERC777Token standard as defined in the EIP.
 *
 * This contract uses the
 * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
 * token holders and recipients react to token movements by using setting implementers
 * for the associated interfaces in said registry. See {IERC1820Registry} and
 * {ERC1820Implementer}.
 */
interface IERC777 {
    /**
     * @dev Emitted when `amount` tokens are created by `operator` and assigned to `to`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` destroys `amount` tokens from `account`.
     *
     * Note that some additional user `data` and `operatorData` can be logged in the event.
     */
    event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);

    /**
     * @dev Emitted when `operator` is made operator for `tokenHolder`.
     */
    event AuthorizedOperator(address indexed operator, address indexed tokenHolder);

    /**
     * @dev Emitted when `operator` is revoked its operator status for `tokenHolder`.
     */
    event RevokedOperator(address indexed operator, address indexed tokenHolder);

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the smallest part of the token that is not divisible. This
     * means all token operations (creation, movement and destruction) must have
     * amounts that are a multiple of this number.
     *
     * For most token contracts, this value will equal 1.
     */
    function granularity() external view returns (uint256);

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

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * If send or receive hooks are registered for the caller and `recipient`,
     * the corresponding functions will be called with `data` and empty
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function send(address recipient, uint256 amount, bytes calldata data) external;

    /**
     * @dev Destroys `amount` tokens from the caller's account, reducing the
     * total supply.
     *
     * If a send hook is registered for the caller, the corresponding function
     * will be called with `data` and empty `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - the caller must have at least `amount` tokens.
     */
    function burn(uint256 amount, bytes calldata data) external;

    /**
     * @dev Returns true if an account is an operator of `tokenHolder`.
     * Operators can send and burn tokens on behalf of their owners. All
     * accounts are their own operator.
     *
     * See {operatorSend} and {operatorBurn}.
     */
    function isOperatorFor(address operator, address tokenHolder) external view returns (bool);

    /**
     * @dev Make an account an operator of the caller.
     *
     * See {isOperatorFor}.
     *
     * Emits an {AuthorizedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function authorizeOperator(address operator) external;

    /**
     * @dev Revoke an account's operator status for the caller.
     *
     * See {isOperatorFor} and {defaultOperators}.
     *
     * Emits a {RevokedOperator} event.
     *
     * Requirements
     *
     * - `operator` cannot be calling address.
     */
    function revokeOperator(address operator) external;

    /**
     * @dev Returns the list of default operators. These accounts are operators
     * for all token holders, even if {authorizeOperator} was never called on
     * them.
     *
     * This list is immutable, but individual holders may revoke these via
     * {revokeOperator}, in which case {isOperatorFor} will return false.
     */
    function defaultOperators() external view returns (address[] memory);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
     * be an operator of `sender`.
     *
     * If send or receive hooks are registered for `sender` and `recipient`,
     * the corresponding functions will be called with `data` and
     * `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
     *
     * Emits a {Sent} event.
     *
     * Requirements
     *
     * - `sender` cannot be the zero address.
     * - `sender` must have at least `amount` tokens.
     * - the caller must be an operator for `sender`.
     * - `recipient` cannot be the zero address.
     * - if `recipient` is a contract, it must implement the {IERC777Recipient}
     * interface.
     */
    function operatorSend(
        address sender,
        address recipient,
        uint256 amount,
        bytes calldata data,
        bytes calldata operatorData
    ) external;

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the total supply.
     * The caller must be an operator of `account`.
     *
     * If a send hook is registered for `account`, the corresponding function
     * will be called with `data` and `operatorData`. See {IERC777Sender}.
     *
     * Emits a {Burned} event.
     *
     * Requirements
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     * - the caller must be an operator for `account`.
     */
    function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external;

    event Sent(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256 amount,
        bytes data,
        bytes operatorData
    );
}

// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/IERC1820Registry.sol)

/**
 * @dev Interface of the global ERC1820 Registry, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
 * implementers for interfaces in this registry, as well as query support.
 *
 * Implementers may be shared by multiple accounts, and can also implement more
 * than a single interface for each account. Contracts can implement interfaces
 * for themselves, but externally-owned accounts (EOA) must delegate this to a
 * contract.
 *
 * {IERC165} interfaces can also be queried via the registry.
 *
 * For an in-depth explanation and source code analysis, see the EIP text.
 */
interface IERC1820Registry {
    event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);

    event ManagerChanged(address indexed account, address indexed newManager);

    /**
     * @dev Sets `newManager` as the manager for `account`. A manager of an
     * account is able to set interface implementers for it.
     *
     * By default, each account is its own manager. Passing a value of `0x0` in
     * `newManager` will reset the manager to this initial state.
     *
     * Emits a {ManagerChanged} event.
     *
     * Requirements:
     *
     * - the caller must be the current manager for `account`.
     */
    function setManager(address account, address newManager) external;

    /**
     * @dev Returns the manager for `account`.
     *
     * See {setManager}.
     */
    function getManager(address account) external view returns (address);

    /**
     * @dev Sets the `implementer` contract as ``account``'s implementer for
     * `interfaceHash`.
     *
     * `account` being the zero address is an alias for the caller's address.
     * The zero address can also be used in `implementer` to remove an old one.
     *
     * See {interfaceHash} to learn how these are created.
     *
     * Emits an {InterfaceImplementerSet} event.
     *
     * Requirements:
     *
     * - the caller must be the current manager for `account`.
     * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
     * end in 28 zeroes).
     * - `implementer` must implement {IERC1820Implementer} and return true when
     * queried for support, unless `implementer` is the caller. See
     * {IERC1820Implementer-canImplementInterfaceForAddress}.
     */
    function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;

    /**
     * @dev Returns the implementer of `interfaceHash` for `account`. If no such
     * implementer is registered, returns the zero address.
     *
     * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
     * zeroes), `account` will be queried for support of it.
     *
     * `account` being the zero address is an alias for the caller's address.
     */
    function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);

    /**
     * @dev Returns the interface hash for an `interfaceName`, as defined in the
     * corresponding
     * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
     */
    function interfaceHash(string calldata interfaceName) external pure returns (bytes32);

    /**
     * @notice Updates the cache with whether the contract implements an ERC165 interface or not.
     * @param account Address of the contract for which to update the cache.
     * @param interfaceId ERC165 interface for which to update the cache.
     */
    function updateERC165Cache(address account, bytes4 interfaceId) external;

    /**
     * @notice Checks whether a contract implements an ERC165 interface or not.
     * If the result is not cached a direct lookup on the contract address is performed.
     * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
     * {updateERC165Cache} with the contract address.
     * @param account Address of the contract to check.
     * @param interfaceId ERC165 interface to check.
     * @return True if `account` implements `interfaceId`, false otherwise.
     */
    function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);

    /**
     * @notice Checks whether a contract implements an ERC165 interface or not without using or updating the cache.
     * @param account Address of the contract to check.
     * @param interfaceId ERC165 interface to check.
     * @return True if `account` implements `interfaceId`, false otherwise.
     */
    function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
}

/**
 * @dev Implementation of a contract to keep characters for others. The keepers and addresses with
 * the ADMIN_ROLE are expected to issue the proof to users. Then users could use the
 * proof to withdraw the corresponding character.
 */

contract NewbieVilla is Initializable, AccessControlEnumerable, IERC721Receiver, IERC777Recipient {
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    IERC1820Registry public constant ERC1820_REGISTRY =
        IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
    bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");

    address public web3Entry;
    address public xsyncOperator;
    address internal _token; // mira token, erc777 standard
    // characterId => balance
    mapping(uint256 => uint256) internal _balances;
    address internal _tips; // tips contract

    mapping(uint256 characterId => address keeper) private _keepers;

    // events
    /**
     * @dev Emitted when the web3Entry character nft is withdrawn.
     * @param to The receiver of web3Entry character nft.
     * @param characterId The character ID.
     * @param token Addresses of token withdrawn.
     * @param amount Amount of token withdrawn.
     */
    event Withdraw(address to, uint256 characterId, address token, uint256 amount);

    modifier notExpired(uint256 expires) {
        require(expires >= block.timestamp, "NewbieVilla: receipt has expired");
        _;
    }

    /**
     * @notice Initialize the Newbie Villa contract.
     * @dev msg.sender will be granted `DEFAULT_ADMIN_ROLE`.
     * @param web3Entry_ Address of web3Entry contract.
     * @param xsyncOperator_ Address of xsyncOperator.
     * @param token_ Address of ERC777 token.
     * @param admin_ Address of admin.
     * @param tips_ Address of Tips contract.
     */
    function initialize(
        address web3Entry_,
        address xsyncOperator_,
        address token_,
        address admin_,
        address tips_
    ) external reinitializer(3) {
        web3Entry = web3Entry_;
        xsyncOperator = xsyncOperator_;
        _token = token_;
        _tips = tips_;

        // grants `DEFAULT_ADMIN_ROLE`
        _setupRole(DEFAULT_ADMIN_ROLE, admin_);

        // register interfaces
        ERC1820_REGISTRY.setInterfaceImplementer(
            address(this),
            TOKENS_RECIPIENT_INTERFACE_HASH,
            address(this)
        );
    }

    /**
     * @notice Tips a character by transferring `amount` tokens
     * from account with required permission to `Tips` contract. <br>
     *
     * Admin will call `send` erc777 token to the Tips contract, with `fromCharacterId`
     * and `toCharacterId` encoded in the `data`. <br>
     *
     * `send` interface is
     * [IERC777-send](https://docs.openzeppelin.com/contracts/2.x/api/token/erc777#IERC777-send-address-uint256-bytes-),
     * and parameters encode refers
     * [AbiCoder-encode](https://docs.ethers.org/v5/api/utils/abi/coder/#AbiCoder-encode).<br>
     *
     * <b> Requirements: </b>
     * - The `msg.sender` must be character's keeper or have `ADMIN_ROLE` but not character's keeper.
     * @param fromCharacterId The token ID of character that calls this contract.
     * @param toCharacterId The token ID of character that will receive the token.
     * @param amount Amount of token.
     */
    function tipCharacter(uint256 fromCharacterId, uint256 toCharacterId, uint256 amount) external {
        // check permission
        require(
            _hasPermission(msg.sender, fromCharacterId),
            "NewbieVilla: unauthorized role for tipCharacter"
        );

        // newbievilla's balance - tip amount
        // will fail if balance is insufficient
        _balances[fromCharacterId] -= amount;

        // prepare tipCharacter `data` for `Tips` contract's `tokensReceived` callback method
        bytes memory data = abi.encode(fromCharacterId, toCharacterId);

        // send token
        IERC777(_token).send(_tips, amount, data); // solhint-disable-line check-send-result
    }

    /**
     * @notice Tips a character's note by transferring `amount` tokens
     * from account with required permission to `Tips` contract. <br>
     *
     * Admin will call `send` erc777 token to the Tips contract, with `fromCharacterId`,
     * `toCharacterId` and `toNoteId` encoded in the `data`. <br>
     *
     * `send` interface is
     * [IERC777-send](https://docs.openzeppelin.com/contracts/2.x/api/token/erc777#IERC777-send-address-uint256-bytes-),
     * and parameters encode refers
     * [AbiCoder-encode](https://docs.ethers.org/v5/api/utils/abi/coder/#AbiCoder-encode).<br>
     *
     * <b> Requirements: </b>
     * - The `msg.sender` must be character's keeper or have `ADMIN_ROLE` but not character's keeper.
     * @param fromCharacterId The token ID of character that calls this contract.
     * @param toCharacterId The token ID of character that will receive the token.
     * @param toNoteId The note ID.
     * @param amount Amount of token.
     */
    function tipCharacterForNote(
        uint256 fromCharacterId,
        uint256 toCharacterId,
        uint256 toNoteId,
        uint256 amount
    ) external {
        // check permission
        require(
            _hasPermission(msg.sender, fromCharacterId),
            "NewbieVilla: unauthorized role for tipCharacterForNote"
        );

        // newbievilla's balance - tip amount
        // will fail if balance is insufficient
        _balances[fromCharacterId] -= amount;

        // prepare tipCharacterForNote `data` for `Tips` contract's `tokensReceived` callback method
        bytes memory data = abi.encode(fromCharacterId, toCharacterId, toNoteId);

        // send token
        IERC777(_token).send(_tips, amount, data); // solhint-disable-line check-send-result
    }

    /**
     * @notice  Withdraw character#`characterId` to `to` using the nonce, expires and the proof. <br>
     * Emits the `Withdraw` event. <br>
     * @dev Proof is the signature from character keepers or someone with the ADMIN_ROLE. The message to sign is
     * the packed data of this contract's address, `characterId`, `nonce` and `expires`. <br>
     *
     * Here's an example to generate a proof: <br>
     * ```
     *     digest = ethers.utils.arrayify(
     *          ethers.utils.solidityKeccak256(
     *              ["address", "uint256", "uint256", "uint256"],
     *              [newbieVilla.address, characterId, nonce, expires]
     *          )
     *      );
     *      proof = await owner.signMessage(digest);
     * ```
     *
     * <b> Requirements: </b>:
     * - `expires` is greater than the current timestamp
     * - `proof` is signed by the keeper or address with the ADMIN_ROLE
     *
     * @param   to  Receiver of the withdrawn character.
     * @param   characterId  The token id of the character to withdraw.
     * @param   nonce  Random nonce used to generate the proof.
     * @param   expires  Expire time of the proof, Unix timestamp in seconds.
     * @param   proof  The proof using to withdraw the character.
     */
    function withdraw(
        address to,
        uint256 characterId,
        uint256 nonce,
        uint256 expires,
        bytes calldata proof
    ) external notExpired(expires) {
        bytes32 signedData = ECDSA.toEthSignedMessageHash(
            keccak256(abi.encodePacked(address(this), characterId, nonce, expires))
        );

        // check proof
        address signer = ECDSA.recover(signedData, proof);
        require(_hasPermission(signer, characterId), "NewbieVilla: unauthorized withdraw");

        // update balance
        uint256 amount = _balances[characterId];
        _balances[characterId] = 0;
        // update keeper
        delete _keepers[characterId];

        // send token
        IERC777(_token).send(to, amount, ""); // solhint-disable-line check-send-result

        // transfer web3Entry nft
        IERC721(web3Entry).safeTransferFrom(address(this), to, characterId);

        emit Withdraw(to, characterId, _token, amount);
    }

    /**
     * @dev  Whenever a character `tokenId` is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called. `data` will be decoded as an address and set as
     * the operator of the character. If the `data` is empty, the `operator` will be default operator of the
     * character. <br>
     *
     * <b> Requirements: </b>:
     *
     * - `msg.sender` must be address of Web3Entry.
     *
     * @param data bytes encoded from the operator address to set for the incoming character.
     *
     */
    function onERC721Received(
        address operator,
        address,
        uint256 tokenId,
        bytes calldata data
    ) external override returns (bytes4) {
        // Only character nft could be received, other nft, e.g. mint nft would be reverted
        require(msg.sender == web3Entry, "NewbieVilla: receive unknown token");

        // set keeper for tokenId
        _keepers[tokenId] = operator;

        // grant operator permissions
        if (data.length == 0) {
            IWeb3Entry(web3Entry).grantOperatorPermissions(
                tokenId,
                operator,
                OP.DEFAULT_PERMISSION_BITMAP
            );
        } else {
            address selectedOperator = abi.decode(data, (address));
            IWeb3Entry(web3Entry).grantOperatorPermissions(
                tokenId,
                selectedOperator,
                OP.DEFAULT_PERMISSION_BITMAP
            );
        }
        IWeb3Entry(web3Entry).grantOperatorPermissions(
            tokenId,
            xsyncOperator,
            OP.POST_NOTE_DEFAULT_PERMISSION_BITMAP
        );
        return IERC721Receiver.onERC721Received.selector;
    }

    /// @inheritdoc IERC777Recipient
    /**
     * @notice  Receives tokens. Only specific tokens are accepted, so be careful not to send tokens to this
     address randomly.
     * @dev     The userData/operatorData should be an abi-encoded bytes of `fromCharacterId` and `toCharacter`,
     * which are both uint256 type, so the length of data is 64.
     * @param   to  The Newbie Villa contract address.
     * @param   amount  The amount of token sent.
     * @param   userData  The abi-encoded bytes of `fromCharacterId` and `toCharacter`.
     * @param   operatorData  The abi-encoded bytes of `fromCharacterId` and `toCharacter`.
     */
    function tokensReceived(
        address,
        address,
        address to,
        uint256 amount,
        bytes calldata userData,
        bytes calldata operatorData
    ) external override(IERC777Recipient) {
        require(msg.sender == _token, "NewbieVilla: invalid token");
        require(address(this) == to, "NewbieVilla: invalid receiver");
        bytes memory data = userData.length > 0 ? userData : operatorData;

        if (data.length == 64) {
            (, uint256 toCharacterId) = abi.decode(data, (uint256, uint256));
            _balances[toCharacterId] += amount;
        } else {
            revert("NewbieVilla: unknown receiving");
        }
    }

    /**
     * @notice  Returns the amount of tokens owned by `characterId`.
     * @param   characterId  The character ID to query.
     * @return  uint256  The amount of tokens owned by the character.
     */
    function balanceOf(uint256 characterId) external view returns (uint256) {
        return _balances[characterId];
    }

    /**
     * @notice Returns the address of keeper by `characterId`.
     * @param characterId The character ID to query.
     * @return address The address of the keeper.
     */
    function getKeeper(uint256 characterId) external view returns (address) {
        return _keepers[characterId];
    }

    /**
     * @notice Returns the address of mira token contract.
     * @return The address of mira token contract.
     */
    function getToken() external view returns (address) {
        return _token;
    }

    /// @dev It will return true if `account` is character's keeper or has `ADMIN_ROLE` but not character's keeper.
    function _hasPermission(address account, uint256 characterId) internal view returns (bool) {
        address keeper = _keepers[characterId];
        return (keeper == account) || (keeper == address(0) && hasRole(ADMIN_ROLE, account));
    }
}

        

Contract ABI

[{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"RoleAdminChanged","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"previousAdminRole","internalType":"bytes32","indexed":true},{"type":"bytes32","name":"newAdminRole","internalType":"bytes32","indexed":true}],"anonymous":false},{"type":"event","name":"RoleGranted","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"RoleRevoked","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32","indexed":true},{"type":"address","name":"account","internalType":"address","indexed":true},{"type":"address","name":"sender","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Withdraw","inputs":[{"type":"address","name":"to","internalType":"address","indexed":false},{"type":"uint256","name":"characterId","internalType":"uint256","indexed":false},{"type":"address","name":"token","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"DEFAULT_ADMIN_ROLE","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC1820Registry"}],"name":"ERC1820_REGISTRY","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"TOKENS_RECIPIENT_INTERFACE_HASH","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOf","inputs":[{"type":"uint256","name":"characterId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getKeeper","inputs":[{"type":"uint256","name":"characterId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bytes32","name":"","internalType":"bytes32"}],"name":"getRoleAdmin","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getRoleMember","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"uint256","name":"index","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getRoleMemberCount","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getToken","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"grantRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"hasRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"address","name":"web3Entry_","internalType":"address"},{"type":"address","name":"xsyncOperator_","internalType":"address"},{"type":"address","name":"token_","internalType":"address"},{"type":"address","name":"admin_","internalType":"address"},{"type":"address","name":"tips_","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"bytes4","name":"","internalType":"bytes4"}],"name":"onERC721Received","inputs":[{"type":"address","name":"operator","internalType":"address"},{"type":"address","name":"","internalType":"address"},{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"revokeRole","inputs":[{"type":"bytes32","name":"role","internalType":"bytes32"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"tipCharacter","inputs":[{"type":"uint256","name":"fromCharacterId","internalType":"uint256"},{"type":"uint256","name":"toCharacterId","internalType":"uint256"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"tipCharacterForNote","inputs":[{"type":"uint256","name":"fromCharacterId","internalType":"uint256"},{"type":"uint256","name":"toCharacterId","internalType":"uint256"},{"type":"uint256","name":"toNoteId","internalType":"uint256"},{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"tokensReceived","inputs":[{"type":"address","name":"","internalType":"address"},{"type":"address","name":"","internalType":"address"},{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"amount","internalType":"uint256"},{"type":"bytes","name":"userData","internalType":"bytes"},{"type":"bytes","name":"operatorData","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"web3Entry","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"withdraw","inputs":[{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"characterId","internalType":"uint256"},{"type":"uint256","name":"nonce","internalType":"uint256"},{"type":"uint256","name":"expires","internalType":"uint256"},{"type":"bytes","name":"proof","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"xsyncOperator","inputs":[]}]
              

Contract Creation Code

0x608060405234801561001057600080fd5b50611d72806100206000396000f3fe608060405234801561001057600080fd5b506004361061014c5760003560e01c806372581cc0116100c3578063a217fddf1161007c578063a217fddf14610336578063c44a71301461033e578063ca15c87314610367578063d547741f1461037a578063ddf1858a1461038d578063e1332272146103a057600080fd5b806372581cc01461028f57806375b238fc146102b65780639010d07c146102dd57806391a9dffc146102f057806391d14854146103035780639cc7f7081461031657600080fd5b806321df0da71161011557806321df0da714610200578063248a9ca3146102115780632f2ff15d1461024357806332eba3b21461025657806336568abe146102695780636d13b1ca1461027c57600080fd5b806223de2914610151578063013eb1771461016657806301ffc9a71461019e5780631459457a146101c1578063150b7a02146101d4575b600080fd5b61016461015f366004611836565b6103b3565b005b610181731820a4b7618bde71dce8cdc73aab6c95905fad2481565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b16101ac3660046118e7565b610552565b6040519015158152602001610195565b6101646101cf366004611911565b61057d565b6101e76101e2366004611982565b610744565b6040516001600160e01b03199091168152602001610195565b6005546001600160a01b0316610181565b61023561021f3660046119f5565b6000908152600160208190526040909120015490565b604051908152602001610195565b610164610251366004611a0e565b610968565b600454610181906001600160a01b031681565b610164610277366004611a0e565b610993565b61016461028a366004611a3e565b610a11565b6102357fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b81565b6102357fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177581565b6101816102eb366004611a6a565b610b33565b6101646102fe366004611a8c565b610b52565b6101b1610311366004611a0e565b610c7e565b6102356103243660046119f5565b60009081526006602052604090205490565b610235600081565b61018161034c3660046119f5565b6000908152600860205260409020546001600160a01b031690565b6102356103753660046119f5565b610ca9565b610164610388366004611a0e565b610cc0565b61016461039b366004611abe565b610ce6565b600354610181906001600160a01b031681565b6005546001600160a01b031633146104125760405162461bcd60e51b815260206004820152601a60248201527f4e657762696556696c6c613a20696e76616c696420746f6b656e00000000000060448201526064015b60405180910390fd5b306001600160a01b0387161461046a5760405162461bcd60e51b815260206004820152601d60248201527f4e657762696556696c6c613a20696e76616c69642072656365697665720000006044820152606401610409565b60008361047857828261047b565b84845b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050825192935050506040036104ff576000818060200190518101906104d19190611b31565b600081815260066020526040812080549294508a9350916104f3908490611b6b565b90915550610547915050565b60405162461bcd60e51b815260206004820152601e60248201527f4e657762696556696c6c613a20756e6b6e6f776e20726563656976696e6700006044820152606401610409565b505050505050505050565b60006001600160e01b03198216635a05180f60e01b1480610577575061057782610fea565b92915050565b600054600390610100900460ff1615801561059f575060005460ff8083169116105b6106025760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610409565b6000805461ffff191660ff831617610100178155600380546001600160a01b03808a166001600160a01b0319928316179092556004805489841690831617905560058054888416908316179055600780549286169290911691909117905561066a908461101f565b6040516329965a1d60e01b815230600482018190527fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b60248301526044820152731820a4b7618bde71dce8cdc73aab6c95905fad24906329965a1d90606401600060405180830381600087803b1580156106e357600080fd5b505af11580156106f7573d6000803e3d6000fd5b50506000805461ff0019169055505060405160ff821681527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a1505050505050565b6003546000906001600160a01b031633146107ac5760405162461bcd60e51b815260206004820152602260248201527f4e657762696556696c6c613a207265636569766520756e6b6e6f776e20746f6b60448201526132b760f11b6064820152608401610409565b600084815260086020526040812080546001600160a01b0319166001600160a01b038916179055829003610856576003546040516310332bf960e11b8152600481018690526001600160a01b03888116602483015267100000001fffffff60b01b60448301529091169063206657f290606401600060405180830381600087803b15801561083957600080fd5b505af115801561084d573d6000803e3d6000fd5b505050506108df565b600061086483850185611b7e565b6003546040516310332bf960e11b8152600481018890526001600160a01b03808416602483015267100000001fffffff60b01b604483015292935091169063206657f290606401600060405180830381600087803b1580156108c557600080fd5b505af11580156108d9573d6000803e3d6000fd5b50505050505b600354600480546040516310332bf960e11b81529182018790526001600160a01b03908116602483015264400000003f60c61b60448301529091169063206657f290606401600060405180830381600087803b15801561093e57600080fd5b505af1158015610952573d6000803e3d6000fd5b50630a85bd0160e11b9998505050505050505050565b6000828152600160208190526040909120015461098481611029565b61098e8383611036565b505050565b6001600160a01b0381163314610a035760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152608401610409565b610a0d8282611058565b5050565b610a1b338461107a565b610a7f5760405162461bcd60e51b815260206004820152602f60248201527f4e657762696556696c6c613a20756e617574686f72697a656420726f6c65206660448201526e37b9103a34b821b430b930b1ba32b960891b6064820152608401610409565b60008381526006602052604081208054839290610a9d908490611b9b565b909155505060408051602081018590528082018490528151808203830181526060820192839052600554600754634decdde360e11b90945290926001600160a01b0391821692639bd9bbc692610afb92169086908690606401611bfe565b600060405180830381600087803b158015610b1557600080fd5b505af1158015610b29573d6000803e3d6000fd5b5050505050505050565b6000828152600260205260408120610b4b90836110e3565b9392505050565b610b5c338561107a565b610bc75760405162461bcd60e51b815260206004820152603660248201527f4e657762696556696c6c613a20756e617574686f72697a656420726f6c6520666044820152756f7220746970436861726163746572466f724e6f746560501b6064820152608401610409565b60008481526006602052604081208054839290610be5908490611b9b565b909155505060408051602081018690529081018490526060810183905260009060800160408051601f1981840301815290829052600554600754634decdde360e11b84529193506001600160a01b0390811692639bd9bbc692610c5092169086908690600401611bfe565b600060405180830381600087803b158015610c6a57600080fd5b505af1158015610547573d6000803e3d6000fd5b60009182526001602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6000818152600260205260408120610577906110ef565b60008281526001602081905260409091200154610cdc81611029565b61098e8383611058565b8242811015610d375760405162461bcd60e51b815260206004820181905260248201527f4e657762696556696c6c613a20726563656970742068617320657870697265646044820152606401610409565b6040516bffffffffffffffffffffffff193060601b166020820152603481018790526054810186905260748101859052600090610dba90609401604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000006000908152601c91909152603c902090565b90506000610dfe8286868080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506110f992505050565b9050610e0a818961107a565b610e615760405162461bcd60e51b815260206004820152602260248201527f4e657762696556696c6c613a20756e617574686f72697a656420776974686472604482015261617760f01b6064820152608401610409565b6000888152600660209081526040808320805490849055600890925280832080546001600160a01b03191690556005549051634decdde360e11b81526001600160a01b038d811660048301526024820184905260606044830152606482019490945291921690639bd9bbc690608401600060405180830381600087803b158015610eea57600080fd5b505af1158015610efe573d6000803e3d6000fd5b5050600354604051632142170760e11b81523060048201526001600160a01b038e81166024830152604482018e905290911692506342842e0e9150606401600060405180830381600087803b158015610f5657600080fd5b505af1158015610f6a573d6000803e3d6000fd5b50506005546040517f457f950b75085c30ff780acd57bde642ff1316cc4aad9f286af2c1ffc4163a789350610fd692508d918d916001600160a01b039091169086906001600160a01b039485168152602081019390935292166040820152606081019190915260800190565b60405180910390a150505050505050505050565b60006001600160e01b03198216637965db0b60e01b148061057757506301ffc9a760e01b6001600160e01b0319831614610577565b610a0d8282611036565b611033813361111d565b50565b6110408282611176565b600082815260026020526040902061098e90826111e1565b61106282826111f6565b600082815260026020526040902061098e908261125d565b6000818152600860205260408120546001600160a01b039081169084168114806110db57506001600160a01b0381161580156110db57506110db7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177585610c7e565b949350505050565b6000610b4b8383611272565b6000610577825490565b6000806000611108858561129c565b91509150611115816112e1565b509392505050565b6111278282610c7e565b610a0d576111348161142b565b61113f83602061143d565b604051602001611150929190611c2e565b60408051601f198184030181529082905262461bcd60e51b825261040991600401611ca3565b6111808282610c7e565b610a0d5760008281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45050565b6000610b4b836001600160a01b0384166115d9565b6112008282610c7e565b15610a0d5760008281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000610b4b836001600160a01b038416611628565b600082600001828154811061128957611289611cb6565b9060005260206000200154905092915050565b60008082516041036112d25760208301516040840151606085015160001a6112c68782858561171b565b945094505050506112da565b506000905060025b9250929050565b60008160048111156112f5576112f5611ccc565b036112fd5750565b600181600481111561131157611311611ccc565b0361135e5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610409565b600281600481111561137257611372611ccc565b036113bf5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610409565b60038160048111156113d3576113d3611ccc565b036110335760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610409565b60606105776001600160a01b03831660145b6060600061144c836002611ce2565b611457906002611b6b565b67ffffffffffffffff81111561146f5761146f611cf9565b6040519080825280601f01601f191660200182016040528015611499576020820181803683370190505b509050600360fc1b816000815181106114b4576114b4611cb6565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106114e3576114e3611cb6565b60200101906001600160f81b031916908160001a9053506000611507846002611ce2565b611512906001611b6b565b90505b600181111561158a576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061154657611546611cb6565b1a60f81b82828151811061155c5761155c611cb6565b60200101906001600160f81b031916908160001a90535060049490941c9361158381611d0f565b9050611515565b508315610b4b5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610409565b600081815260018301602052604081205461162057508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610577565b506000610577565b6000818152600183016020526040812054801561171157600061164c600183611b9b565b855490915060009061166090600190611b9b565b90508181146116c557600086600001828154811061168057611680611cb6565b90600052602060002001549050808760000184815481106116a3576116a3611cb6565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806116d6576116d6611d26565b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050610577565b6000915050610577565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561175257506000905060036117d6565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa1580156117a6573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166117cf576000600192509250506117d6565b9150600090505b94509492505050565b6001600160a01b038116811461103357600080fd5b60008083601f84011261180657600080fd5b50813567ffffffffffffffff81111561181e57600080fd5b6020830191508360208285010111156112da57600080fd5b60008060008060008060008060c0898b03121561185257600080fd5b883561185d816117df565b9750602089013561186d816117df565b9650604089013561187d816117df565b955060608901359450608089013567ffffffffffffffff808211156118a157600080fd5b6118ad8c838d016117f4565b909650945060a08b01359150808211156118c657600080fd5b506118d38b828c016117f4565b999c989b5096995094979396929594505050565b6000602082840312156118f957600080fd5b81356001600160e01b031981168114610b4b57600080fd5b600080600080600060a0868803121561192957600080fd5b8535611934816117df565b94506020860135611944816117df565b93506040860135611954816117df565b92506060860135611964816117df565b91506080860135611974816117df565b809150509295509295909350565b60008060008060006080868803121561199a57600080fd5b85356119a5816117df565b945060208601356119b5816117df565b935060408601359250606086013567ffffffffffffffff8111156119d857600080fd5b6119e4888289016117f4565b969995985093965092949392505050565b600060208284031215611a0757600080fd5b5035919050565b60008060408385031215611a2157600080fd5b823591506020830135611a33816117df565b809150509250929050565b600080600060608486031215611a5357600080fd5b505081359360208301359350604090920135919050565b60008060408385031215611a7d57600080fd5b50508035926020909101359150565b60008060008060808587031215611aa257600080fd5b5050823594602084013594506040840135936060013592509050565b60008060008060008060a08789031215611ad757600080fd5b8635611ae2816117df565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff811115611b1357600080fd5b611b1f89828a016117f4565b979a9699509497509295939492505050565b60008060408385031215611b4457600080fd5b505080516020909101519092909150565b634e487b7160e01b600052601160045260246000fd5b8082018082111561057757610577611b55565b600060208284031215611b9057600080fd5b8135610b4b816117df565b8181038181111561057757610577611b55565b60005b83811015611bc9578181015183820152602001611bb1565b50506000910152565b60008151808452611bea816020860160208601611bae565b601f01601f19169290920160200192915050565b60018060a01b0384168152826020820152606060408201526000611c256060830184611bd2565b95945050505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c66816017850160208801611bae565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611c97816028840160208801611bae565b01602801949350505050565b602081526000610b4b6020830184611bd2565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052602160045260246000fd5b808202811582820484141761057757610577611b55565b634e487b7160e01b600052604160045260246000fd5b600081611d1e57611d1e611b55565b506000190190565b634e487b7160e01b600052603160045260246000fdfea2646970667358221220c7afd54002fbdb4527f026f7454d4f71347c76b623ee543ad3617c3c12908adf64736f6c63430008120033

Deployed ByteCode

0x608060405234801561001057600080fd5b506004361061014c5760003560e01c806372581cc0116100c3578063a217fddf1161007c578063a217fddf14610336578063c44a71301461033e578063ca15c87314610367578063d547741f1461037a578063ddf1858a1461038d578063e1332272146103a057600080fd5b806372581cc01461028f57806375b238fc146102b65780639010d07c146102dd57806391a9dffc146102f057806391d14854146103035780639cc7f7081461031657600080fd5b806321df0da71161011557806321df0da714610200578063248a9ca3146102115780632f2ff15d1461024357806332eba3b21461025657806336568abe146102695780636d13b1ca1461027c57600080fd5b806223de2914610151578063013eb1771461016657806301ffc9a71461019e5780631459457a146101c1578063150b7a02146101d4575b600080fd5b61016461015f366004611836565b6103b3565b005b610181731820a4b7618bde71dce8cdc73aab6c95905fad2481565b6040516001600160a01b0390911681526020015b60405180910390f35b6101b16101ac3660046118e7565b610552565b6040519015158152602001610195565b6101646101cf366004611911565b61057d565b6101e76101e2366004611982565b610744565b6040516001600160e01b03199091168152602001610195565b6005546001600160a01b0316610181565b61023561021f3660046119f5565b6000908152600160208190526040909120015490565b604051908152602001610195565b610164610251366004611a0e565b610968565b600454610181906001600160a01b031681565b610164610277366004611a0e565b610993565b61016461028a366004611a3e565b610a11565b6102357fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b81565b6102357fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177581565b6101816102eb366004611a6a565b610b33565b6101646102fe366004611a8c565b610b52565b6101b1610311366004611a0e565b610c7e565b6102356103243660046119f5565b60009081526006602052604090205490565b610235600081565b61018161034c3660046119f5565b6000908152600860205260409020546001600160a01b031690565b6102356103753660046119f5565b610ca9565b610164610388366004611a0e565b610cc0565b61016461039b366004611abe565b610ce6565b600354610181906001600160a01b031681565b6005546001600160a01b031633146104125760405162461bcd60e51b815260206004820152601a60248201527f4e657762696556696c6c613a20696e76616c696420746f6b656e00000000000060448201526064015b60405180910390fd5b306001600160a01b0387161461046a5760405162461bcd60e51b815260206004820152601d60248201527f4e657762696556696c6c613a20696e76616c69642072656365697665720000006044820152606401610409565b60008361047857828261047b565b84845b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050825192935050506040036104ff576000818060200190518101906104d19190611b31565b600081815260066020526040812080549294508a9350916104f3908490611b6b565b90915550610547915050565b60405162461bcd60e51b815260206004820152601e60248201527f4e657762696556696c6c613a20756e6b6e6f776e20726563656976696e6700006044820152606401610409565b505050505050505050565b60006001600160e01b03198216635a05180f60e01b1480610577575061057782610fea565b92915050565b600054600390610100900460ff1615801561059f575060005460ff8083169116105b6106025760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610409565b6000805461ffff191660ff831617610100178155600380546001600160a01b03808a166001600160a01b0319928316179092556004805489841690831617905560058054888416908316179055600780549286169290911691909117905561066a908461101f565b6040516329965a1d60e01b815230600482018190527fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b60248301526044820152731820a4b7618bde71dce8cdc73aab6c95905fad24906329965a1d90606401600060405180830381600087803b1580156106e357600080fd5b505af11580156106f7573d6000803e3d6000fd5b50506000805461ff0019169055505060405160ff821681527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a1505050505050565b6003546000906001600160a01b031633146107ac5760405162461bcd60e51b815260206004820152602260248201527f4e657762696556696c6c613a207265636569766520756e6b6e6f776e20746f6b60448201526132b760f11b6064820152608401610409565b600084815260086020526040812080546001600160a01b0319166001600160a01b038916179055829003610856576003546040516310332bf960e11b8152600481018690526001600160a01b03888116602483015267100000001fffffff60b01b60448301529091169063206657f290606401600060405180830381600087803b15801561083957600080fd5b505af115801561084d573d6000803e3d6000fd5b505050506108df565b600061086483850185611b7e565b6003546040516310332bf960e11b8152600481018890526001600160a01b03808416602483015267100000001fffffff60b01b604483015292935091169063206657f290606401600060405180830381600087803b1580156108c557600080fd5b505af11580156108d9573d6000803e3d6000fd5b50505050505b600354600480546040516310332bf960e11b81529182018790526001600160a01b03908116602483015264400000003f60c61b60448301529091169063206657f290606401600060405180830381600087803b15801561093e57600080fd5b505af1158015610952573d6000803e3d6000fd5b50630a85bd0160e11b9998505050505050505050565b6000828152600160208190526040909120015461098481611029565b61098e8383611036565b505050565b6001600160a01b0381163314610a035760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152608401610409565b610a0d8282611058565b5050565b610a1b338461107a565b610a7f5760405162461bcd60e51b815260206004820152602f60248201527f4e657762696556696c6c613a20756e617574686f72697a656420726f6c65206660448201526e37b9103a34b821b430b930b1ba32b960891b6064820152608401610409565b60008381526006602052604081208054839290610a9d908490611b9b565b909155505060408051602081018590528082018490528151808203830181526060820192839052600554600754634decdde360e11b90945290926001600160a01b0391821692639bd9bbc692610afb92169086908690606401611bfe565b600060405180830381600087803b158015610b1557600080fd5b505af1158015610b29573d6000803e3d6000fd5b5050505050505050565b6000828152600260205260408120610b4b90836110e3565b9392505050565b610b5c338561107a565b610bc75760405162461bcd60e51b815260206004820152603660248201527f4e657762696556696c6c613a20756e617574686f72697a656420726f6c6520666044820152756f7220746970436861726163746572466f724e6f746560501b6064820152608401610409565b60008481526006602052604081208054839290610be5908490611b9b565b909155505060408051602081018690529081018490526060810183905260009060800160408051601f1981840301815290829052600554600754634decdde360e11b84529193506001600160a01b0390811692639bd9bbc692610c5092169086908690600401611bfe565b600060405180830381600087803b158015610c6a57600080fd5b505af1158015610547573d6000803e3d6000fd5b60009182526001602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6000818152600260205260408120610577906110ef565b60008281526001602081905260409091200154610cdc81611029565b61098e8383611058565b8242811015610d375760405162461bcd60e51b815260206004820181905260248201527f4e657762696556696c6c613a20726563656970742068617320657870697265646044820152606401610409565b6040516bffffffffffffffffffffffff193060601b166020820152603481018790526054810186905260748101859052600090610dba90609401604051602081830303815290604052805190602001207f19457468657265756d205369676e6564204d6573736167653a0a3332000000006000908152601c91909152603c902090565b90506000610dfe8286868080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506110f992505050565b9050610e0a818961107a565b610e615760405162461bcd60e51b815260206004820152602260248201527f4e657762696556696c6c613a20756e617574686f72697a656420776974686472604482015261617760f01b6064820152608401610409565b6000888152600660209081526040808320805490849055600890925280832080546001600160a01b03191690556005549051634decdde360e11b81526001600160a01b038d811660048301526024820184905260606044830152606482019490945291921690639bd9bbc690608401600060405180830381600087803b158015610eea57600080fd5b505af1158015610efe573d6000803e3d6000fd5b5050600354604051632142170760e11b81523060048201526001600160a01b038e81166024830152604482018e905290911692506342842e0e9150606401600060405180830381600087803b158015610f5657600080fd5b505af1158015610f6a573d6000803e3d6000fd5b50506005546040517f457f950b75085c30ff780acd57bde642ff1316cc4aad9f286af2c1ffc4163a789350610fd692508d918d916001600160a01b039091169086906001600160a01b039485168152602081019390935292166040820152606081019190915260800190565b60405180910390a150505050505050505050565b60006001600160e01b03198216637965db0b60e01b148061057757506301ffc9a760e01b6001600160e01b0319831614610577565b610a0d8282611036565b611033813361111d565b50565b6110408282611176565b600082815260026020526040902061098e90826111e1565b61106282826111f6565b600082815260026020526040902061098e908261125d565b6000818152600860205260408120546001600160a01b039081169084168114806110db57506001600160a01b0381161580156110db57506110db7fa49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c2177585610c7e565b949350505050565b6000610b4b8383611272565b6000610577825490565b6000806000611108858561129c565b91509150611115816112e1565b509392505050565b6111278282610c7e565b610a0d576111348161142b565b61113f83602061143d565b604051602001611150929190611c2e565b60408051601f198184030181529082905262461bcd60e51b825261040991600401611ca3565b6111808282610c7e565b610a0d5760008281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45050565b6000610b4b836001600160a01b0384166115d9565b6112008282610c7e565b15610a0d5760008281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000610b4b836001600160a01b038416611628565b600082600001828154811061128957611289611cb6565b9060005260206000200154905092915050565b60008082516041036112d25760208301516040840151606085015160001a6112c68782858561171b565b945094505050506112da565b506000905060025b9250929050565b60008160048111156112f5576112f5611ccc565b036112fd5750565b600181600481111561131157611311611ccc565b0361135e5760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606401610409565b600281600481111561137257611372611ccc565b036113bf5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606401610409565b60038160048111156113d3576113d3611ccc565b036110335760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608401610409565b60606105776001600160a01b03831660145b6060600061144c836002611ce2565b611457906002611b6b565b67ffffffffffffffff81111561146f5761146f611cf9565b6040519080825280601f01601f191660200182016040528015611499576020820181803683370190505b509050600360fc1b816000815181106114b4576114b4611cb6565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106114e3576114e3611cb6565b60200101906001600160f81b031916908160001a9053506000611507846002611ce2565b611512906001611b6b565b90505b600181111561158a576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061154657611546611cb6565b1a60f81b82828151811061155c5761155c611cb6565b60200101906001600160f81b031916908160001a90535060049490941c9361158381611d0f565b9050611515565b508315610b4b5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610409565b600081815260018301602052604081205461162057508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610577565b506000610577565b6000818152600183016020526040812054801561171157600061164c600183611b9b565b855490915060009061166090600190611b9b565b90508181146116c557600086600001828154811061168057611680611cb6565b90600052602060002001549050808760000184815481106116a3576116a3611cb6565b6000918252602080832090910192909255918252600188019052604090208390555b85548690806116d6576116d6611d26565b600190038181906000526020600020016000905590558560010160008681526020019081526020016000206000905560019350505050610577565b6000915050610577565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a083111561175257506000905060036117d6565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa1580156117a6573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166117cf576000600192509250506117d6565b9150600090505b94509492505050565b6001600160a01b038116811461103357600080fd5b60008083601f84011261180657600080fd5b50813567ffffffffffffffff81111561181e57600080fd5b6020830191508360208285010111156112da57600080fd5b60008060008060008060008060c0898b03121561185257600080fd5b883561185d816117df565b9750602089013561186d816117df565b9650604089013561187d816117df565b955060608901359450608089013567ffffffffffffffff808211156118a157600080fd5b6118ad8c838d016117f4565b909650945060a08b01359150808211156118c657600080fd5b506118d38b828c016117f4565b999c989b5096995094979396929594505050565b6000602082840312156118f957600080fd5b81356001600160e01b031981168114610b4b57600080fd5b600080600080600060a0868803121561192957600080fd5b8535611934816117df565b94506020860135611944816117df565b93506040860135611954816117df565b92506060860135611964816117df565b91506080860135611974816117df565b809150509295509295909350565b60008060008060006080868803121561199a57600080fd5b85356119a5816117df565b945060208601356119b5816117df565b935060408601359250606086013567ffffffffffffffff8111156119d857600080fd5b6119e4888289016117f4565b969995985093965092949392505050565b600060208284031215611a0757600080fd5b5035919050565b60008060408385031215611a2157600080fd5b823591506020830135611a33816117df565b809150509250929050565b600080600060608486031215611a5357600080fd5b505081359360208301359350604090920135919050565b60008060408385031215611a7d57600080fd5b50508035926020909101359150565b60008060008060808587031215611aa257600080fd5b5050823594602084013594506040840135936060013592509050565b60008060008060008060a08789031215611ad757600080fd5b8635611ae2816117df565b9550602087013594506040870135935060608701359250608087013567ffffffffffffffff811115611b1357600080fd5b611b1f89828a016117f4565b979a9699509497509295939492505050565b60008060408385031215611b4457600080fd5b505080516020909101519092909150565b634e487b7160e01b600052601160045260246000fd5b8082018082111561057757610577611b55565b600060208284031215611b9057600080fd5b8135610b4b816117df565b8181038181111561057757610577611b55565b60005b83811015611bc9578181015183820152602001611bb1565b50506000910152565b60008151808452611bea816020860160208601611bae565b601f01601f19169290920160200192915050565b60018060a01b0384168152826020820152606060408201526000611c256060830184611bd2565b95945050505050565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351611c66816017850160208801611bae565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351611c97816028840160208801611bae565b01602801949350505050565b602081526000610b4b6020830184611bd2565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052602160045260246000fd5b808202811582820484141761057757610577611b55565b634e487b7160e01b600052604160045260246000fd5b600081611d1e57611d1e611b55565b506000190190565b634e487b7160e01b600052603160045260246000fdfea2646970667358221220c7afd54002fbdb4527f026f7454d4f71347c76b623ee543ad3617c3c12908adf64736f6c63430008120033