creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "/contracts/XENFT.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n        \\\\      //   |||||||||||   |\\      ||       A CRYPTOCURRENCY FOR THE MASSES\n         \\\\    //    ||            |\\\\     ||\n          \\\\  //     ||            ||\\\\    ||       PRINCIPLES OF XEN:\n           \\\\//      ||            || \\\\   ||       - No pre-mint; starts with zero supply\n            XX       ||||||||      ||  \\\\  ||       - No admin keys\n           //\\\\      ||            ||   \\\\ ||       - Immutable contract\n          //  \\\\     ||            ||    \\\\||\n         //    \\\\    ||            ||     \\\\|\n        //      \\\\   |||||||||||   ||      \\|       Copyright (C) FairCrypto Foundation 2022\n\n\n    XENFT XEN Torrent props:\n    - count: number of VMUs\n    - mintInfo: (term, maturityTs, cRank start, AMP,  EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n    DefaultOperatorFilterer, // required to support OpenSea royalties\n    IXENTorrent,\n    IXENProxying,\n    IBurnableToken,\n    IBurnRedeemable,\n    ERC2771Context, // required to support meta transactions\n    IERC2981, // required to support NFT royalties\n    ERC721(\"XEN Torrent\", \"XENT\")\n{\n    // HELPER LIBRARIES\n\n    using Strings for uint256;\n    using MintInfo for uint256;\n    using Array for uint256[];\n\n    // PUBLIC CONSTANTS\n\n    // XENFT common business logic\n    uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n    // XENFT categories' params\n    uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n    uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n    uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n    uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n    string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n    uint256 public constant ROYALTY_BP = 250;\n\n    // PUBLIC MUTABLE STATE\n\n    // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n    uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n    // Indexing of params by categories and classes:\n    // 0: Collector\n    // 1: Limited\n    // 2: Rare\n    // 3: Epic\n    // 4: Legendary\n    // 5: Exotic\n    // 6: Xunicorn\n    // [0, B1, B2, B3, B4, B5, B6]\n    uint256[] public specialClassesBurnRates;\n    // [0, 0, R1, R2, R3, R4, R5]\n    uint256[] public specialClassesTokenLimits;\n    // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n    uint256[] public specialClassesCounters;\n\n    // mapping: NFT tokenId => count of Virtual Mining Units\n    mapping(uint256 => uint256) public vmuCount;\n    // mapping: NFT tokenId => burned XEN\n    mapping(uint256 => uint256) public xenBurned;\n    // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n    // MintInfo encoded as:\n    //      term (uint16)\n    //      | maturityTs (uint64)\n    //      | rank (uint128)\n    //      | amp (uint16)\n    //      | eaa (uint16)\n    //      | class (uint8):\n    //          [7] isApex\n    //          [6] isLimited\n    //          [0-5] powerGroupIdx\n    //      | redeemed (uint8)\n    mapping(uint256 => uint256) public mintInfo;\n\n    // PUBLIC IMMUTABLE STATE\n\n    // pointer to XEN Crypto contract\n    XENCrypto public immutable xenCrypto;\n    // genesisTs for the contract\n    uint256 public immutable genesisTs;\n    // start of operations block number\n    uint256 public immutable startBlockNumber;\n\n    // PRIVATE STATE\n\n    // original contract marking to distinguish from proxy copies\n    address private immutable _original;\n    // original deployer address to be used for setting trusted forwarder\n    address private immutable _deployer;\n    // address to be used for royalties' tracking\n    address private immutable _royaltyReceiver;\n\n    // reentrancy guard constants and state\n    // using non-zero constants to save gas avoiding repeated initialization\n    uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n    uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n    // used as both\n    // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n    // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n    uint256 private _tokenId;\n\n    // mapping Address => tokenId[]\n    mapping(address => uint256[]) private _ownedTokens;\n\n    /**\n        @dev    Constructor. Creates XEN Torrent contract, setting immutable parameters\n     */\n    constructor(\n        address xenCrypto_,\n        uint256[] memory burnRates_,\n        uint256[] memory tokenLimits_,\n        uint256 startBlockNumber_,\n        address forwarder_,\n        address royaltyReceiver_\n    ) ERC2771Context(forwarder_) {\n        require(xenCrypto_ != address(0), \"bad address\");\n        require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n        _tokenId = _NOT_USED;\n        _original = address(this);\n        _deployer = msg.sender;\n        _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n        startBlockNumber = startBlockNumber_;\n        genesisTs = block.timestamp;\n        xenCrypto = XENCrypto(xenCrypto_);\n        specialClassesBurnRates = burnRates_;\n        specialClassesTokenLimits = tokenLimits_;\n        specialClassesCounters = new uint256[](tokenLimits_.length);\n        for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n            specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n        }\n        specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n    }\n\n    /**\n        @dev    Call Reentrancy Guard\n    */\n    modifier nonReentrant() {\n        require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n        _tokenId = _USED;\n        _;\n        _tokenId = _NOT_USED;\n    }\n\n    /**\n        @dev    Start of Operations Guard\n    */\n    modifier notBeforeStart() {\n        require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n        _;\n    }\n\n    // INTERFACES & STANDARDS\n    // IERC165 IMPLEMENTATION\n\n    /**\n        @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n        return\n            interfaceId == type(IBurnRedeemable).interfaceId ||\n            interfaceId == type(IERC2981).interfaceId ||\n            interfaceId == type(IERC2771).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    // ERC2771 IMPLEMENTATION\n\n    /**\n        @dev use ERC2771Context implementation of _msgSender()\n     */\n    function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n        return ERC2771Context._msgSender();\n    }\n\n    /**\n        @dev use ERC2771Context implementation of _msgData()\n     */\n    function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n        return ERC2771Context._msgData();\n    }\n\n    // OWNABLE IMPLEMENTATION\n\n    /**\n        @dev public getter to check for deployer / owner (Opensea, etc.)\n     */\n    function owner() external view returns (address) {\n        return _deployer;\n    }\n\n    // ERC-721 METADATA IMPLEMENTATION\n    /**\n        @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n     */\n    function tokenURI(uint256 tokenId) public view override returns (string memory) {\n        uint256 count = vmuCount[tokenId];\n        uint256 info = mintInfo[tokenId];\n        uint256 burned = xenBurned[tokenId];\n        require(count > 0);\n        bytes memory dataURI = abi.encodePacked(\n            \"{\",\n            '\"name\": \"XEN Torrent #',\n            tokenId.toString(),\n            '\",',\n            '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n            '\"image\": \"',\n            \"data:image/svg+xml;base64,\",\n            Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n            '\",',\n            '\"attributes\": ',\n            Metadata.attributes(count, burned, info),\n            \"}\"\n        );\n        return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n    }\n\n    // IMPLEMENTATION OF XENProxying INTERFACE\n    // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n    /**\n        @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n     */\n    function callClaimRank(uint256 term) external {\n        require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n        bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n        (bool success, ) = address(xenCrypto).call(callData);\n        require(success, \"call failed\");\n    }\n\n    /**\n        @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n     */\n    function callClaimMintReward(address to) external {\n        require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n        bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n        (bool success, ) = address(xenCrypto).call(callData);\n        require(success, \"call failed\");\n    }\n\n    /**\n        @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n     */\n    function powerDown() external {\n        require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n        selfdestruct(payable(address(0)));\n    }\n\n    // OVERRIDING OF ERC-721 IMPLEMENTATION\n    // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n    /**\n        @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address,\n        uint256 tokenId\n    ) internal virtual override {\n        if (from != address(0)) {\n            uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n            uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n            require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n        }\n    }\n\n    /**\n        @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual override {\n        _ownedTokens[from].removeItem(tokenId);\n        _ownedTokens[to].addItem(tokenId);\n    }\n\n    // IBurnRedeemable IMPLEMENTATION\n\n    /**\n        @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n     */\n    function onTokenBurned(address user, uint256 burned) external {\n        require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n        require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n        _ownedTokens[user].addItem(_tokenId);\n        xenBurned[_tokenId] = burned;\n        _safeMint(user, _tokenId);\n        emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n        _tokenId = _NOT_USED;\n    }\n\n    // IBurnableToken IMPLEMENTATION\n\n    /**\n        @dev burns XENTorrent XENFT which can be used by connected contracts services\n     */\n    function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n        require(\n            IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n            \"XENFT burn: not a supported contract\"\n        );\n        require(user != address(0), \"XENFT burn: illegal owner address\");\n        require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n        require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n        _ownedTokens[user].removeItem(tokenId);\n        _burn(tokenId);\n        IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n    }\n\n    // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n    /**\n        @dev implements `setApprovalForAll` with additional approved Operator checking\n     */\n    function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n        super.setApprovalForAll(operator, approved);\n    }\n\n    /**\n        @dev implements `approve` with additional approved Operator checking\n     */\n    function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n        super.approve(operator, tokenId);\n    }\n\n    /**\n        @dev implements `transferFrom` with additional approved Operator checking\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public override onlyAllowedOperator(from) {\n        super.transferFrom(from, to, tokenId);\n    }\n\n    /**\n        @dev implements `safeTransferFrom` with additional approved Operator checking\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public override onlyAllowedOperator(from) {\n        super.safeTransferFrom(from, to, tokenId);\n    }\n\n    /**\n        @dev implements `safeTransferFrom` with additional approved Operator checking\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) public override onlyAllowedOperator(from) {\n        super.safeTransferFrom(from, to, tokenId, data);\n    }\n\n    // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n    /**\n        @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n     */\n    function addForwarder(address trustedForwarder) external {\n        require(msg.sender == _deployer, \"XENFT: not an deployer\");\n        require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n        _trustedForwarder = trustedForwarder;\n    }\n\n    // SUPPORT FOR ERC2981 ROYALTY INFO\n\n    /**\n        @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n     */\n    function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n        receiver = _royaltyReceiver;\n        royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n    }\n\n    // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n    /**\n        @dev Sets specified XENFT as redeemed\n     */\n    function _setRedeemed(uint256 tokenId) private {\n        mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n    }\n\n    /**\n        @dev Determines power group index for Collector Category\n     */\n    function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n        return (vmus * term) / POWER_GROUP_SIZE;\n    }\n\n    /**\n        @dev calculates Collector Class index\n    */\n    function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n        if (_powerGroup(count, term) > 7) return 7;\n        return _powerGroup(count, term);\n    }\n\n    /**\n        @dev internal helper to determine special class tier based on XEN to be burned\n     */\n    function _specialTier(uint256 burning) private view returns (uint256) {\n        for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n            if (specialClassesBurnRates[i] == 0) {\n                return 0;\n            }\n            if (burning > specialClassesBurnRates[i] - 1) {\n                return i;\n            }\n        }\n        return 0;\n    }\n\n    /**\n        @dev internal helper to collect params and encode MintInfo\n     */\n    function _mintInfo(\n        address proxy,\n        uint256 count,\n        uint256 term,\n        uint256 burning,\n        uint256 tokenId\n    ) private view returns (uint256) {\n        bool apex = isApex(tokenId);\n        uint256 _class = _classIdx(count, term);\n        if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n        if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n        (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n        return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n    }\n\n    /**\n        @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n     */\n    function _bulkClaimRank(\n        uint256 count,\n        uint256 term,\n        uint256 tokenId,\n        uint256 burning\n    ) private {\n        bytes memory bytecode = bytes.concat(\n            bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n            bytes20(address(this)),\n            bytes15(0x5af43d82803e903d91602b57fd5bf3)\n        );\n        bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n        address proxy;\n        bool succeeded;\n        for (uint256 i = 1; i < count + 1; i++) {\n            bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n            assembly {\n                proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n                succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n            }\n            require(succeeded, \"XENFT: Error while claiming rank\");\n            if (i == 1) {\n                mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n            }\n        }\n        vmuCount[tokenId] = count;\n    }\n\n    /**\n        @dev internal helper to claim tokenId (limited / ordinary)\n     */\n    function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n        // burn possibility has already been verified\n        uint256 tier = _specialTier(burning);\n        if (tier == 1) {\n            require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n            require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n            return tokenIdCounter++;\n        }\n        if (tier > 1) {\n            require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n            require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n            require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n            return specialClassesCounters[tier]++;\n        }\n        return tokenIdCounter++;\n    }\n\n    // PUBLIC GETTERS\n\n    /**\n        @dev public getter for tokens owned by address\n     */\n    function ownedTokens() external view returns (uint256[] memory) {\n        return _ownedTokens[_msgSender()];\n    }\n\n    /**\n        @dev determines if tokenId corresponds to Limited Category\n     */\n    function isApex(uint256 tokenId) public pure returns (bool apex) {\n        apex = tokenId < COMMON_CATEGORY_COUNTER;\n    }\n\n    // PUBLIC TRANSACTIONAL INTERFACE\n\n    /**\n        @dev    public XEN Torrent interface\n                initiates Bulk Mint (Torrent) Operation (Common Category)\n     */\n    function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n        require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n        require(count > 0, \"XENFT: Illegal count\");\n        require(term > 0, \"XENFT: Illegal term\");\n        _tokenId = _getTokenId(count, 0);\n        _bulkClaimRank(count, term, _tokenId, 0);\n        _ownedTokens[_msgSender()].addItem(_tokenId);\n        _safeMint(_msgSender(), _tokenId);\n        emit StartTorrent(_msgSender(), count, term);\n        tokenId = _tokenId;\n        _tokenId = _NOT_USED;\n    }\n\n    /**\n        @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n     */\n    function bulkClaimRankLimited(\n        uint256 count,\n        uint256 term,\n        uint256 burning\n    ) public notBeforeStart returns (uint256) {\n        require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n        require(count > 0, \"XENFT: Illegal count\");\n        require(term > 0, \"XENFT: Illegal term\");\n        require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n        uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n        require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n        uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n        require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n        _tokenId = _getTokenId(count, burning);\n        _bulkClaimRank(count, term, _tokenId, burning);\n        IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n        return _tokenId;\n    }\n\n    /**\n        @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n     */\n    function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n        require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n        require(to != address(0), \"XENFT: Illegal address\");\n        require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n        bytes memory bytecode = bytes.concat(\n            bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n            bytes20(address(this)),\n            bytes15(0x5af43d82803e903d91602b57fd5bf3)\n        );\n        uint256 end = vmuCount[tokenId] + 1;\n        bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n        bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n        for (uint256 i = 1; i < end; i++) {\n            bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n            bool succeeded;\n            bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n            address proxy = address(uint160(uint256(hash)));\n            assembly {\n                succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n            }\n            require(succeeded, \"XENFT: Error while claiming rewards\");\n            assembly {\n                succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n            }\n            require(succeeded, \"XENFT: Error while powering down\");\n        }\n        _setRedeemed(tokenId);\n        emit EndTorrent(_msgSender(), tokenId, to);\n    }\n}\n"
      },
      "/contracts/libs/StringData.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n    Extra XEN quotes:\n\n    \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n    \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n    \"If you are depressed, you are living in the past.\" - Lao Tzu\n    \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n    \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n    \"Be the path. Do not seek it.\" - Yara Tschallener\n    \"Bow to no one but your own divinity.\" - Satya\n    \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n    \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n    \"If you can't, you must.\" - Tony Robbins\n    “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n    “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n    \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n    \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n    \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n    \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n   @dev  a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n    uint256 public constant QUOTES_COUNT = 12;\n    uint256 public constant QUOTE_LENGTH = 66;\n    bytes public constant QUOTES =\n        bytes(\n            '\"If you realize you have enough, you are truly rich.\" - Lao Tzu   '\n            '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n            '\"To know that you do not know is the best.\" - Lao Tzu             '\n            '\"An over-sharpened sword cannot last long.\" - Lao Tzu             '\n            '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n            '\"Music in the soul can be heard by the universe.\" - Lao Tzu       '\n            '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu      '\n            '\"The further one goes, the less one knows.\" - Lao Tzu             '\n            '\"Stop thinking, and end your problems.\" - Lao Tzu                 '\n            '\"Reliability is the foundation of commitment.\" - Unknown          '\n            '\"Your past does not equal your future.\" - Tony Robbins            '\n            '\"Be the path. Do not seek it.\" - Yara Tschallener                 '\n        );\n    uint256 public constant CLASSES_COUNT = 14;\n    uint256 public constant CLASSES_NAME_LENGTH = 10;\n    bytes public constant CLASSES =\n        bytes(\n            \"Ruby      \"\n            \"Opal      \"\n            \"Topaz     \"\n            \"Emerald   \"\n            \"Aquamarine\"\n            \"Sapphire  \"\n            \"Amethyst  \"\n            \"Xenturion \"\n            \"Limited   \"\n            \"Rare      \"\n            \"Epic      \"\n            \"Legendary \"\n            \"Exotic    \"\n            \"Xunicorn  \"\n        );\n\n    /**\n        @dev    Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n                therefore we make a hack by supplying our local constant packed string array as calldata\n    */\n    function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n        if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n        return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n    }\n\n    function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n        if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n        return \"\";\n    }\n}\n"
      },
      "/contracts/libs/SVG.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n    @dev        Library to create SVG image for XENFT metadata\n    @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n    // Type to encode all data params for SVG image generation\n    struct SvgParams {\n        string symbol;\n        address xenAddress;\n        uint256 tokenId;\n        uint256 term;\n        uint256 rank;\n        uint256 count;\n        uint256 maturityTs;\n        uint256 amp;\n        uint256 eaa;\n        uint256 xenBurned;\n        bool redeemed;\n        string series;\n    }\n\n    // Type to encode SVG gradient stop color on HSL color scale\n    struct Color {\n        uint256 h;\n        uint256 s;\n        uint256 l;\n        uint256 a;\n        uint256 off;\n    }\n\n    // Type to encode SVG gradient\n    struct Gradient {\n        Color[] colors;\n        uint256 id;\n        uint256[4] coords;\n    }\n\n    using DateTime for uint256;\n    using Strings for uint256;\n    using FormattedStrings for uint256;\n    using Strings for address;\n\n    string private constant _STYLE =\n        \"<style> \"\n        \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n        \".series {text-transform: uppercase} \"\n        \".logo {font-size:200px;font-weight:100;} \"\n        \".meta {font-size:12px;} \"\n        \".small {font-size:8px;} \"\n        \".burn {font-weight:500;font-size:16px;} }\"\n        \"</style>\";\n\n    string private constant _COLLECTOR =\n        \"<g>\"\n        \"<path \"\n        'stroke=\"#ededed\" '\n        'fill=\"none\" '\n        'transform=\"translate(265,418)\" '\n        'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n        \"</g>\";\n\n    string private constant _LIMITED =\n        \"<g> \"\n        '<path fill=\"#ededed\" '\n        'transform=\"scale(0.4) translate(600, 940)\" '\n        'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n        \"</g>\";\n\n    string private constant _APEX =\n        '<g transform=\"scale(0.5) translate(533, 790)\">'\n        '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n        '<path fill=\"#ededed\" '\n        'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n        'fill-rule=\"evenodd\"/>'\n        '<path fill=\"#ededed\" '\n        'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n        \"</g>\";\n\n    string private constant _LOGO =\n        '<path fill=\"#ededed\" '\n        'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n        'vector-effect=\"non-scaling-stroke\" />';\n\n    /**\n        @dev internal helper to create HSL-encoded color prop for SVG tags\n     */\n    function colorHSL(Color memory c) internal pure returns (bytes memory) {\n        return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n    }\n\n    /**\n        @dev internal helper to create `stop` SVG tag\n     */\n    function colorStop(Color memory c) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                '<stop stop-color=\"',\n                colorHSL(c),\n                '\" stop-opacity=\"',\n                c.a.toString(),\n                '\" offset=\"',\n                c.off.toString(),\n                '%\"/>'\n            );\n    }\n\n    /**\n        @dev internal helper to encode position for `Gradient` SVG tag\n     */\n    function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                'x1=\"',\n                coords[0].toString(),\n                '%\" '\n                'y1=\"',\n                coords[1].toString(),\n                '%\" '\n                'x2=\"',\n                coords[2].toString(),\n                '%\" '\n                'y2=\"',\n                coords[3].toString(),\n                '%\" '\n            );\n    }\n\n    /**\n        @dev internal helper to create `Gradient` SVG tag\n     */\n    function linearGradient(\n        Color[] memory colors,\n        uint256 id,\n        uint256[4] memory coords\n    ) internal pure returns (bytes memory) {\n        string memory stops = \"\";\n        for (uint256 i = 0; i < colors.length; i++) {\n            if (colors[i].h != 0) {\n                stops = string.concat(stops, string(colorStop(colors[i])));\n            }\n        }\n        return\n            abi.encodePacked(\n                \"<linearGradient  \",\n                pos(coords),\n                'id=\"g',\n                id.toString(),\n                '\">',\n                stops,\n                \"</linearGradient>\"\n            );\n    }\n\n    /**\n        @dev internal helper to create `Defs` SVG tag\n     */\n    function defs(Gradient memory grad) internal pure returns (bytes memory) {\n        return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n    }\n\n    /**\n        @dev internal helper to create `Rect` SVG tag\n     */\n    function rect(uint256 id) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                \"<rect \"\n                'width=\"100%\" '\n                'height=\"100%\" '\n                'fill=\"url(#g',\n                id.toString(),\n                ')\" '\n                'rx=\"10px\" '\n                'ry=\"10px\" '\n                'stroke-linejoin=\"round\" '\n                \"/>\"\n            );\n    }\n\n    /**\n        @dev internal helper to create border `Rect` SVG tag\n     */\n    function border() internal pure returns (string memory) {\n        return\n            \"<rect \"\n            'width=\"94%\" '\n            'height=\"96%\" '\n            'fill=\"transparent\" '\n            'rx=\"10px\" '\n            'ry=\"10px\" '\n            'stroke-linejoin=\"round\" '\n            'x=\"3%\" '\n            'y=\"2%\" '\n            'stroke-dasharray=\"1,6\" '\n            'stroke=\"white\" '\n            \"/>\";\n    }\n\n    /**\n        @dev internal helper to create group `G` SVG tag\n     */\n    function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n        string memory background = \"\";\n        for (uint256 i = 0; i < gradientsCount; i++) {\n            background = string.concat(background, string(rect(i)));\n        }\n        return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n    }\n\n    /**\n        @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n     */\n    function logo() internal pure returns (bytes memory) {\n        return abi.encodePacked();\n    }\n\n    /**\n        @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n     */\n    function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                \"<text \"\n                'x=\"50%\" '\n                'y=\"5%\" '\n                'class=\"base small\" '\n                'dominant-baseline=\"middle\" '\n                'text-anchor=\"middle\">',\n                symbol,\n                unicode\"・\",\n                xenAddress.toHexString(),\n                \"</text>\"\n            );\n    }\n\n    /**\n        @dev internal helper to create cRank range string\n     */\n    function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n        if (count == 1) return abi.encodePacked(rank.toString());\n        return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n    }\n\n    /**\n        @dev internal helper to create 1st part of metadata section of SVG\n     */\n    function meta1(\n        uint256 tokenId,\n        uint256 count,\n        uint256 eaa,\n        string memory series,\n        uint256 xenBurned\n    ) internal pure returns (bytes memory) {\n        bytes memory part1 = abi.encodePacked(\n            \"<text \"\n            'x=\"50%\" '\n            'y=\"50%\" '\n            'class=\"base \" '\n            'dominant-baseline=\"middle\" '\n            'text-anchor=\"middle\">'\n            \"XEN CRYPTO\"\n            \"</text>\"\n            \"<text \"\n            'x=\"50%\" '\n            'y=\"56%\" '\n            'class=\"base burn\" '\n            'text-anchor=\"middle\" '\n            'dominant-baseline=\"middle\"> ',\n            xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n            \"</text>\"\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"62%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\"> '\n            \"#\",\n            tokenId.toString(),\n            \"</text>\"\n            \"<text \"\n            'x=\"82%\" '\n            'y=\"62%\" '\n            'class=\"base meta series\" '\n            'dominant-baseline=\"middle\" '\n            'text-anchor=\"end\" >',\n            series,\n            \"</text>\"\n        );\n        bytes memory part2 = abi.encodePacked(\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"68%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"VMU: \",\n            count.toString(),\n            \"</text>\"\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"72%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"EAA: \",\n            (eaa / 10).toString(),\n            \"%\"\n            \"</text>\"\n        );\n        return abi.encodePacked(part1, part2);\n    }\n\n    /**\n        @dev internal helper to create 2nd part of metadata section of SVG\n     */\n    function meta2(\n        uint256 maturityTs,\n        uint256 amp,\n        uint256 term,\n        uint256 rank,\n        uint256 count\n    ) internal pure returns (bytes memory) {\n        bytes memory part3 = abi.encodePacked(\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"76%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"AMP: \",\n            amp.toString(),\n            \"</text>\"\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"80%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"Term: \",\n            term.toString()\n        );\n        bytes memory part4 = abi.encodePacked(\n            \" days\"\n            \"</text>\"\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"84%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"cRank: \",\n            rankAndCount(rank, count),\n            \"</text>\"\n            \"<text \"\n            'x=\"18%\" '\n            'y=\"88%\" '\n            'class=\"base meta\" '\n            'dominant-baseline=\"middle\" >'\n            \"Maturity: \",\n            maturityTs.asString(),\n            \"</text>\"\n        );\n        return abi.encodePacked(part3, part4);\n    }\n\n    /**\n        @dev internal helper to create `Text` SVG tag for XEN quote\n     */\n    function quote(uint256 idx) internal pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                \"<text \"\n                'x=\"50%\" '\n                'y=\"95%\" '\n                'class=\"base small\" '\n                'dominant-baseline=\"middle\" '\n                'text-anchor=\"middle\" >',\n                StringData.getQuote(StringData.QUOTES, idx),\n                \"</text>\"\n            );\n    }\n\n    /**\n        @dev internal helper to generate `Redeemed` stamp\n     */\n    function stamp(bool redeemed) internal pure returns (bytes memory) {\n        if (!redeemed) return \"\";\n        return\n            abi.encodePacked(\n                \"<rect \"\n                'x=\"50%\" '\n                'y=\"77.5%\" '\n                'width=\"100\" '\n                'height=\"40\" '\n                'stroke=\"black\" '\n                'stroke-width=\"1\" '\n                'fill=\"none\" '\n                'rx=\"5px\" '\n                'ry=\"5px\" '\n                'transform=\"translate(-50,-20) '\n                'rotate(-20,0,400)\" />',\n                \"<text \"\n                'x=\"50%\" '\n                'y=\"77.5%\" '\n                'stroke=\"black\" '\n                'class=\"base meta\" '\n                'dominant-baseline=\"middle\" '\n                'text-anchor=\"middle\" '\n                'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n                \"Redeemed\"\n                \"</text>\"\n            );\n    }\n\n    /**\n        @dev main internal helper to create SVG file representing XENFT\n     */\n    function image(\n        SvgParams memory params,\n        Gradient[] memory gradients,\n        uint256 idx,\n        bool apex,\n        bool limited\n    ) internal pure returns (bytes memory) {\n        string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n        bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n        bytes memory metadata = abi.encodePacked(\n            contractData(params.symbol, params.xenAddress),\n            meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n            meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n            quote(idx),\n            stamp(params.redeemed)\n        );\n        return\n            abi.encodePacked(\n                \"<svg \"\n                'xmlns=\"http://www.w3.org/2000/svg\" '\n                'preserveAspectRatio=\"xMinYMin meet\" '\n                'viewBox=\"0 0 350 566\">',\n                graphics,\n                metadata,\n                \"</svg>\"\n            );\n    }\n}\n"
      },
      "/contracts/libs/MintInfo.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n//      term (uint16)\n//      | maturityTs (uint64)\n//      | rank (uint128)\n//      | amp (uint16)\n//      | eaa (uint16)\n//      | class (uint8):\n//          [7] isApex\n//          [6] isLimited\n//          [0-5] powerGroupIdx\n//      | redeemed (uint8)\nlibrary MintInfo {\n    /**\n        @dev helper to convert Bool to U256 type and make compiler happy\n     */\n    function toU256(bool x) internal pure returns (uint256 r) {\n        assembly {\n            r := x\n        }\n    }\n\n    /**\n        @dev encodes MintInfo record from its props\n     */\n    function encodeMintInfo(\n        uint256 term,\n        uint256 maturityTs,\n        uint256 rank,\n        uint256 amp,\n        uint256 eaa,\n        uint256 class_,\n        bool redeemed\n    ) public pure returns (uint256 info) {\n        info = info | (toU256(redeemed) & 0xFF);\n        info = info | ((class_ & 0xFF) << 8);\n        info = info | ((eaa & 0xFFFF) << 16);\n        info = info | ((amp & 0xFFFF) << 32);\n        info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n        info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n        info = info | ((term & 0xFFFF) << 240);\n    }\n\n    /**\n        @dev decodes MintInfo record and extracts all of its props\n     */\n    function decodeMintInfo(uint256 info)\n        public\n        pure\n        returns (\n            uint256 term,\n            uint256 maturityTs,\n            uint256 rank,\n            uint256 amp,\n            uint256 eaa,\n            uint256 class,\n            bool apex,\n            bool limited,\n            bool redeemed\n        )\n    {\n        term = uint16(info >> 240);\n        maturityTs = uint64(info >> 176);\n        rank = uint128(info >> 48);\n        amp = uint16(info >> 32);\n        eaa = uint16(info >> 16);\n        class = uint8(info >> 8) & 0x3F;\n        apex = (uint8(info >> 8) & 0x80) > 0;\n        limited = (uint8(info >> 8) & 0x40) > 0;\n        redeemed = uint8(info) == 1;\n    }\n\n    /**\n        @dev extracts `term` prop from encoded MintInfo\n     */\n    function getTerm(uint256 info) public pure returns (uint256 term) {\n        (term, , , , , , , , ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `maturityTs` prop from encoded MintInfo\n     */\n    function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n        (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `rank` prop from encoded MintInfo\n     */\n    function getRank(uint256 info) public pure returns (uint256 rank) {\n        (, , rank, , , , , , ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `AMP` prop from encoded MintInfo\n     */\n    function getAMP(uint256 info) public pure returns (uint256 amp) {\n        (, , , amp, , , , , ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `EAA` prop from encoded MintInfo\n     */\n    function getEAA(uint256 info) public pure returns (uint256 eaa) {\n        (, , , , eaa, , , , ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `redeemed` prop from encoded MintInfo\n     */\n    function getClass(uint256 info)\n        public\n        pure\n        returns (\n            uint256 class_,\n            bool apex,\n            bool limited\n        )\n    {\n        (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n    }\n\n    /**\n        @dev extracts `redeemed` prop from encoded MintInfo\n     */\n    function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n        (, , , , , , , , redeemed) = decodeMintInfo(info);\n    }\n}\n"
      },
      "/contracts/libs/Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n    @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n    using DateTime for uint256;\n    using MintInfo for uint256;\n    using Strings for uint256;\n\n    uint256 public constant POWER_GROUP_SIZE = 7_500;\n    uint256 public constant MAX_POWER = 52_500;\n\n    uint256 public constant COLORS_FULL_SCALE = 300;\n    uint256 public constant SPECIAL_LUMINOSITY = 45;\n    uint256 public constant BASE_SATURATION = 75;\n    uint256 public constant BASE_LUMINOSITY = 38;\n    uint256 public constant GROUP_SATURATION = 100;\n    uint256 public constant GROUP_LUMINOSITY = 50;\n    uint256 public constant DEFAULT_OPACITY = 1;\n    uint256 public constant NO_COLOR = 360;\n\n    // PRIVATE HELPERS\n\n    // The following pure methods returning arrays are workaround to use array constants,\n    // not yet available in Solidity\n\n    function _powerGroupColors() private pure returns (uint256[8] memory) {\n        return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n    }\n\n    function _huesApex() private pure returns (uint256[3] memory) {\n        return [uint256(169), 210, 305];\n    }\n\n    function _huesLimited() private pure returns (uint256[3] memory) {\n        return [uint256(263), 0, 42];\n    }\n\n    function _stopOffsets() private pure returns (uint256[3] memory) {\n        return [uint256(10), 50, 90];\n    }\n\n    function _gradColorsRegular() private pure returns (uint256[4] memory) {\n        return [uint256(150), 150, 20, 20];\n    }\n\n    function _gradColorsBlack() private pure returns (uint256[4] memory) {\n        return [uint256(100), 100, 20, 20];\n    }\n\n    function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n        return [uint256(100), 100, 0, 0];\n    }\n\n    /**\n        @dev private helper to determine XENFT group index by its power\n             (power = count of VMUs * mint term in days)\n     */\n    function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n        return (vmus * term) / POWER_GROUP_SIZE;\n    }\n\n    /**\n        @dev private helper to generate SVG gradients for special XENFT categories\n     */\n    function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n        uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n        SVG.Color[] memory colors = new SVG.Color[](3);\n        for (uint256 i = 0; i < colors.length; i++) {\n            colors[i] = SVG.Color({\n                h: specialColors[i],\n                s: BASE_SATURATION,\n                l: SPECIAL_LUMINOSITY,\n                a: DEFAULT_OPACITY,\n                off: _stopOffsets()[i]\n            });\n        }\n        gradients = new SVG.Gradient[](1);\n        gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n    }\n\n    /**\n        @dev private helper to generate SVG gradients for common XENFT category\n     */\n    function _commonCategoryGradients(uint256 vmus, uint256 term)\n        private\n        pure\n        returns (SVG.Gradient[] memory gradients)\n    {\n        SVG.Color[] memory colors = new SVG.Color[](2);\n        uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n        // group\n        uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n        colors[0] = SVG.Color({\n            h: groupHue,\n            s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n            l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n            a: DEFAULT_OPACITY,\n            off: _stopOffsets()[0]\n        });\n        // power\n        colors[1] = SVG.Color({\n            h: powerHue,\n            s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n            l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n            a: DEFAULT_OPACITY,\n            off: _stopOffsets()[2]\n        });\n        gradients = new SVG.Gradient[](1);\n        gradients[0] = SVG.Gradient({\n            colors: colors,\n            id: 0,\n            coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n        });\n    }\n\n    // PUBLIC INTERFACE\n\n    /**\n        @dev public interface to generate SVG image based on XENFT params\n     */\n    function svgData(\n        uint256 tokenId,\n        uint256 count,\n        uint256 info,\n        address token,\n        uint256 burned\n    ) external view returns (bytes memory) {\n        string memory symbol = IERC20Metadata(token).symbol();\n        (uint256 classIds, bool rare, bool limited) = info.getClass();\n        SVG.SvgParams memory params = SVG.SvgParams({\n            symbol: symbol,\n            xenAddress: token,\n            tokenId: tokenId,\n            term: info.getTerm(),\n            rank: info.getRank(),\n            count: count,\n            maturityTs: info.getMaturityTs(),\n            amp: info.getAMP(),\n            eaa: info.getEAA(),\n            xenBurned: burned,\n            series: StringData.getClassName(StringData.CLASSES, classIds),\n            redeemed: info.getRedeemed()\n        });\n        uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n        if (rare || limited) {\n            return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n        }\n        return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n    }\n\n    function _attr1(\n        uint256 count,\n        uint256 rank,\n        uint256 class_\n    ) private pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                '{\"trait_type\":\"Class\",\"value\":\"',\n                StringData.getClassName(StringData.CLASSES, class_),\n                '\"},'\n                '{\"trait_type\":\"VMUs\",\"value\":\"',\n                count.toString(),\n                '\"},'\n                '{\"trait_type\":\"cRank\",\"value\":\"',\n                rank.toString(),\n                '\"},'\n            );\n    }\n\n    function _attr2(\n        uint256 amp,\n        uint256 eaa,\n        uint256 maturityTs\n    ) private pure returns (bytes memory) {\n        (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n        return\n            abi.encodePacked(\n                '{\"trait_type\":\"AMP\",\"value\":\"',\n                amp.toString(),\n                '\"},'\n                '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n                (eaa / 10).toString(),\n                '\"},'\n                '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n                year.toString(),\n                '\"},'\n                '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n                month,\n                '\"},'\n            );\n    }\n\n    function _attr3(\n        uint256 maturityTs,\n        uint256 term,\n        uint256 burned\n    ) private pure returns (bytes memory) {\n        return\n            abi.encodePacked(\n                '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n                maturityTs.asString(),\n                '\"},'\n                '{\"trait_type\":\"Term\",\"value\":\"',\n                term.toString(),\n                '\"},'\n                '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n                (burned / 10**18).toString(),\n                '\"},'\n            );\n    }\n\n    function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n        string memory category = \"Collector\";\n        if (limited) category = \"Limited\";\n        if (apex) category = \"Apex\";\n        return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n    }\n\n    /**\n        @dev private helper to construct attributes portion of NFT metadata\n     */\n    function attributes(\n        uint256 count,\n        uint256 burned,\n        uint256 mintInfo\n    ) external pure returns (bytes memory) {\n        (\n            uint256 term,\n            uint256 maturityTs,\n            uint256 rank,\n            uint256 amp,\n            uint256 eaa,\n            uint256 series,\n            bool apex,\n            bool limited,\n\n        ) = MintInfo.decodeMintInfo(mintInfo);\n        return\n            abi.encodePacked(\n                \"[\",\n                _attr1(count, rank, series),\n                _attr2(amp, eaa, maturityTs),\n                _attr3(maturityTs, term, burned),\n                _attr4(apex, limited),\n                \"]\"\n            );\n    }\n\n    function formattedString(uint256 n) public pure returns (string memory) {\n        return FormattedStrings.toFormattedString(n);\n    }\n}\n"
      },
      "/contracts/libs/FormattedStrings.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n            Base on OpenZeppelin `toString` method from `String` library\n     */\n    function toFormattedString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        uint256 pos;\n        uint256 comas = digits / 3;\n        digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            if (pos == 3) {\n                buffer[digits] = \",\";\n                pos = 0;\n            } else {\n                buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n                value /= 10;\n                pos++;\n            }\n        }\n        return string(buffer);\n    }\n}\n"
      },
      "/contracts/libs/ERC2771Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    // one-time settable var\n    address internal _trustedForwarder;\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor(address trustedForwarder) {\n        _trustedForwarder = trustedForwarder;\n    }\n\n    function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n        return forwarder == _trustedForwarder;\n    }\n\n    function _msgSender() internal view virtual override returns (address sender) {\n        if (isTrustedForwarder(msg.sender)) {\n            // The assembly code is more direct than the Solidity version using `abi.decode`.\n            /// @solidity memory-safe-assembly\n            assembly {\n                sender := shr(96, calldataload(sub(calldatasize(), 20)))\n            }\n        } else {\n            return super._msgSender();\n        }\n    }\n\n    function _msgData() internal view virtual override returns (bytes calldata) {\n        if (isTrustedForwarder(msg.sender)) {\n            return msg.data[:msg.data.length - 20];\n        } else {\n            return super._msgData();\n        }\n    }\n}\n"
      },
      "/contracts/libs/DateTime.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n    @dev        Library to convert epoch timestamp to a human-readable Date-Time string\n    @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n    using Strings for uint256;\n\n    bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n    /**\n     *   @dev returns month as short (3-letter) string\n     */\n    function monthAsString(uint256 idx) internal pure returns (string memory) {\n        require(idx > 0, \"bad idx\");\n        bytes memory str = new bytes(3);\n        uint256 offset = (idx - 1) * 3;\n        str[0] = bytes1(MONTHS[offset]);\n        str[1] = bytes1(MONTHS[offset + 1]);\n        str[2] = bytes1(MONTHS[offset + 2]);\n        return string(str);\n    }\n\n    /**\n     *   @dev returns string representation of number left-padded for 2 symbols\n     */\n    function asPaddedString(uint256 n) internal pure returns (string memory) {\n        if (n == 0) return \"00\";\n        if (n < 10) return string.concat(\"0\", n.toString());\n        return n.toString();\n    }\n\n    /**\n     *   @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n     */\n    function asString(uint256 ts) external pure returns (string memory) {\n        (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n            .timestampToDateTime(ts);\n        return\n            string(\n                abi.encodePacked(\n                    monthAsString(month),\n                    \" \",\n                    day.toString(),\n                    \", \",\n                    year.toString(),\n                    \" \",\n                    asPaddedString(hour),\n                    \":\",\n                    asPaddedString(minute),\n                    \" UTC\"\n                )\n            );\n    }\n\n    /**\n     *   @dev returns (year, month as string) components of a date by timestamp\n     */\n    function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n        (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n        return (year, monthAsString(month));\n    }\n}\n"
      },
      "/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit      | Range         | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0          | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year      | 1970 ... 2345 |\n// month     | 1 ... 12      |\n// day       | 1 ... 31      |\n// hour      | 0 ... 23      |\n// minute    | 0 ... 59      |\n// second    | 0 ... 59      |\n// dayOfWeek | 1 ... 7       | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n    uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n    uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n    uint256 constant _SECONDS_PER_MINUTE = 60;\n    int256 constant _OFFSET19700101 = 2440588;\n\n    uint256 constant _DOW_FRI = 5;\n    uint256 constant _DOW_SAT = 6;\n\n    // ------------------------------------------------------------------------\n    // Calculate the number of days from 1970/01/01 to year/month/day using\n    // the date conversion algorithm from\n    //   https://aa.usno.navy.mil/faq/JD_formula.html\n    // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n    //\n    // days = day\n    //      - 32075\n    //      + 1461 * (year + 4800 + (month - 14) / 12) / 4\n    //      + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n    //      - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n    //      - offset\n    // ------------------------------------------------------------------------\n    function _daysFromDate(\n        uint256 year,\n        uint256 month,\n        uint256 day\n    ) private pure returns (uint256 _days) {\n        require(year >= 1970);\n        int256 _year = int256(year);\n        int256 _month = int256(month);\n        int256 _day = int256(day);\n\n        int256 __days = _day -\n            32075 +\n            (1461 * (_year + 4800 + (_month - 14) / 12)) /\n            4 +\n            (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n            12 -\n            (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n            4 -\n            _OFFSET19700101;\n\n        _days = uint256(__days);\n    }\n\n    // ------------------------------------------------------------------------\n    // Calculate year/month/day from the number of days since 1970/01/01 using\n    // the date conversion algorithm from\n    //   http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n    // and adding the offset 2440588 so that 1970/01/01 is day 0\n    //\n    // int L = days + 68569 + offset\n    // int N = 4 * L / 146097\n    // L = L - (146097 * N + 3) / 4\n    // year = 4000 * (L + 1) / 1461001\n    // L = L - 1461 * year / 4 + 31\n    // month = 80 * L / 2447\n    // dd = L - 2447 * month / 80\n    // L = month / 11\n    // month = month + 2 - 12 * L\n    // year = 100 * (N - 49) + year + L\n    // ------------------------------------------------------------------------\n    function _daysToDate(uint256 _days)\n        private\n        pure\n        returns (\n            uint256 year,\n            uint256 month,\n            uint256 day\n        )\n    {\n        int256 __days = int256(_days);\n\n        int256 L = __days + 68569 + _OFFSET19700101;\n        int256 N = (4 * L) / 146097;\n        L = L - (146097 * N + 3) / 4;\n        int256 _year = (4000 * (L + 1)) / 1461001;\n        L = L - (1461 * _year) / 4 + 31;\n        int256 _month = (80 * L) / 2447;\n        int256 _day = L - (2447 * _month) / 80;\n        L = _month / 11;\n        _month = _month + 2 - 12 * L;\n        _year = 100 * (N - 49) + _year + L;\n\n        year = uint256(_year);\n        month = uint256(_month);\n        day = uint256(_day);\n    }\n\n    function timestampFromDate(\n        uint256 year,\n        uint256 month,\n        uint256 day\n    ) internal pure returns (uint256 timestamp) {\n        timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n    }\n\n    function timestampFromDateTime(\n        uint256 year,\n        uint256 month,\n        uint256 day,\n        uint256 hour,\n        uint256 minute,\n        uint256 second\n    ) internal pure returns (uint256 timestamp) {\n        timestamp =\n            _daysFromDate(year, month, day) *\n            _SECONDS_PER_DAY +\n            hour *\n            _SECONDS_PER_HOUR +\n            minute *\n            _SECONDS_PER_MINUTE +\n            second;\n    }\n\n    function timestampToDate(uint256 timestamp)\n        internal\n        pure\n        returns (\n            uint256 year,\n            uint256 month,\n            uint256 day\n        )\n    {\n        (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n    }\n\n    function timestampToDateTime(uint256 timestamp)\n        internal\n        pure\n        returns (\n            uint256 year,\n            uint256 month,\n            uint256 day,\n            uint256 hour,\n            uint256 minute,\n            uint256 second\n        )\n    {\n        (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        uint256 secs = timestamp % _SECONDS_PER_DAY;\n        hour = secs / _SECONDS_PER_HOUR;\n        secs = secs % _SECONDS_PER_HOUR;\n        minute = secs / _SECONDS_PER_MINUTE;\n        second = secs % _SECONDS_PER_MINUTE;\n    }\n\n    function isValidDate(\n        uint256 year,\n        uint256 month,\n        uint256 day\n    ) internal pure returns (bool valid) {\n        if (year >= 1970 && month > 0 && month <= 12) {\n            uint256 daysInMonth = _getDaysInMonth(year, month);\n            if (day > 0 && day <= daysInMonth) {\n                valid = true;\n            }\n        }\n    }\n\n    function isValidDateTime(\n        uint256 year,\n        uint256 month,\n        uint256 day,\n        uint256 hour,\n        uint256 minute,\n        uint256 second\n    ) internal pure returns (bool valid) {\n        if (isValidDate(year, month, day)) {\n            if (hour < 24 && minute < 60 && second < 60) {\n                valid = true;\n            }\n        }\n    }\n\n    function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n        (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        leapYear = _isLeapYear(year);\n    }\n\n    function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n        leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n    }\n\n    function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n        weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n    }\n\n    function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n        weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n    }\n\n    function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n        (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        daysInMonth = _getDaysInMonth(year, month);\n    }\n\n    function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n            daysInMonth = 31;\n        } else if (month != 2) {\n            daysInMonth = 30;\n        } else {\n            daysInMonth = _isLeapYear(year) ? 29 : 28;\n        }\n    }\n\n    // 1 = Monday, 7 = Sunday\n    function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n        uint256 _days = timestamp / _SECONDS_PER_DAY;\n        dayOfWeek = ((_days + 3) % 7) + 1;\n    }\n\n    function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n        (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n    }\n\n    function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n        (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n    }\n\n    function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n        (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n    }\n\n    function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n        uint256 secs = timestamp % _SECONDS_PER_DAY;\n        hour = secs / _SECONDS_PER_HOUR;\n    }\n\n    function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n        uint256 secs = timestamp % _SECONDS_PER_HOUR;\n        minute = secs / _SECONDS_PER_MINUTE;\n    }\n\n    function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n        second = timestamp % _SECONDS_PER_MINUTE;\n    }\n\n    function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n        (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        year += _years;\n        uint256 daysInMonth = _getDaysInMonth(year, month);\n        if (day > daysInMonth) {\n            day = daysInMonth;\n        }\n        newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n        require(newTimestamp >= timestamp);\n    }\n\n    function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n        (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        month += _months;\n        year += (month - 1) / 12;\n        month = ((month - 1) % 12) + 1;\n        uint256 daysInMonth = _getDaysInMonth(year, month);\n        if (day > daysInMonth) {\n            day = daysInMonth;\n        }\n        newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n        require(newTimestamp >= timestamp);\n    }\n\n    function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n        require(newTimestamp >= timestamp);\n    }\n\n    function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n        require(newTimestamp >= timestamp);\n    }\n\n    function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n        require(newTimestamp >= timestamp);\n    }\n\n    function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp + _seconds;\n        require(newTimestamp >= timestamp);\n    }\n\n    function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n        (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        year -= _years;\n        uint256 daysInMonth = _getDaysInMonth(year, month);\n        if (day > daysInMonth) {\n            day = daysInMonth;\n        }\n        newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n        require(newTimestamp <= timestamp);\n    }\n\n    function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n        (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n        uint256 yearMonth = year * 12 + (month - 1) - _months;\n        year = yearMonth / 12;\n        month = (yearMonth % 12) + 1;\n        uint256 daysInMonth = _getDaysInMonth(year, month);\n        if (day > daysInMonth) {\n            day = daysInMonth;\n        }\n        newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n        require(newTimestamp <= timestamp);\n    }\n\n    function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n        require(newTimestamp <= timestamp);\n    }\n\n    function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n        require(newTimestamp <= timestamp);\n    }\n\n    function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n        require(newTimestamp <= timestamp);\n    }\n\n    function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n        newTimestamp = timestamp - _seconds;\n        require(newTimestamp <= timestamp);\n    }\n\n    function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n        require(fromTimestamp <= toTimestamp);\n        (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n        (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n        _years = toYear - fromYear;\n    }\n\n    function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n        require(fromTimestamp <= toTimestamp);\n        (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n        (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n        _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n    }\n\n    function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n        require(fromTimestamp <= toTimestamp);\n        _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n    }\n\n    function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n        require(fromTimestamp <= toTimestamp);\n        _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n    }\n\n    function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n        require(fromTimestamp <= toTimestamp);\n        _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n    }\n\n    function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n        require(fromTimestamp <= toTimestamp);\n        _seconds = toTimestamp - fromTimestamp;\n    }\n}\n"
      },
      "/contracts/libs/Array.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n    function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n        for (i = 1; i <= arr.length; i++) {\n            if (arr[i - 1] == item) {\n                return i;\n            }\n        }\n        i = 0;\n    }\n\n    function addItem(uint256[] storage arr, uint256 item) internal {\n        if (idx(arr, item) == 0) {\n            arr.push(item);\n        }\n    }\n\n    function removeItem(uint256[] storage arr, uint256 item) internal {\n        uint256 i = idx(arr, item);\n        if (i > 0) {\n            arr[i - 1] = arr[arr.length - 1];\n            arr.pop();\n        }\n    }\n\n    function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n        if (items.length == 0) return true;\n        for (uint256 i = 0; i < items.length; i++) {\n            bool itemIsContained = false;\n            for (uint256 j = 0; j < container.length; j++) {\n                itemIsContained = items[i] == container[j];\n            }\n            if (!itemIsContained) return false;\n        }\n        return true;\n    }\n\n    function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n        uint256[] memory array = new uint256[](1);\n        array[0] = element;\n        return array;\n    }\n\n    function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n        for (uint256 i = 0; i < array.length; i++) {\n            if (array[i] == 0) return true;\n            for (uint256 j = 0; j < array.length; j++) {\n                if (array[i] == array[j] && i != j) return true;\n            }\n        }\n        return false;\n    }\n\n    function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n        uint256 _first = array[0];\n        for (uint256 i = 0; i < array.length; i++) {\n            if (array[i] == 0 || array[i] != _first) return true;\n        }\n        return false;\n    }\n}\n"
      },
      "/contracts/interfaces/IXENTorrent.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n    event StartTorrent(address indexed user, uint256 count, uint256 term);\n    event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n    function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n    function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
      },
      "/contracts/interfaces/IXENProxying.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n    function callClaimRank(uint256 term) external;\n\n    function callClaimMintReward(address to) external;\n\n    function powerDown() external;\n}\n"
      },
      "/contracts/interfaces/IERC2771.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n    function isTrustedForwarder(address forwarder) external;\n}\n"
      },
      "operator-filter-registry/src/OperatorFilterer.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title  OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n *         registrant's entries in the OperatorFilterRegistry.\n * @dev    This smart contract is meant to be inherited by token contracts so they can use the following:\n *         - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n *         - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n    error OperatorNotAllowed(address operator);\n\n    IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n        IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n    constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n        // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n        // will not revert, but the contract will need to be registered with the registry once it is deployed in\n        // order for the modifier to filter addresses.\n        if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n            if (subscribe) {\n                OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n            } else {\n                if (subscriptionOrRegistrantToCopy != address(0)) {\n                    OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n                } else {\n                    OPERATOR_FILTER_REGISTRY.register(address(this));\n                }\n            }\n        }\n    }\n\n    modifier onlyAllowedOperator(address from) virtual {\n        // Allow spending tokens from addresses with balance\n        // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n        // from an EOA.\n        if (from != msg.sender) {\n            _checkFilterOperator(msg.sender);\n        }\n        _;\n    }\n\n    modifier onlyAllowedOperatorApproval(address operator) virtual {\n        _checkFilterOperator(operator);\n        _;\n    }\n\n    function _checkFilterOperator(address operator) internal view virtual {\n        // Check registry code length to facilitate testing in environments without a deployed registry.\n        if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n            if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n                revert OperatorNotAllowed(operator);\n            }\n        }\n    }\n}\n"
      },
      "operator-filter-registry/src/IOperatorFilterRegistry.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n    function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n    function register(address registrant) external;\n    function registerAndSubscribe(address registrant, address subscription) external;\n    function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n    function unregister(address addr) external;\n    function updateOperator(address registrant, address operator, bool filtered) external;\n    function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n    function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n    function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n    function subscribe(address registrant, address registrantToSubscribe) external;\n    function unsubscribe(address registrant, bool copyExistingEntries) external;\n    function subscriptionOf(address addr) external returns (address registrant);\n    function subscribers(address registrant) external returns (address[] memory);\n    function subscriberAt(address registrant, uint256 index) external returns (address);\n    function copyEntriesOf(address registrant, address registrantToCopy) external;\n    function isOperatorFiltered(address registrant, address operator) external returns (bool);\n    function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n    function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n    function filteredOperators(address addr) external returns (address[] memory);\n    function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n    function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n    function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n    function isRegistered(address addr) external returns (bool);\n    function codeHashOf(address addr) external returns (bytes32);\n}\n"
      },
      "operator-filter-registry/src/DefaultOperatorFilterer.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title  DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n    address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n    constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
      },
      "abdk-libraries-solidity/ABDKMath64x64.sol": {
        "content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library.  Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers.  Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64.  As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n  /*\n   * Minimum value signed 64.64-bit fixed point number may have. \n   */\n  int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n  /*\n   * Maximum value signed 64.64-bit fixed point number may have. \n   */\n  int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n  /**\n   * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n   * number.  Revert on overflow.\n   *\n   * @param x signed 256-bit integer number\n   * @return signed 64.64-bit fixed point number\n   */\n  function fromInt (int256 x) internal pure returns (int128) {\n    unchecked {\n      require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n      return int128 (x << 64);\n    }\n  }\n\n  /**\n   * Convert signed 64.64 fixed point number into signed 64-bit integer number\n   * rounding down.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64-bit integer number\n   */\n  function toInt (int128 x) internal pure returns (int64) {\n    unchecked {\n      return int64 (x >> 64);\n    }\n  }\n\n  /**\n   * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n   * number.  Revert on overflow.\n   *\n   * @param x unsigned 256-bit integer number\n   * @return signed 64.64-bit fixed point number\n   */\n  function fromUInt (uint256 x) internal pure returns (int128) {\n    unchecked {\n      require (x <= 0x7FFFFFFFFFFFFFFF);\n      return int128 (int256 (x << 64));\n    }\n  }\n\n  /**\n   * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n   * number rounding down.  Revert on underflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return unsigned 64-bit integer number\n   */\n  function toUInt (int128 x) internal pure returns (uint64) {\n    unchecked {\n      require (x >= 0);\n      return uint64 (uint128 (x >> 64));\n    }\n  }\n\n  /**\n   * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n   * number rounding down.  Revert on overflow.\n   *\n   * @param x signed 128.128-bin fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function from128x128 (int256 x) internal pure returns (int128) {\n    unchecked {\n      int256 result = x >> 64;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n   * number.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 128.128 fixed point number\n   */\n  function to128x128 (int128 x) internal pure returns (int256) {\n    unchecked {\n      return int256 (x) << 64;\n    }\n  }\n\n  /**\n   * Calculate x + y.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function add (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      int256 result = int256(x) + y;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate x - y.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function sub (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      int256 result = int256(x) - y;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate x * y rounding down.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function mul (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      int256 result = int256(x) * y >> 64;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n   * number and y is signed 256-bit integer number.  Revert on overflow.\n   *\n   * @param x signed 64.64 fixed point number\n   * @param y signed 256-bit integer number\n   * @return signed 256-bit integer number\n   */\n  function muli (int128 x, int256 y) internal pure returns (int256) {\n    unchecked {\n      if (x == MIN_64x64) {\n        require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n          y <= 0x1000000000000000000000000000000000000000000000000);\n        return -y << 63;\n      } else {\n        bool negativeResult = false;\n        if (x < 0) {\n          x = -x;\n          negativeResult = true;\n        }\n        if (y < 0) {\n          y = -y; // We rely on overflow behavior here\n          negativeResult = !negativeResult;\n        }\n        uint256 absoluteResult = mulu (x, uint256 (y));\n        if (negativeResult) {\n          require (absoluteResult <=\n            0x8000000000000000000000000000000000000000000000000000000000000000);\n          return -int256 (absoluteResult); // We rely on overflow behavior here\n        } else {\n          require (absoluteResult <=\n            0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n          return int256 (absoluteResult);\n        }\n      }\n    }\n  }\n\n  /**\n   * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n   * and y is unsigned 256-bit integer number.  Revert on overflow.\n   *\n   * @param x signed 64.64 fixed point number\n   * @param y unsigned 256-bit integer number\n   * @return unsigned 256-bit integer number\n   */\n  function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n    unchecked {\n      if (y == 0) return 0;\n\n      require (x >= 0);\n\n      uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n      uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n      require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n      hi <<= 64;\n\n      require (hi <=\n        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n      return hi + lo;\n    }\n  }\n\n  /**\n   * Calculate x / y rounding towards zero.  Revert on overflow or when y is\n   * zero.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function div (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      require (y != 0);\n      int256 result = (int256 (x) << 64) / y;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n   * integer numbers.  Revert on overflow or when y is zero.\n   *\n   * @param x signed 256-bit integer number\n   * @param y signed 256-bit integer number\n   * @return signed 64.64-bit fixed point number\n   */\n  function divi (int256 x, int256 y) internal pure returns (int128) {\n    unchecked {\n      require (y != 0);\n\n      bool negativeResult = false;\n      if (x < 0) {\n        x = -x; // We rely on overflow behavior here\n        negativeResult = true;\n      }\n      if (y < 0) {\n        y = -y; // We rely on overflow behavior here\n        negativeResult = !negativeResult;\n      }\n      uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n      if (negativeResult) {\n        require (absoluteResult <= 0x80000000000000000000000000000000);\n        return -int128 (absoluteResult); // We rely on overflow behavior here\n      } else {\n        require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n        return int128 (absoluteResult); // We rely on overflow behavior here\n      }\n    }\n  }\n\n  /**\n   * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n   * integer numbers.  Revert on overflow or when y is zero.\n   *\n   * @param x unsigned 256-bit integer number\n   * @param y unsigned 256-bit integer number\n   * @return signed 64.64-bit fixed point number\n   */\n  function divu (uint256 x, uint256 y) internal pure returns (int128) {\n    unchecked {\n      require (y != 0);\n      uint128 result = divuu (x, y);\n      require (result <= uint128 (MAX_64x64));\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate -x.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function neg (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x != MIN_64x64);\n      return -x;\n    }\n  }\n\n  /**\n   * Calculate |x|.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function abs (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x != MIN_64x64);\n      return x < 0 ? -x : x;\n    }\n  }\n\n  /**\n   * Calculate 1 / x rounding towards zero.  Revert on overflow or when x is\n   * zero.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function inv (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x != 0);\n      int256 result = int256 (0x100000000000000000000000000000000) / x;\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function avg (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      return int128 ((int256 (x) + int256 (y)) >> 1);\n    }\n  }\n\n  /**\n   * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n   * Revert on overflow or in case x * y is negative.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function gavg (int128 x, int128 y) internal pure returns (int128) {\n    unchecked {\n      int256 m = int256 (x) * int256 (y);\n      require (m >= 0);\n      require (m <\n          0x4000000000000000000000000000000000000000000000000000000000000000);\n      return int128 (sqrtu (uint256 (m)));\n    }\n  }\n\n  /**\n   * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n   * and y is unsigned 256-bit integer number.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @param y uint256 value\n   * @return signed 64.64-bit fixed point number\n   */\n  function pow (int128 x, uint256 y) internal pure returns (int128) {\n    unchecked {\n      bool negative = x < 0 && y & 1 == 1;\n\n      uint256 absX = uint128 (x < 0 ? -x : x);\n      uint256 absResult;\n      absResult = 0x100000000000000000000000000000000;\n\n      if (absX <= 0x10000000000000000) {\n        absX <<= 63;\n        while (y != 0) {\n          if (y & 0x1 != 0) {\n            absResult = absResult * absX >> 127;\n          }\n          absX = absX * absX >> 127;\n\n          if (y & 0x2 != 0) {\n            absResult = absResult * absX >> 127;\n          }\n          absX = absX * absX >> 127;\n\n          if (y & 0x4 != 0) {\n            absResult = absResult * absX >> 127;\n          }\n          absX = absX * absX >> 127;\n\n          if (y & 0x8 != 0) {\n            absResult = absResult * absX >> 127;\n          }\n          absX = absX * absX >> 127;\n\n          y >>= 4;\n        }\n\n        absResult >>= 64;\n      } else {\n        uint256 absXShift = 63;\n        if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n        if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n        if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n        if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n        if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n        if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n        uint256 resultShift = 0;\n        while (y != 0) {\n          require (absXShift < 64);\n\n          if (y & 0x1 != 0) {\n            absResult = absResult * absX >> 127;\n            resultShift += absXShift;\n            if (absResult > 0x100000000000000000000000000000000) {\n              absResult >>= 1;\n              resultShift += 1;\n            }\n          }\n          absX = absX * absX >> 127;\n          absXShift <<= 1;\n          if (absX >= 0x100000000000000000000000000000000) {\n              absX >>= 1;\n              absXShift += 1;\n          }\n\n          y >>= 1;\n        }\n\n        require (resultShift < 64);\n        absResult >>= 64 - resultShift;\n      }\n      int256 result = negative ? -int256 (absResult) : int256 (absResult);\n      require (result >= MIN_64x64 && result <= MAX_64x64);\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate sqrt (x) rounding down.  Revert if x < 0.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function sqrt (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x >= 0);\n      return int128 (sqrtu (uint256 (int256 (x)) << 64));\n    }\n  }\n\n  /**\n   * Calculate binary logarithm of x.  Revert if x <= 0.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function log_2 (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x > 0);\n\n      int256 msb = 0;\n      int256 xc = x;\n      if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n      if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n      if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n      if (xc >= 0x100) { xc >>= 8; msb += 8; }\n      if (xc >= 0x10) { xc >>= 4; msb += 4; }\n      if (xc >= 0x4) { xc >>= 2; msb += 2; }\n      if (xc >= 0x2) msb += 1;  // No need to shift xc anymore\n\n      int256 result = msb - 64 << 64;\n      uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n      for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n        ux *= ux;\n        uint256 b = ux >> 255;\n        ux >>= 127 + b;\n        result += bit * int256 (b);\n      }\n\n      return int128 (result);\n    }\n  }\n\n  /**\n   * Calculate natural logarithm of x.  Revert if x <= 0.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function ln (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x > 0);\n\n      return int128 (int256 (\n          uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n    }\n  }\n\n  /**\n   * Calculate binary exponent of x.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function exp_2 (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x < 0x400000000000000000); // Overflow\n\n      if (x < -0x400000000000000000) return 0; // Underflow\n\n      uint256 result = 0x80000000000000000000000000000000;\n\n      if (x & 0x8000000000000000 > 0)\n        result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n      if (x & 0x4000000000000000 > 0)\n        result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n      if (x & 0x2000000000000000 > 0)\n        result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n      if (x & 0x1000000000000000 > 0)\n        result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n      if (x & 0x800000000000000 > 0)\n        result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n      if (x & 0x400000000000000 > 0)\n        result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n      if (x & 0x200000000000000 > 0)\n        result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n      if (x & 0x100000000000000 > 0)\n        result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n      if (x & 0x80000000000000 > 0)\n        result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n      if (x & 0x40000000000000 > 0)\n        result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n      if (x & 0x20000000000000 > 0)\n        result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n      if (x & 0x10000000000000 > 0)\n        result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n      if (x & 0x8000000000000 > 0)\n        result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n      if (x & 0x4000000000000 > 0)\n        result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n      if (x & 0x2000000000000 > 0)\n        result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n      if (x & 0x1000000000000 > 0)\n        result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n      if (x & 0x800000000000 > 0)\n        result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n      if (x & 0x400000000000 > 0)\n        result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n      if (x & 0x200000000000 > 0)\n        result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n      if (x & 0x100000000000 > 0)\n        result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n      if (x & 0x80000000000 > 0)\n        result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n      if (x & 0x40000000000 > 0)\n        result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n      if (x & 0x20000000000 > 0)\n        result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n      if (x & 0x10000000000 > 0)\n        result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n      if (x & 0x8000000000 > 0)\n        result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n      if (x & 0x4000000000 > 0)\n        result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n      if (x & 0x2000000000 > 0)\n        result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n      if (x & 0x1000000000 > 0)\n        result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n      if (x & 0x800000000 > 0)\n        result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n      if (x & 0x400000000 > 0)\n        result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n      if (x & 0x200000000 > 0)\n        result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n      if (x & 0x100000000 > 0)\n        result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n      if (x & 0x80000000 > 0)\n        result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n      if (x & 0x40000000 > 0)\n        result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n      if (x & 0x20000000 > 0)\n        result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n      if (x & 0x10000000 > 0)\n        result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n      if (x & 0x8000000 > 0)\n        result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n      if (x & 0x4000000 > 0)\n        result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n      if (x & 0x2000000 > 0)\n        result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n      if (x & 0x1000000 > 0)\n        result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n      if (x & 0x800000 > 0)\n        result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n      if (x & 0x400000 > 0)\n        result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n      if (x & 0x200000 > 0)\n        result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n      if (x & 0x100000 > 0)\n        result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n      if (x & 0x80000 > 0)\n        result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n      if (x & 0x40000 > 0)\n        result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n      if (x & 0x20000 > 0)\n        result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n      if (x & 0x10000 > 0)\n        result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n      if (x & 0x8000 > 0)\n        result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n      if (x & 0x4000 > 0)\n        result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n      if (x & 0x2000 > 0)\n        result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n      if (x & 0x1000 > 0)\n        result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n      if (x & 0x800 > 0)\n        result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n      if (x & 0x400 > 0)\n        result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n      if (x & 0x200 > 0)\n        result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n      if (x & 0x100 > 0)\n        result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n      if (x & 0x80 > 0)\n        result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n      if (x & 0x40 > 0)\n        result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n      if (x & 0x20 > 0)\n        result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n      if (x & 0x10 > 0)\n        result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n      if (x & 0x8 > 0)\n        result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n      if (x & 0x4 > 0)\n        result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n      if (x & 0x2 > 0)\n        result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n      if (x & 0x1 > 0)\n        result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n      result >>= uint256 (int256 (63 - (x >> 64)));\n      require (result <= uint256 (int256 (MAX_64x64)));\n\n      return int128 (int256 (result));\n    }\n  }\n\n  /**\n   * Calculate natural exponent of x.  Revert on overflow.\n   *\n   * @param x signed 64.64-bit fixed point number\n   * @return signed 64.64-bit fixed point number\n   */\n  function exp (int128 x) internal pure returns (int128) {\n    unchecked {\n      require (x < 0x400000000000000000); // Overflow\n\n      if (x < -0x400000000000000000) return 0; // Underflow\n\n      return exp_2 (\n          int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n    }\n  }\n\n  /**\n   * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n   * integer numbers.  Revert on overflow or when y is zero.\n   *\n   * @param x unsigned 256-bit integer number\n   * @param y unsigned 256-bit integer number\n   * @return unsigned 64.64-bit fixed point number\n   */\n  function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n    unchecked {\n      require (y != 0);\n\n      uint256 result;\n\n      if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n        result = (x << 64) / y;\n      else {\n        uint256 msb = 192;\n        uint256 xc = x >> 192;\n        if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n        if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n        if (xc >= 0x100) { xc >>= 8; msb += 8; }\n        if (xc >= 0x10) { xc >>= 4; msb += 4; }\n        if (xc >= 0x4) { xc >>= 2; msb += 2; }\n        if (xc >= 0x2) msb += 1;  // No need to shift xc anymore\n\n        result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n        require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n        uint256 hi = result * (y >> 128);\n        uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n        uint256 xh = x >> 192;\n        uint256 xl = x << 64;\n\n        if (xl < lo) xh -= 1;\n        xl -= lo; // We rely on overflow behavior here\n        lo = hi << 128;\n        if (xl < lo) xh -= 1;\n        xl -= lo; // We rely on overflow behavior here\n\n        assert (xh == hi >> 128);\n\n        result += xl / y;\n      }\n\n      require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n      return uint128 (result);\n    }\n  }\n\n  /**\n   * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n   * number.\n   *\n   * @param x unsigned 256-bit integer number\n   * @return unsigned 128-bit integer number\n   */\n  function sqrtu (uint256 x) private pure returns (uint128) {\n    unchecked {\n      if (x == 0) return 0;\n      else {\n        uint256 xx = x;\n        uint256 r = 1;\n        if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n        if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n        if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n        if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n        if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n        if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n        if (xx >= 0x4) { r <<= 1; }\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1;\n        r = (r + x / r) >> 1; // Seven iterations should be enough\n        uint256 r1 = x / r;\n        return uint128 (r < r1 ? r : r1);\n      }\n    }\n  }\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/utils/introspection/ERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n    uint8 private constant _ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        // Inspired by OraclizeAPI's implementation - MIT licence\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n        if (value == 0) {\n            return \"0\";\n        }\n        uint256 temp = value;\n        uint256 digits;\n        while (temp != 0) {\n            digits++;\n            temp /= 10;\n        }\n        bytes memory buffer = new bytes(digits);\n        while (value != 0) {\n            digits -= 1;\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n            value /= 10;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        if (value == 0) {\n            return \"0x00\";\n        }\n        uint256 temp = value;\n        uint256 length = 0;\n        while (temp != 0) {\n            length++;\n            temp >>= 8;\n        }\n        return toHexString(value, length);\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = _HEX_SYMBOLS[value & 0xf];\n            value >>= 4;\n        }\n        require(value == 0, \"Strings: hex length insufficient\");\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Base64.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n    /**\n     * @dev Base64 Encoding/Decoding Table\n     */\n    string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64 `string` representation.\n     */\n    function encode(bytes memory data) internal pure returns (string memory) {\n        /**\n         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n         */\n        if (data.length == 0) return \"\";\n\n        // Loads the table into memory\n        string memory table = _TABLE;\n\n        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n        // and split into 4 numbers of 6 bits.\n        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n        // - `data.length + 2`  -> Round up\n        // - `/ 3`              -> Number of 3-bytes chunks\n        // - `4 *`              -> 4 characters for each chunk\n        string memory result = new string(4 * ((data.length + 2) / 3));\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Prepare the lookup table (skip the first \"length\" byte)\n            let tablePtr := add(table, 1)\n\n            // Prepare result pointer, jump over length\n            let resultPtr := add(result, 32)\n\n            // Run over the input, 3 bytes at a time\n            for {\n                let dataPtr := data\n                let endPtr := add(data, mload(data))\n            } lt(dataPtr, endPtr) {\n\n            } {\n                // Advance 3 bytes\n                dataPtr := add(dataPtr, 3)\n                let input := mload(dataPtr)\n\n                // To write each character, shift the 3 bytes (18 bits) chunk\n                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n                // and apply logical AND with 0x3F which is the number of\n                // the previous character in the ASCII table prior to the Base64 Table\n                // The result is then added to the table to get the character to write,\n                // and finally write it in the result pointer but with a left shift\n                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n            }\n\n            // When data `bytes` is not exactly 3 bytes long\n            // it is padded with `=` characters at the end\n            switch mod(mload(data), 3)\n            case 1 {\n                mstore8(sub(resultPtr, 1), 0x3d)\n                mstore8(sub(resultPtr, 2), 0x3d)\n            }\n            case 2 {\n                mstore8(sub(resultPtr, 1), 0x3d)\n            }\n        }\n\n        return result;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCall(target, data, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        require(isContract(target), \"Address: call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        require(isContract(target), \"Address: static call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(isContract(target), \"Address: delegate call to non-contract\");\n\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResult(success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            // Look for revert reason and bubble it up if present\n            if (returndata.length > 0) {\n                // The easiest way to bubble the revert reason is using memory via assembly\n                /// @solidity memory-safe-assembly\n                assembly {\n                    let returndata_size := mload(returndata)\n                    revert(add(32, returndata), returndata_size)\n                }\n            } else {\n                revert(errorMessage);\n            }\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/IERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes calldata data\n    ) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the caller.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool _approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC721/ERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n    using Address for address;\n    using Strings for uint256;\n\n    // Token name\n    string private _name;\n\n    // Token symbol\n    string private _symbol;\n\n    // Mapping from token ID to owner address\n    mapping(uint256 => address) private _owners;\n\n    // Mapping owner address to token count\n    mapping(address => uint256) private _balances;\n\n    // Mapping from token ID to approved address\n    mapping(uint256 => address) private _tokenApprovals;\n\n    // Mapping from owner to operator approvals\n    mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev See {IERC721-balanceOf}.\n     */\n    function balanceOf(address owner) public view virtual override returns (uint256) {\n        require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n        return _balances[owner];\n    }\n\n    /**\n     * @dev See {IERC721-ownerOf}.\n     */\n    function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n        address owner = _owners[tokenId];\n        require(owner != address(0), \"ERC721: invalid token ID\");\n        return owner;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-name}.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-symbol}.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev See {IERC721Metadata-tokenURI}.\n     */\n    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n        _requireMinted(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /**\n     * @dev See {IERC721-approve}.\n     */\n    function approve(address to, uint256 tokenId) public virtual override {\n        address owner = ERC721.ownerOf(tokenId);\n        require(to != owner, \"ERC721: approval to current owner\");\n\n        require(\n            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n            \"ERC721: approve caller is not token owner nor approved for all\"\n        );\n\n        _approve(to, tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-getApproved}.\n     */\n    function getApproved(uint256 tokenId) public view virtual override returns (address) {\n        _requireMinted(tokenId);\n\n        return _tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev See {IERC721-setApprovalForAll}.\n     */\n    function setApprovalForAll(address operator, bool approved) public virtual override {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /**\n     * @dev See {IERC721-isApprovedForAll}.\n     */\n    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n        return _operatorApprovals[owner][operator];\n    }\n\n    /**\n     * @dev See {IERC721-transferFrom}.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public virtual override {\n        //solhint-disable-next-line max-line-length\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n        _transfer(from, to, tokenId);\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) public virtual override {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev See {IERC721-safeTransferFrom}.\n     */\n    function safeTransferFrom(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) public virtual override {\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n        _safeTransfer(from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal virtual {\n        _transfer(from, to, tokenId);\n        require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n    }\n\n    /**\n     * @dev Returns whether `tokenId` exists.\n     *\n     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n     *\n     * Tokens start existing when they are minted (`_mint`),\n     * and stop existing when they are burned (`_burn`).\n     */\n    function _exists(uint256 tokenId) internal view virtual returns (bool) {\n        return _owners[tokenId] != address(0);\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `tokenId`.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n        address owner = ERC721.ownerOf(tokenId);\n        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Safely mints `tokenId` and transfers it to `to`.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal virtual {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal virtual {\n        _mint(to, tokenId);\n        require(\n            _checkOnERC721Received(address(0), to, tokenId, data),\n            \"ERC721: transfer to non ERC721Receiver implementer\"\n        );\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal virtual {\n        require(to != address(0), \"ERC721: mint to the zero address\");\n        require(!_exists(tokenId), \"ERC721: token already minted\");\n\n        _beforeTokenTransfer(address(0), to, tokenId);\n\n        _balances[to] += 1;\n        _owners[tokenId] = to;\n\n        emit Transfer(address(0), to, tokenId);\n\n        _afterTokenTransfer(address(0), to, tokenId);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal virtual {\n        address owner = ERC721.ownerOf(tokenId);\n\n        _beforeTokenTransfer(owner, address(0), tokenId);\n\n        // Clear approvals\n        _approve(address(0), tokenId);\n\n        _balances[owner] -= 1;\n        delete _owners[tokenId];\n\n        emit Transfer(owner, address(0), tokenId);\n\n        _afterTokenTransfer(owner, address(0), tokenId);\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual {\n        require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n        require(to != address(0), \"ERC721: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, tokenId);\n\n        // Clear approvals from the previous owner\n        _approve(address(0), tokenId);\n\n        _balances[from] -= 1;\n        _balances[to] += 1;\n        _owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        _afterTokenTransfer(from, to, tokenId);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * Emits an {Approval} event.\n     */\n    function _approve(address to, uint256 tokenId) internal virtual {\n        _tokenApprovals[tokenId] = to;\n        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(\n        address owner,\n        address operator,\n        bool approved\n    ) internal virtual {\n        require(owner != operator, \"ERC721: approve to caller\");\n        _operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` has not been minted yet.\n     */\n    function _requireMinted(uint256 tokenId) internal view virtual {\n        require(_exists(tokenId), \"ERC721: invalid token ID\");\n    }\n\n    /**\n     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n     * The call is not executed if the target address is not a contract.\n     *\n     * @param from address representing the previous owner of the given token ID\n     * @param to target address that will receive the tokens\n     * @param tokenId uint256 ID of the token to be transferred\n     * @param data bytes optional data to send along with the call\n     * @return bool whether the call correctly returned the expected magic value\n     */\n    function _checkOnERC721Received(\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) private returns (bool) {\n        if (to.isContract()) {\n            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n                return retval == IERC721Receiver.onERC721Received.selector;\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n                } else {\n                    /// @solidity memory-safe-assembly\n                    assembly {\n                        revert(add(32, reason), mload(reason))\n                    }\n                }\n            }\n        } else {\n            return true;\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any token transfer. This includes minting\n     * and burning.\n     *\n     * Calling conditions:\n     *\n     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n     * transferred to `to`.\n     * - When `from` is zero, `tokenId` will be minted for `to`.\n     * - When `to` is zero, ``from``'s `tokenId` will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 tokenId\n    ) internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts/token/ERC20/ERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * The default value of {decimals} is 18. To select a different value for\n     * {decimals} you should overload it.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the value {ERC20} uses, unless this function is\n     * overridden;\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n        }\n        _balances[to] += amount;\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        _balances[account] += amount;\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n        }\n        _totalSupply -= amount;\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(\n        address owner,\n        address spender,\n        uint256 amount\n    ) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(\n        address from,\n        address to,\n        uint256 amount\n    ) internal virtual {}\n}\n"
      },
      "@openzeppelin/contracts/interfaces/IERC2981.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n    /**\n     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n     */\n    function royaltyInfo(uint256 tokenId, uint256 salePrice)\n        external\n        view\n        returns (address receiver, uint256 royaltyAmount);\n}\n"
      },
      "@openzeppelin/contracts/interfaces/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
      },
      "@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n    event Staked(address indexed user, uint256 amount, uint256 term);\n\n    event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n    function stake(uint256 amount, uint256 term) external;\n\n    function withdraw() external;\n}\n"
      },
      "@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n    event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n    event MintClaimed(address indexed user, uint256 rewardAmount);\n\n    function claimRank(uint256 term) external;\n\n    function claimMintReward() external;\n}\n"
      },
      "@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n    function burn(address user, uint256 amount) external;\n}\n"
      },
      "@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n    event Redeemed(\n        address indexed user,\n        address indexed xenContract,\n        address indexed tokenContract,\n        uint256 xenAmount,\n        uint256 tokenAmount\n    );\n\n    function onTokenBurned(address user, uint256 amount) external;\n}\n"
      },
      "@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n    using Math for uint256;\n    using ABDKMath64x64 for int128;\n    using ABDKMath64x64 for uint256;\n\n    // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n    struct MintInfo {\n        address user;\n        uint256 term;\n        uint256 maturityTs;\n        uint256 rank;\n        uint256 amplifier;\n        uint256 eaaRate;\n    }\n\n    // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n    struct StakeInfo {\n        uint256 term;\n        uint256 maturityTs;\n        uint256 amount;\n        uint256 apy;\n    }\n\n    // PUBLIC CONSTANTS\n\n    uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n    uint256 public constant DAYS_IN_YEAR = 365;\n\n    uint256 public constant GENESIS_RANK = 1;\n\n    uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n    uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n    uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n    uint256 public constant TERM_AMPLIFIER = 15;\n    uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n    uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n    uint256 public constant REWARD_AMPLIFIER_END = 1;\n    uint256 public constant EAA_PM_START = 100;\n    uint256 public constant EAA_PM_STEP = 1;\n    uint256 public constant EAA_RANK_STEP = 100_000;\n    uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n    uint256 public constant MAX_PENALTY_PCT = 99;\n\n    uint256 public constant XEN_MIN_STAKE = 0;\n\n    uint256 public constant XEN_MIN_BURN = 0;\n\n    uint256 public constant XEN_APY_START = 20;\n    uint256 public constant XEN_APY_DAYS_STEP = 90;\n    uint256 public constant XEN_APY_END = 2;\n\n    string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n    // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n    uint256 public immutable genesisTs;\n    uint256 public globalRank = GENESIS_RANK;\n    uint256 public activeMinters;\n    uint256 public activeStakes;\n    uint256 public totalXenStaked;\n    // user address => XEN mint info\n    mapping(address => MintInfo) public userMints;\n    // user address => XEN stake info\n    mapping(address => StakeInfo) public userStakes;\n    // user address => XEN burn amount\n    mapping(address => uint256) public userBurns;\n\n    // CONSTRUCTOR\n    constructor() {\n        genesisTs = block.timestamp;\n    }\n\n    // PRIVATE METHODS\n\n    /**\n     * @dev calculates current MaxTerm based on Global Rank\n     *      (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n     */\n    function _calculateMaxTerm() private view returns (uint256) {\n        if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n            uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n            uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n            return Math.min(newMax, MAX_TERM_END);\n        }\n        return MAX_TERM_START;\n    }\n\n    /**\n     * @dev calculates Withdrawal Penalty depending on lateness\n     */\n    function _penalty(uint256 secsLate) private pure returns (uint256) {\n        // =MIN(2^(daysLate+3)/window-1,99)\n        uint256 daysLate = secsLate / SECONDS_IN_DAY;\n        if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n        uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n        return Math.min(penalty, MAX_PENALTY_PCT);\n    }\n\n    /**\n     * @dev calculates net Mint Reward (adjusted for Penalty)\n     */\n    function _calculateMintReward(\n        uint256 cRank,\n        uint256 term,\n        uint256 maturityTs,\n        uint256 amplifier,\n        uint256 eeaRate\n    ) private view returns (uint256) {\n        uint256 secsLate = block.timestamp - maturityTs;\n        uint256 penalty = _penalty(secsLate);\n        uint256 rankDelta = Math.max(globalRank - cRank, 2);\n        uint256 EAA = (1_000 + eeaRate);\n        uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n        return (reward * (100 - penalty)) / 100;\n    }\n\n    /**\n     * @dev cleans up User Mint storage (gets some Gas credit;))\n     */\n    function _cleanUpUserMint() private {\n        delete userMints[_msgSender()];\n        activeMinters--;\n    }\n\n    /**\n     * @dev calculates XEN Stake Reward\n     */\n    function _calculateStakeReward(\n        uint256 amount,\n        uint256 term,\n        uint256 maturityTs,\n        uint256 apy\n    ) private view returns (uint256) {\n        if (block.timestamp > maturityTs) {\n            uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n            return (amount * rate) / 100_000_000;\n        }\n        return 0;\n    }\n\n    /**\n     * @dev calculates Reward Amplifier\n     */\n    function _calculateRewardAmplifier() private view returns (uint256) {\n        uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n        if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n            return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n        } else {\n            return REWARD_AMPLIFIER_END;\n        }\n    }\n\n    /**\n     * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n     *      actual EAA is (1_000 + EAAR) / 1_000\n     */\n    function _calculateEAARate() private view returns (uint256) {\n        uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n        if (decrease > EAA_PM_START) return 0;\n        return EAA_PM_START - decrease;\n    }\n\n    /**\n     * @dev calculates APY (in %)\n     */\n    function _calculateAPY() private view returns (uint256) {\n        uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n        if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n        return XEN_APY_START - decrease;\n    }\n\n    /**\n     * @dev creates User Stake\n     */\n    function _createStake(uint256 amount, uint256 term) private {\n        userStakes[_msgSender()] = StakeInfo({\n            term: term,\n            maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n            amount: amount,\n            apy: _calculateAPY()\n        });\n        activeStakes++;\n        totalXenStaked += amount;\n    }\n\n    // PUBLIC CONVENIENCE GETTERS\n\n    /**\n     * @dev calculates gross Mint Reward\n     */\n    function getGrossReward(\n        uint256 rankDelta,\n        uint256 amplifier,\n        uint256 term,\n        uint256 eaa\n    ) public pure returns (uint256) {\n        int128 log128 = rankDelta.fromUInt().log_2();\n        int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n        return reward128.div(uint256(1_000).fromUInt()).toUInt();\n    }\n\n    /**\n     * @dev returns User Mint object associated with User account address\n     */\n    function getUserMint() external view returns (MintInfo memory) {\n        return userMints[_msgSender()];\n    }\n\n    /**\n     * @dev returns XEN Stake object associated with User account address\n     */\n    function getUserStake() external view returns (StakeInfo memory) {\n        return userStakes[_msgSender()];\n    }\n\n    /**\n     * @dev returns current AMP\n     */\n    function getCurrentAMP() external view returns (uint256) {\n        return _calculateRewardAmplifier();\n    }\n\n    /**\n     * @dev returns current EAA Rate\n     */\n    function getCurrentEAAR() external view returns (uint256) {\n        return _calculateEAARate();\n    }\n\n    /**\n     * @dev returns current APY\n     */\n    function getCurrentAPY() external view returns (uint256) {\n        return _calculateAPY();\n    }\n\n    /**\n     * @dev returns current MaxTerm\n     */\n    function getCurrentMaxTerm() external view returns (uint256) {\n        return _calculateMaxTerm();\n    }\n\n    // PUBLIC STATE-CHANGING METHODS\n\n    /**\n     * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n     */\n    function claimRank(uint256 term) external {\n        uint256 termSec = term * SECONDS_IN_DAY;\n        require(termSec > MIN_TERM, \"CRank: Term less than min\");\n        require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n        require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n        // create and store new MintInfo\n        MintInfo memory mintInfo = MintInfo({\n            user: _msgSender(),\n            term: term,\n            maturityTs: block.timestamp + termSec,\n            rank: globalRank,\n            amplifier: _calculateRewardAmplifier(),\n            eaaRate: _calculateEAARate()\n        });\n        userMints[_msgSender()] = mintInfo;\n        activeMinters++;\n        emit RankClaimed(_msgSender(), term, globalRank++);\n    }\n\n    /**\n     * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n     */\n    function claimMintReward() external {\n        MintInfo memory mintInfo = userMints[_msgSender()];\n        require(mintInfo.rank > 0, \"CRank: No mint exists\");\n        require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n        // calculate reward and mint tokens\n        uint256 rewardAmount = _calculateMintReward(\n            mintInfo.rank,\n            mintInfo.term,\n            mintInfo.maturityTs,\n            mintInfo.amplifier,\n            mintInfo.eaaRate\n        ) * 1 ether;\n        _mint(_msgSender(), rewardAmount);\n\n        _cleanUpUserMint();\n        emit MintClaimed(_msgSender(), rewardAmount);\n    }\n\n    /**\n     * @dev  ends minting upon maturity (and within permitted Withdrawal time Window)\n     *       mints XEN coins and splits them between User and designated other address\n     */\n    function claimMintRewardAndShare(address other, uint256 pct) external {\n        MintInfo memory mintInfo = userMints[_msgSender()];\n        require(other != address(0), \"CRank: Cannot share with zero address\");\n        require(pct > 0, \"CRank: Cannot share zero percent\");\n        require(pct < 101, \"CRank: Cannot share 100+ percent\");\n        require(mintInfo.rank > 0, \"CRank: No mint exists\");\n        require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n        // calculate reward\n        uint256 rewardAmount = _calculateMintReward(\n            mintInfo.rank,\n            mintInfo.term,\n            mintInfo.maturityTs,\n            mintInfo.amplifier,\n            mintInfo.eaaRate\n        ) * 1 ether;\n        uint256 sharedReward = (rewardAmount * pct) / 100;\n        uint256 ownReward = rewardAmount - sharedReward;\n\n        // mint reward tokens\n        _mint(_msgSender(), ownReward);\n        _mint(other, sharedReward);\n\n        _cleanUpUserMint();\n        emit MintClaimed(_msgSender(), rewardAmount);\n    }\n\n    /**\n     * @dev  ends minting upon maturity (and within permitted Withdrawal time Window)\n     *       mints XEN coins and stakes 'pct' of it for 'term'\n     */\n    function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n        MintInfo memory mintInfo = userMints[_msgSender()];\n        // require(pct > 0, \"CRank: Cannot share zero percent\");\n        require(pct < 101, \"CRank: Cannot share >100 percent\");\n        require(mintInfo.rank > 0, \"CRank: No mint exists\");\n        require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n        // calculate reward\n        uint256 rewardAmount = _calculateMintReward(\n            mintInfo.rank,\n            mintInfo.term,\n            mintInfo.maturityTs,\n            mintInfo.amplifier,\n            mintInfo.eaaRate\n        ) * 1 ether;\n        uint256 stakedReward = (rewardAmount * pct) / 100;\n        uint256 ownReward = rewardAmount - stakedReward;\n\n        // mint reward tokens part\n        _mint(_msgSender(), ownReward);\n        _cleanUpUserMint();\n        emit MintClaimed(_msgSender(), rewardAmount);\n\n        // nothing to burn since we haven't minted this part yet\n        // stake extra tokens part\n        require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n        require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n        require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n        require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n        _createStake(stakedReward, term);\n        emit Staked(_msgSender(), stakedReward, term);\n    }\n\n    /**\n     * @dev initiates XEN Stake in amount for a term (days)\n     */\n    function stake(uint256 amount, uint256 term) external {\n        require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n        require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n        require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n        require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n        require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n        // burn staked XEN\n        _burn(_msgSender(), amount);\n        // create XEN Stake\n        _createStake(amount, term);\n        emit Staked(_msgSender(), amount, term);\n    }\n\n    /**\n     * @dev ends XEN Stake and gets reward if the Stake is mature\n     */\n    function withdraw() external {\n        StakeInfo memory userStake = userStakes[_msgSender()];\n        require(userStake.amount > 0, \"XEN: no stake exists\");\n\n        uint256 xenReward = _calculateStakeReward(\n            userStake.amount,\n            userStake.term,\n            userStake.maturityTs,\n            userStake.apy\n        );\n        activeStakes--;\n        totalXenStaked -= userStake.amount;\n\n        // mint staked XEN (+ reward)\n        _mint(_msgSender(), userStake.amount + xenReward);\n        emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n        delete userStakes[_msgSender()];\n    }\n\n    /**\n     * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n     */\n    function burn(address user, uint256 amount) public {\n        require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n        require(\n            IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n            \"Burn: not a supported contract\"\n        );\n\n        _spendAllowance(user, _msgSender(), amount);\n        _burn(user, amount);\n        userBurns[user] += amount;\n        IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n    }\n}\n"
      },
      "@faircrypto/xen-crypto/contracts/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n    function min(uint256 a, uint256 b) external pure returns (uint256) {\n        if (a > b) return b;\n        return a;\n    }\n\n    function max(uint256 a, uint256 b) external pure returns (uint256) {\n        if (a > b) return a;\n        return b;\n    }\n\n    function logX64(uint256 x) external pure returns (int128) {\n        return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [],
      "optimizer": {
        "enabled": true,
        "runs": 20
      },
      "evmVersion": "london",
      "libraries": {
        "/contracts/libs/MintInfo.sol": {
          "MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
        },
        "/contracts/libs/Metadata.sol": {
          "Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
        }
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      }
    }
  }}