// File: src/deployer/SubscribeDeployer.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

import { ISubscribeDeployer } from "../interfaces/ISubscribeDeployer.sol";

import { DataTypes } from "../libraries/DataTypes.sol";

import { Subscribe } from "../core/Subscribe.sol";

contract SubscribeDeployer is ISubscribeDeployer {
    DataTypes.DeployParameters public override params;

    /// @inheritdoc ISubscribeDeployer
    function deploySubscribe(
        bytes32 salt,
        address engine
    ) external override returns (address addr) {
        params.engine = engine;
        addr = address(new Subscribe{ salt: salt }());
        delete params;
    }
}

// File: src/interfaces/ISubscribeDeployer.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

/**
 * @title ISubscribeDeployer
 * @author CyberConnect
 */
interface ISubscribeDeployer {
    /**
     * @notice Parameters when constructing a Content, Essence or W3ST.
     *
     * @return engine The engine address.
     */
    function params() external view returns (address engine);

    /**
     * @notice Deploy a new Subscribe
     *
     * @param salt The salt used to generate contract address in a deterministic way.
     * @param engine The CyberEngine address.
     *
     * @return addr The deployed Subscribe address.
     */
    function deploySubscribe(
        bytes32 salt,
        address engine
    ) external returns (address addr);
}

// File: src/libraries/DataTypes.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

library DataTypes {
    enum Category {
        Essence,
        Content,
        W3ST,
        Subscribe
    }

    enum ContentType {
        Content,
        Comment,
        Share
    }

    struct EIP712Signature {
        uint8 v;
        bytes32 r;
        bytes32 s;
        uint256 deadline;
    }

    struct RegisterEssenceParams {
        address account;
        string name;
        string symbol;
        string tokenURI;
        address mw;
        bool transferable;
    }

    struct RegisterSubscriptionParams {
        address account;
        string name;
        string symbol;
        string tokenURI;
        uint256 dayPerSub;
        uint256 pricePerSub;
        address recipient;
    }

    struct PublishContentParams {
        address account;
        string tokenURI;
        address mw;
        bool transferable;
    }

    struct ShareParams {
        address account;
        address accountShared;
        uint256 idShared;
    }

    struct InitParams {
        address soulAddr;
        address mwManagerAddr;
        address essImpl;
        address contentImpl;
        address w3stImpl;
        address subImpl;
        address adminAddr;
    }

    struct CommentParams {
        address account;
        string tokenURI;
        address mw;
        bool transferable;
        address accountCommented;
        uint256 idCommented;
    }

    struct IssueW3stParams {
        address account;
        string tokenURI;
        address mw;
        bool transferable;
    }

    struct EssenceStruct {
        address essence;
        address mw;
        string name;
        string symbol;
        string tokenURI;
        bool transferable;
    }

    struct SubscribeStruct {
        address subscribe;
        string name;
        string symbol;
        string tokenURI;
        uint256 dayPerSub;
        uint256 pricePerSub;
        address recipient;
    }

    struct AccountStruct {
        uint256 essenceCount;
        address w3st;
        uint256 w3stCount;
        address content;
        uint256 contentCount;
    }

    struct ContentStruct {
        address mw;
        string tokenURI;
        bool transferable;
        address srcAccount;
        uint256 srcId;
        ContentType contentType;
    }

    struct W3stStruct {
        address mw;
        string tokenURI;
        bool transferable;
    }

    struct CollectParams {
        address account;
        uint256 id;
        uint256 amount;
        address to;
        Category category;
    }

    struct MwParams {
        address account;
        Category category;
        uint256 id;
        uint256 amount;
        address from;
        address to;
        address referrerAccount;
        bytes data;
    }

    struct DeployParameters {
        address engine;
    }

    struct MetadataPair {
        string key;
        string value;
    }
}

// File: src/core/Subscribe.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

import { ISubscribe } from "../interfaces/ISubscribe.sol";
import { ICyberEngine } from "../interfaces/ICyberEngine.sol";
import { IDeployer } from "../interfaces/IDeployer.sol";

import { CyberNFT721 } from "../base/CyberNFT721.sol";
import { LibString } from "../libraries/LibString.sol";

/**
 * @title Subscribe NFT
 * @author CyberConnect
 * @notice This contract defines Subscribe NFT in CyberConnect Protocol.
 */
contract Subscribe is CyberNFT721, ISubscribe {
    /*//////////////////////////////////////////////////////////////
                                STATES
    //////////////////////////////////////////////////////////////*/

    address public immutable ENGINE;
    address internal _account;
    mapping(address => uint256) public ownedToken;
    mapping(uint256 => uint256) public expiries;

    /*//////////////////////////////////////////////////////////////
                                 CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor() {
        address engine = IDeployer(msg.sender).params();
        require(engine != address(0), "ZERO_ADDRESS");

        ENGINE = engine;
        _disableInitializers();
    }

    /*//////////////////////////////////////////////////////////////
                                 EXTERNAL
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc ISubscribe
    function mint(
        address to,
        uint256 durationDay
    ) external override returns (uint256) {
        require(msg.sender == ENGINE, "ONLY_ENGINE");
        require(durationDay >= 1, "MIN_DURATION_ONE_DAY");

        uint256 mintedId = super._mint(to);
        ownedToken[to] = mintedId;
        expiries[mintedId] = block.timestamp + durationDay * 1 days;

        return mintedId;
    }

    /// @inheritdoc ISubscribe
    function initialize(
        address account,
        string calldata name,
        string calldata symbol
    ) external override initializer {
        _account = account;
        super._initialize(name, symbol);
    }

    /// @inheritdoc ISubscribe
    function extend(
        address account,
        uint256 durationDay
    ) external override returns (uint256) {
        require(msg.sender == ENGINE, "ONLY_ENGINE");
        require(durationDay >= 1, "MIN_DURATION_ONE_DAY");

        uint256 curTime = block.timestamp;
        uint256 tokenId = ownedToken[account];

        // not expired
        if (curTime < expiries[tokenId]) {
            expiries[tokenId] += durationDay * 1 days;
        } else {
            expiries[tokenId] = curTime + durationDay * 1 days;
        }

        return tokenId;
    }

    /*//////////////////////////////////////////////////////////////
                                 PUBLIC
    //////////////////////////////////////////////////////////////*/

    /**
     * @notice Disallows the transfer of the essence nft.
     */
    function transferFrom(address, address, uint256) public pure override {
        revert("TRANSFER_NOT_ALLOWED");
    }

    /// ERC721
    function ownerOf(uint256 tokenId) public view override returns (address) {
        uint256 expiryTs = expiries[tokenId];
        if (expiryTs != 0) {
            require(block.timestamp < expiryTs, "EXPIRED");
        }

        return super.ownerOf(tokenId);
    }

    /*//////////////////////////////////////////////////////////////
                            PUBLIC VIEW
    //////////////////////////////////////////////////////////////*/

    /// ERC721
    function tokenURI(
        uint256 tokenId
    ) public view virtual override returns (string memory) {
        _requireMinted(tokenId);
        string memory uri = ICyberEngine(ENGINE).getSubscriptionTokenURI(
            _account
        );
        return string(abi.encodePacked(uri, LibString.toString(tokenId)));
    }
}

// File: src/interfaces/ISubscribe.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

/**
 * @title ISubscribe
 * @author CyberConnect
 */
interface ISubscribe {
    /**
     * @notice Mints the Subscribe.
     *
     * @param to The recipient address.
     * @param to The duration with unit Day.
     * @return uint256 The token id.
     */
    function mint(address to, uint256 durationDay) external returns (uint256);

    /**
     * @notice Initializes the Subscribe NFT.
     *
     * @param account The account address for the Subscribe NFT.
     * @param name The name for the Subscribe NFT.
     * @param symbol The symbol for the Subscribe NFT.
     */
    function initialize(
        address account,
        string calldata name,
        string calldata symbol
    ) external;

    /**
     * @notice Extends the Subscribe NFT.
     *
     * @param account The account address for the Subscribe NFT.
     * @param durationDay The duration with unit Day.
     * @return uint256 The token id.
     */
    function extend(
        address account,
        uint256 durationDay
    ) external returns (uint256);
}

// File: src/interfaces/ICyberEngine.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

import { ICyberEngineEvents } from "./ICyberEngineEvents.sol";

import { DataTypes } from "../libraries/DataTypes.sol";

/**
 * @title ICyberEngine
 * @author CyberConnect
 */
interface ICyberEngine is ICyberEngineEvents {
    /**
     * @notice Initialize the CyberEngine.
     *
     * @param params The params for init.
     */
    function initialize(DataTypes.InitParams calldata params) external;

    /**
     * @notice Collect an CyberAccount's essence, content or w3st.
     *
     * @param params The params for collect.
     * @param data The collect data for pre process.
     * @return uint256 The collected nft id.
     */
    function collect(
        DataTypes.CollectParams calldata params,
        bytes calldata data
    ) external returns (uint256);

    /**
     * @notice Subscribe to a CyberAccount.
     *
     * @param account The account to subscribe.
     * @param to The address that will receive the subscription.
     * @return uint256 The new token id.
     */
    function subscribe(
        address account,
        address to
    ) external payable returns (uint256);

    /**
     * @notice Register an essence.
     *
     * @param params The params for registration.
     * @param initData The registration initial data.
     * @return uint256 The new essence count.
     */
    function registerEssence(
        DataTypes.RegisterEssenceParams calldata params,
        bytes calldata initData
    ) external returns (uint256);

    /**
     * @notice Register subscription.
     *
     * @param params The params for registration.
     */
    function registerSubscription(
        DataTypes.RegisterSubscriptionParams calldata params
    ) external;

    /**
     * @notice Set subscription data.
     *
     * @param account The account to set.
     * @param uri The uri to set.
     * @param recipient The recipient to set.
     * @param pricePerSub The price per subscription to set.
     * @param dayPerSub The day per subscription to set.
     */
    function setSubscriptionData(
        address account,
        string calldata uri,
        address recipient,
        uint256 pricePerSub,
        uint256 dayPerSub
    ) external;

    /**
     * @notice Publish a content.
     *
     * @param params The params for publishing content.
     * @param initData The registration initial data.
     * @return uint256 The new token id.
     */
    function publishContent(
        DataTypes.PublishContentParams calldata params,
        bytes calldata initData
    ) external returns (uint256);

    /**
     * @notice Share a content, comment or another share.
     *
     * @param params The params for sharing.
     * @return uint256 The new token id.
     */
    function share(
        DataTypes.ShareParams calldata params
    ) external returns (uint256);

    /**
     * @notice Comment a content, comment or share.
     *
     * @param params The params for commenting content.
     * @param initData The registration initial data.
     * @return uint256 The new token id.
     */
    function comment(
        DataTypes.CommentParams calldata params,
        bytes calldata initData
    ) external returns (uint256);

    /**
     * @notice Issue a w3st.
     *
     * @param params The params for issuing w3st.
     * @param initData The registration initial data.
     * @return uint256 The new token id.
     */
    function issueW3st(
        DataTypes.IssueW3stParams calldata params,
        bytes calldata initData
    ) external returns (uint256);

    /**
     * @notice Gets the Essence NFT token URI.
     *
     * @param account The account address.
     * @param essenceId The Essence ID.
     * @return string The Essence NFT token URI.
     */
    function getEssenceTokenURI(
        address account,
        uint256 essenceId
    ) external view returns (string memory);

    /**
     * @notice Gets the Essence NFT transferability.
     *
     * @param account The account address.
     * @param essenceId The Essence ID.
     */
    function getEssenceTransferability(
        address account,
        uint256 essenceId
    ) external view returns (bool);

    /**
     * @notice Sets essence data.
     *
     * @param account The account address.
     * @param essenceId The essence ID.
     * @param tokenURI The new token URI.
     * @param mw The new middleware to be set.
     * @param data The data for middleware.
     */
    function setEssenceData(
        address account,
        uint256 essenceId,
        string calldata tokenURI,
        address mw,
        bytes calldata data
    ) external;

    /**
     * @notice Gets the Essence NFT address.
     *
     * @param account The account address.
     * @param essenceId The Essence ID.
     * @return address The Essence NFT address.
     */
    function getEssenceAddr(
        address account,
        uint256 essenceId
    ) external view returns (address);

    /**
     * @notice Gets the Essence NFT middleware.
     *
     * @param account The account address.
     * @param essenceId The Essence ID.
     * @return address The Essence NFT middleware.
     */
    function getEssenceMw(
        address account,
        uint256 essenceId
    ) external view returns (address);

    /**
     * @notice Gets how many Essence NFTs the account registered.
     *
     * @param account The account address.
     * @return uint256 The Essence NFT count.
     */
    function getEssenceCount(address account) external view returns (uint256);

    /**
     * @notice Sets content data.
     *
     * @param account The account address.
     * @param tokenId The content tokenId.
     * @param tokenURI The new token URI.
     * @param mw The new middleware to be set.
     * @param data The data for middleware.
     */
    function setContentData(
        address account,
        uint256 tokenId,
        string calldata tokenURI,
        address mw,
        bytes calldata data
    ) external;

    /**
     * @notice Sets w3st data.
     *
     * @param account The account address.
     * @param tokenId The w3st tokenId.
     * @param tokenURI The new token URI.
     * @param mw The new middleware to be set.
     * @param data The data for middleware.
     */
    function setW3stData(
        address account,
        uint256 tokenId,
        string calldata tokenURI,
        address mw,
        bytes calldata data
    ) external;

    /**
     * @notice Gets the Content NFT token URI.
     *
     * @param account The account address.
     * @param tokenId The Content NFT ID.
     * @return string The Content NFT token URI.
     */
    function getContentTokenURI(
        address account,
        uint256 tokenId
    ) external view returns (string memory);

    /**
     * @notice Gets the Content NFT address.
     *
     * @param account The account address.
     * @return address The Content NFT address.
     */
    function getContentAddr(address account) external view returns (address);

    /**
     * @notice Gets the Content NFT transferability.
     *
     * @param account The account address.
     * @param tokenId The Content NFT ID.
     */
    function getContentTransferability(
        address account,
        uint256 tokenId
    ) external view returns (bool);

    /**
     * @notice Gets the Content source info.
     *
     * @param account The account address.
     * @param tokenId The Content NFT ID.
     * @return address The source content owner.
     * @return uint256 The source content token ID.
     */
    function getContentSrcInfo(
        address account,
        uint256 tokenId
    ) external view returns (address, uint256);

    /**
     * @notice Gets the Content NFT middleware.
     *
     * @param account The account address.
     * @param tokenId The Content NFT ID.
     * @return address The Content NFT middleware.
     */
    function getContentMw(
        address account,
        uint256 tokenId
    ) external view returns (address);

    /**
     * @notice Gets how many Content NFTs the account registered.
     *
     * @param account The account address.
     * @return uint256 The Content NFT count.
     */
    function getContentCount(address account) external view returns (uint256);

    /**
     * @notice Gets the w3st NFT token URI.
     *
     * @param account The account address.
     * @param tokenId The w3st NFT ID.
     * @return string The w3st NFT token URI.
     */
    function getW3stTokenURI(
        address account,
        uint256 tokenId
    ) external view returns (string memory);

    /**
     * @notice Gets the w3st NFT address.
     *
     * @param account The account address.
     * @return address The w3st NFT address.
     */
    function getW3stAddr(address account) external view returns (address);

    /**
     * @notice Gets the w3st NFT transferability.
     *
     * @param account The account address.
     * @param tokenId The w3st NFT ID.
     */
    function getW3stTransferability(
        address account,
        uint256 tokenId
    ) external view returns (bool);

    /**
     * @notice Gets the w3st NFT middleware.
     *
     * @param account The account address.
     * @param tokenId The w3st NFT ID.
     * @return address The w3st NFT middleware.
     */
    function getW3stMw(
        address account,
        uint256 tokenId
    ) external view returns (address);

    /**
     * @notice Gets how many w3st NFTs the account registered.
     *
     * @param account The account address.
     * @return uint256 The w3st NFT count.
     */
    function getW3stCount(address account) external view returns (uint256);

    /**
     * @notice Gets if the account approved the operator to publish/set Content, Comment, Share, W3st, Subscription in the protocol.
     * @param account The account address.
     * @param operator The operator address.
     */
    function getOperatorApproval(
        address account,
        address operator
    ) external view returns (bool);

    /**
     * @notice Sets if the account approves the operator to publish/set Content, Comment, Share, W3st, Subscription in the protocol.
     * @param operator The operator address.
     * @param approved The approval status.
     */
    function setOperatorApproval(address operator, bool approved) external;

    /**
     * @notice Gets the Subscribe NFT token URI.
     *
     * @param account The account address.
     */
    function getSubscriptionTokenURI(
        address account
    ) external view returns (string memory);

    /**
     * @notice Gets the Subscription recipient address.
     *
     * @param account The account address.
     * @return address The Subscription recipient address.
     */
    function getSubscriptionRecipient(
        address account
    ) external view returns (address);

    /**
     * @notice Gets the Subscription price per subscription.
     *
     * @param account The account address.
     * @return uint256 The Subscription price per subscription.
     */
    function getSubscriptionPricePerSub(
        address account
    ) external view returns (uint256);

    /**
     * @notice Gets the Subscription day per subscription.
     *
     * @param account The account address.
     * @return uint256 The Subscription day per subscription.
     */
    function getSubscriptionDayPerSub(
        address account
    ) external view returns (uint256);

    /**
     * @notice Gets the Subscribe NFT address.
     *
     * @param account The account address.
     * @return address The Subscribe NFT address.
     */
    function getSubscriptionAddr(
        address account
    ) external view returns (address);

    /**
     * @notice Contract version number.
     *
     * @return uint256 The version number.
     */
    function version() external pure returns (uint256);
}

// File: src/interfaces/IDeployer.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

/**
 * @title IDeployer
 * @author CyberConnect
 */
interface IDeployer {
    /**
     * @notice Parameters when constructing a Content, Essence or W3ST.
     *
     * @return engine The engine address.
     */
    function params() external view returns (address engine);

    /**
     * @notice Deploy a new Essence.
     *
     * @param salt The salt used to generate contract address in a deterministic way.
     * @param engine The CyberEngine address.
     *
     * @return addr The deployed essence address.
     */
    function deployEssence(
        bytes32 salt,
        address engine
    ) external returns (address addr);

    /**
     * @notice Deploy a new Content
     *
     * @param salt The salt used to generate contract address in a deterministic way.
     * @param engine The CyberEngine address.
     *
     * @return addr The deployed content address.
     */
    function deployContent(
        bytes32 salt,
        address engine
    ) external returns (address addr);

    /**
     * @notice Deploy a new W3ST
     *
     * @param salt The salt used to generate contract address in a deterministic way.
     * @param engine The CyberEngine address.
     *
     * @return addr The deployed W3ST address.
     */
    function deployW3st(
        bytes32 salt,
        address engine
    ) external returns (address addr);
}

// File: src/base/CyberNFT721.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

import { ERC721 } from "../dependencies/solmate/ERC721.sol";
import { Initializable } from "openzeppelin-contracts/contracts/proxy/utils/Initializable.sol";

import { ICyberNFT721 } from "../interfaces/ICyberNFT721.sol";

/**
 * @title Cyber 721 NFT Base
 * @author CyberConnect
 * @notice This contract is the base for all 721 NFT contracts.
 */
abstract contract CyberNFT721 is ERC721, ICyberNFT721 {
    /*//////////////////////////////////////////////////////////////
                                STATES
    //////////////////////////////////////////////////////////////*/
    uint256 internal _currentIndex;
    uint256 internal _totalSupply;

    /*//////////////////////////////////////////////////////////////
                                 CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor() {
        _disableInitializers();
    }

    /*//////////////////////////////////////////////////////////////
                         EXTERNAL VIEW
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc ICyberNFT721
    function totalSupply() external view virtual override returns (uint256) {
        return _totalSupply;
    }

    /*//////////////////////////////////////////////////////////////
                                 PUBLIC
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc ICyberNFT721
    function burn(uint256 tokenId) public virtual override {
        address owner = ownerOf(tokenId);
        require(
            msg.sender == owner ||
                msg.sender == getApproved[tokenId] ||
                isApprovedForAll[owner][msg.sender],
            "NOT_OWNER_OR_APPROVED"
        );
        super._burn(tokenId);
        _totalSupply--;
    }

    /*//////////////////////////////////////////////////////////////
                              INTERNAL
    //////////////////////////////////////////////////////////////*/

    function _initialize(
        string calldata name,
        string calldata symbol
    ) internal onlyInitializing {
        ERC721.__ERC721_Init(name, symbol);
    }

    function _mint(address _to) internal virtual returns (uint256) {
        uint256 mintedId = _currentIndex;
        super._safeMint(_to, mintedId);

        _currentIndex++;
        _totalSupply++;

        return mintedId;
    }

    function _exists(uint256 tokenId) internal view returns (bool) {
        return _ownerOf[tokenId] != address(0);
    }

    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "NOT_MINTED");
    }
}

// File: src/libraries/LibString.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.8.0;

// adapted from 721A contracts
library LibString {
    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory ptr) {
        assembly {
            // The maximum value of a uint256 contains 78 digits (1 byte per digit),
            // but we allocate 128 bytes to keep the free memory pointer 32-byte word aliged.
            // We will need 1 32-byte word to store the length,
            // and 3 32-byte words to store a maximum of 78 digits. Total: 32 + 3 * 32 = 128.
            ptr := add(mload(0x40), 128)
            // Update the free memory pointer to allocate.
            mstore(0x40, ptr)
            // Cache the end of the memory to calculate the length later.
            let end := ptr
            // We write the string from the rightmost digit to the leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            // Costs a bit more than early returning for the zero case,
            // but cheaper in terms of deployment and overall runtime costs.
            for {
                // Initialize and perform the first pass without check.
                let temp := value
                // Move the pointer 1 byte leftwards to point to an empty character slot.
                ptr := sub(ptr, 1)
                // Write the character to the pointer. 48 is the ASCII index of '0'.
                mstore8(ptr, add(48, mod(temp, 10)))
                temp := div(temp, 10)
            } temp {
                // Keep dividing `temp` until zero.
                temp := div(temp, 10)
            } {
                // Body of the for loop.
                ptr := sub(ptr, 1)
                mstore8(ptr, add(48, mod(temp, 10)))
            }
            let length := sub(end, ptr)
            // Move the pointer 32 bytes leftwards to make room for the length.
            ptr := sub(ptr, 32)
            // Store the length.
            mstore(ptr, length)
        }
    }

    function toHexString(
        uint256 value,
        uint256 length
    ) internal pure returns (string memory str) {
        assembly {
            let start := mload(0x40)
            // We need length * 2 bytes for the digits, 2 bytes for the prefix,
            // and 32 bytes for the length. We add 32 to the total and round down
            // to a multiple of 32. (32 + 2 + 32) = 66.
            str := add(start, and(add(shl(1, length), 66), not(31)))

            // Cache the end to calculate the length later.
            let end := str

            // Allocate the memory.
            mstore(0x40, str)

            let temp := value
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for {
                // Initialize and perform the first pass without check.
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
                length := sub(length, 1)
            } length {
                length := sub(length, 1)
            } {
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
            }

            if temp {
                mstore(0x00, "\x08\xc3\x79\xa0") // Function selector of the error method.
                mstore(0x04, 0x20) // Offset of the error string.
                mstore(0x24, 23) // Length of the error string.
                mstore(0x44, "HEX_LENGTH_INSUFFICIENT") // The error string.
                revert(0x00, 0x64) // Revert with (offset, size).
            }

            // Compute the string's length.
            let strLength := add(sub(end, str), 2)
            // Move the pointer and write the "0x" prefix.
            str := sub(str, 32)
            mstore(str, 0x3078)
            // Move the pointer and write the length.
            str := sub(str, 2)
            mstore(str, strLength)
        }
    }

    function toHexString(
        uint256 value
    ) internal pure returns (string memory str) {
        assembly {
            let start := mload(0x40)
            // We need 32 bytes for the length, 2 bytes for the prefix,
            // and 64 bytes for the digits.
            // The next multiple of 32 above (32 + 2 + 64) is 128.
            str := add(start, 128)

            // Cache the end to calculate the length later.
            let end := str

            // Allocate the memory.
            mstore(0x40, str)

            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for {
                // Initialize and perform the first pass without check.
                let temp := value
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
            } temp {
                // prettier-ignore
            } {
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
            }

            // Compute the string's length.
            let strLength := add(sub(end, str), 2)
            // Move the pointer and write the "0x" prefix.
            str := sub(str, 32)
            mstore(str, 0x3078)
            // Move the pointer and write the length.
            str := sub(str, 2)
            mstore(str, strLength)
        }
    }

    function toHexString(
        address value
    ) internal pure returns (string memory str) {
        assembly {
            let start := mload(0x40)
            // We need 32 bytes for the length, 2 bytes for the prefix,
            // and 40 bytes for the digits.
            // The next multiple of 32 above (32 + 2 + 40) is 96.
            str := add(start, 96)

            // Allocate the memory.
            mstore(0x40, str)

            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for {
                // Initialize and perform the first pass without check.
                let length := 20
                let temp := value
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
                length := sub(length, 1)
            } length {
                length := sub(length, 1)
            } {
                str := sub(str, 2)
                mstore8(add(str, 1), byte(and(temp, 15), "0123456789abcdef"))
                mstore8(str, byte(and(shr(4, temp), 15), "0123456789abcdef"))
                temp := shr(8, temp)
            }

            // Move the pointer and write the "0x" prefix.
            str := sub(str, 32)
            mstore(str, 0x3078)
            // Move the pointer and write the length.
            str := sub(str, 2)
            mstore(str, 42)
        }
    }

    function toLower(string memory str) internal pure returns (string memory) {
        bytes memory bStr = bytes(str);
        bytes memory bLower = new bytes(bStr.length);
        for (uint256 i = 0; i < bStr.length; i++) {
            if ((bStr[i] >= "A") && (bStr[i] <= "Z")) {
                bLower[i] = bytes1(uint8(bStr[i]) + 32);
            } else {
                bLower[i] = bStr[i];
            }
        }
        return string(bLower);
    }

    function toUpper(string memory str) internal pure returns (string memory) {
        bytes memory bStr = bytes(str);
        bytes memory bLower = new bytes(bStr.length);
        for (uint256 i = 0; i < bStr.length; i++) {
            if ((bStr[i] >= "a") && (bStr[i] <= "z")) {
                bLower[i] = bytes1(uint8(bStr[i]) - 32);
            } else {
                bLower[i] = bStr[i];
            }
        }
        return string(bLower);
    }
}

// File: src/interfaces/ICyberEngineEvents.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

import { DataTypes } from "../libraries/DataTypes.sol";

/**
 * @title ICyberEngineEvents
 * @author CyberConnect
 */
interface ICyberEngineEvents {
    /**
     * @notice Emitted when a CyberEngine has been created.
     *
     * @param soul The soul contract address.
     * @param mwManager The middleware contract address.
     * @param essImpl The essence impl address.
     * @param contentImpl The content impl address.
     * @param w3stImpl The w3st impl address.
     * @param subImpl The sub impl address.
     * @param admin The admin address to upgrade the contract.
     */
    event Initialize(
        address soul,
        address mwManager,
        address essImpl,
        address contentImpl,
        address w3stImpl,
        address subImpl,
        address indexed admin
    );

    /**
     * @notice Emitted when a new essence has been created.
     *
     * @param account The account address.
     * @param essenceId The essence id.
     * @param name The essence name.
     * @param symbol The essence symbol.
     * @param tokenURI the essence tokenURI.
     * @param transferable The transferable flag.
     * @param essence the deployed EssenceNFT address.
     * @param mw The middleware.
     */
    event RegisterEssence(
        address indexed account,
        uint256 indexed essenceId,
        string name,
        string symbol,
        string tokenURI,
        bool transferable,
        address mw,
        address essence
    );

    /**
     * @notice Emitted when a new Subscription has been registered.
     *
     * @param account The account address.
     * @param name The subscription name.
     * @param symbol The subscription symbol.
     * @param tokenURI the subscription tokenURI.
     * @param pricePerSub The price per subscription.
     * @param dayPerSub The day per subscription.
     * @param recipient The recipient address.
     * @param subscribe The subscribe NFT contract address.
     */
    event RegisterSubscription(
        address indexed account,
        string name,
        string symbol,
        string tokenURI,
        uint256 pricePerSub,
        uint256 dayPerSub,
        address recipient,
        address subscribe
    );

    /**
     * @notice Emitted when a new content has been created.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param tokenURI the content tokenURI.
     * @param transferable The transferable flag.
     * @param mw The middleware.
     * @param content the deployed ContentNFT address.
     */
    event PublishContent(
        address indexed account,
        uint256 indexed tokenId,
        string tokenURI,
        bool transferable,
        address mw,
        address content
    );

    /**
     * @notice Emitted when a new comment has been created.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param tokenURI the content tokenURI.
     * @param transferable The transferable flag.
     * @param content the deployed ContentNFT address.
     * @param mw The middleware.
     * @param accountCommented The commented account address.
     * @param idCommented The commented token id.
     */
    event Comment(
        address indexed account,
        uint256 indexed tokenId,
        string tokenURI,
        bool transferable,
        address mw,
        address content,
        address accountCommented,
        uint256 idCommented
    );

    /**
     * @notice Emitted when a new share has been created.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param srcAccount the src account to share.
     * @param srcId the src id to share
     */
    event Share(
        address indexed account,
        uint256 indexed tokenId,
        address srcAccount,
        uint256 srcId
    );

    /**
     * @notice Emitted when a new w3st has been created.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param tokenURI the content tokenURI.
     * @param transferable The transferable flag.
     * @param w3st the deployed W3ST address.
     * @param mw The middleware.
     */
    event IssueW3st(
        address indexed account,
        uint256 indexed tokenId,
        string tokenURI,
        bool transferable,
        address mw,
        address w3st
    );

    /**
     * @notice Emitted when an essence has been collected.
     *
     * @param to The address that will receive the NFT.
     * @param from The address pays related fees.
     * @param account The account addresss.
     * @param id The id.
     * @param amount The amount to collect.
     * @param newTokenId The token id of the newly minted NFT (only for collecting Essence).
     * @param category The category to collect.
     */
    event Collect(
        address indexed to,
        address from,
        address indexed account,
        uint256 indexed id,
        uint256 amount,
        uint256 newTokenId,
        DataTypes.Category category
    );

    /**
     * @notice Emitted when essence data has been set to an account.
     *
     * @param account The account address.
     * @param essenceId The essence id.
     * @param tokenURI The new token URI.
     * @param mw The new middleware.
     */
    event SetEssenceData(
        address indexed account,
        uint256 indexed essenceId,
        string tokenURI,
        address mw
    );

    /**
     * @notice Emitted when content data has been set to an account.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param tokenURI The new token URI.
     * @param mw The new middleware.
     */
    event SetContentData(
        address indexed account,
        uint256 indexed tokenId,
        string tokenURI,
        address mw
    );

    /**
     * @notice Emitted when w3st data has been set to an account.
     *
     * @param account The account address.
     * @param tokenId The token id.
     * @param tokenURI The new token URI.
     * @param mw The new middleware.
     */
    event SetW3stData(
        address indexed account,
        uint256 indexed tokenId,
        string tokenURI,
        address mw
    );

    /**
     * @notice Emitted when subscription data has been set to an account.
     *
     * @param account The account address.
     * @param tokenURI The new token URI.
     * @param recipient The new recipient address.
     * @param pricePerSub The new price per subscription.
     * @param dayPerSub The new day per subscription.
     */
    event SetSubscriptionData(
        address indexed account,
        string tokenURI,
        address recipient,
        uint256 pricePerSub,
        uint256 dayPerSub
    );

    /**
     * @notice Emitted when a new operator has been approved.
     *
     * @param account The account address.
     * @param operator The operator address.
     * @param approved The approval status.
     */
    event SetOperatorApproval(
        address indexed account,
        address indexed operator,
        bool prevApproved,
        bool approved
    );
}

// File: src/dependencies/solmate/ERC721.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.8.0;

import { Initializable } from "openzeppelin-contracts/contracts/proxy/utils/Initializable.sol";

/// @notice Adapted from Solmate's ERC721.sol with initializer replacing the constructor.

/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721 is Initializable {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(
        address indexed from,
        address indexed to,
        uint256 indexed id
    );

    event Approval(
        address indexed owner,
        address indexed spender,
        uint256 indexed id
    );

    event ApprovalForAll(
        address indexed owner,
        address indexed operator,
        bool approved
    );

    /*//////////////////////////////////////////////////////////////
                         METADATA STORAGE/LOGIC
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    function tokenURI(uint256 id) public view virtual returns (string memory);

    /*//////////////////////////////////////////////////////////////
                      ERC721 BALANCE/OWNER STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) internal _ownerOf;

    mapping(address => uint256) internal _balanceOf;

    function ownerOf(uint256 id) public view virtual returns (address owner) {
        require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
    }

    function balanceOf(address owner) public view virtual returns (uint256) {
        require(owner != address(0), "ZERO_ADDRESS");

        return _balanceOf[owner];
    }

    /*//////////////////////////////////////////////////////////////
                         ERC721 APPROVAL STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) public getApproved;

    mapping(address => mapping(address => bool)) public isApprovedForAll;

    /*//////////////////////////////////////////////////////////////
                               INIT
    //////////////////////////////////////////////////////////////*/

    function __ERC721_Init(
        string calldata _name,
        string calldata _symbol
    ) internal {
        name = _name;
        symbol = _symbol;
    }

    /*//////////////////////////////////////////////////////////////
                              ERC721 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 id) public virtual {
        address owner = _ownerOf[id];

        require(
            msg.sender == owner || isApprovedForAll[owner][msg.sender],
            "NOT_AUTHORIZED"
        );

        getApproved[id] = spender;

        emit Approval(owner, spender, id);
    }

    function setApprovalForAll(address operator, bool approved) public virtual {
        isApprovedForAll[msg.sender][operator] = approved;

        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function transferFrom(address from, address to, uint256 id) public virtual {
        require(from == _ownerOf[id], "WRONG_FROM");

        require(to != address(0), "INVALID_RECIPIENT");

        require(
            msg.sender == from ||
                isApprovedForAll[from][msg.sender] ||
                msg.sender == getApproved[id],
            "NOT_AUTHORIZED"
        );

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        unchecked {
            _balanceOf[from]--;

            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        delete getApproved[id];

        emit Transfer(from, to, id);
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        transferFrom(from, to, id);

        if (to.code.length != 0)
            require(
                ERC721TokenReceiver(to).onERC721Received(
                    msg.sender,
                    from,
                    id,
                    ""
                ) == ERC721TokenReceiver.onERC721Received.selector,
                "UNSAFE_RECIPIENT"
            );
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        bytes calldata data
    ) public virtual {
        transferFrom(from, to, id);

        if (to.code.length != 0)
            require(
                ERC721TokenReceiver(to).onERC721Received(
                    msg.sender,
                    from,
                    id,
                    data
                ) == ERC721TokenReceiver.onERC721Received.selector,
                "UNSAFE_RECIPIENT"
            );
    }

    /*//////////////////////////////////////////////////////////////
                              ERC165 LOGIC
    //////////////////////////////////////////////////////////////*/

    function supportsInterface(
        bytes4 interfaceId
    ) public view virtual returns (bool) {
        return
            interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
            interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
            interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 id) internal virtual {
        require(to != address(0), "INVALID_RECIPIENT");

        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        // Counter overflow is incredibly unrealistic.
        unchecked {
            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        emit Transfer(address(0), to, id);
    }

    function _burn(uint256 id) internal virtual {
        address owner = _ownerOf[id];

        require(owner != address(0), "NOT_MINTED");

        // Ownership check above ensures no underflow.
        unchecked {
            _balanceOf[owner]--;
        }

        delete _ownerOf[id];

        delete getApproved[id];

        emit Transfer(owner, address(0), id);
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL SAFE MINT LOGIC
    //////////////////////////////////////////////////////////////*/

    function _safeMint(address to, uint256 id) internal virtual {
        _mint(to, id);

        if (to.code.length != 0)
            require(
                ERC721TokenReceiver(to).onERC721Received(
                    msg.sender,
                    address(0),
                    id,
                    ""
                ) == ERC721TokenReceiver.onERC721Received.selector,
                "UNSAFE_RECIPIENT"
            );
    }

    function _safeMint(
        address to,
        uint256 id,
        bytes memory data
    ) internal virtual {
        _mint(to, id);

        if (to.code.length != 0)
            require(
                ERC721TokenReceiver(to).onERC721Received(
                    msg.sender,
                    address(0),
                    id,
                    data
                ) == ERC721TokenReceiver.onERC721Received.selector,
                "UNSAFE_RECIPIENT"
            );
    }
}

/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721TokenReceiver {
    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external virtual returns (bytes4) {
        return ERC721TokenReceiver.onERC721Received.selector;
    }
}

// File: lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol



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

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

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

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

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

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

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

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

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

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

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

// File: src/interfaces/ICyberNFT721.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity 0.8.14;

/**
 * @title ICyberNFT721
 * @author CyberConnect
 */
interface ICyberNFT721 {
    /**
     * @notice Gets total number of tokens in existence, burned tokens will reduce the count.
     *
     * @return uint256 The total supply.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @notice Burns a token.
     *
     * @param tokenId The token ID to burn.
     */
    function burn(uint256 tokenId) external;
}

// File: lib/openzeppelin-contracts/contracts/utils/Address.sol



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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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