creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@intercoin/community/contracts/interfaces/ICommunity.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\n\ninterface ICommunity {\n    function initialize(\n        address hook,\n        address invitedHook,\n        address costManager,\n        address authorizedInviteManager,\n        string memory name,\n        string memory symbol,\n        string memory contractUri\n    ) external;\n\n    function addressesCount(uint8 roleIndex) external view returns (uint256);\n\n    function getRoles(\n        address[] calldata accounts\n    ) external view returns (uint8[][] memory);\n\n    function getAddresses(\n        uint8[] calldata rolesIndexes\n    ) external view returns (address[][] memory);\n\n    function getRolesWhichAccountCanGrant(\n        address accountWhichWillGrant,\n        string[] memory roleNames\n    ) external view returns (uint8[] memory);\n\n    function hasRole(\n        address account,\n        uint8 roleIndex\n    ) external view returns (bool);\n\n    function grantRoles(\n        address[] memory accounts,\n        uint8[] memory roleIndexes\n    ) external;\n\n    function revokeRoles(\n        address[] memory accounts,\n        uint8[] memory roleIndexes\n    ) external;\n}\n"
      },
      "@intercoin/releasemanager/contracts/CostManagerBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./interfaces/ICostManager.sol\";\nimport \"./interfaces/ICostManagerFactoryHelper.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nabstract contract CostManagerBase is Initializable {\n    using AddressUpgradeable for address;\n\n    address private costManager;\n    address private deployer;\n    bool private overrode;\n\n    error AlreadyOverrode();\n    error CanNotOverride();\n    error OverrideRequired();\n    error UnknownError();\n\n    /** \n    * @dev sets the costmanager token. calling only by factory owner\n    * @param costManager_ new address of costmanager token, or 0\n    */\n    function overrideCostManager(address costManager_) external {\n        // require factory owner or operator\n        // otherwise needed deployer(!!not contract owner)\n\n        if (overrode) {\n            revert AlreadyOverrode();\n        }\n\n        if (\n            deployer != _sender() ||\n            !ICostManagerFactoryHelper(deployer).canOverrideCostManager(address(this))\n        ) {\n            revert CanNotOverride();\n        }\n        \n        overrode = true;\n        _setCostManager(costManager_);\n    }\n\n    /** \n    * @dev viewer the costmanager address\n    * @return address of costmanager address\n    */\n    function getCostManager() public view returns(address) {\n        return costManager;\n    }\n\n    function __CostManagerHelper_init(address deployer_, address costManager_) internal onlyInitializing\n    {\n        deployer = deployer_;\n        costManager = costManager_;\n        overrode = false;\n    }\n\n     /**\n     * @dev Private function that tells contract to account for an operation\n     * @param info uint256 The operation ID (first 8 bits). in other bits any else info\n     * @param param1 uint256 Some more information, if any\n     * @param param2 uint256 Some more information, if any\n     */\n    function _accountForOperation(uint256 info, uint256 param1, uint256 param2) internal {\n        if (costManager != address(0)) {\n            try ICostManager(costManager).accountForOperation(\n                _sender(), info, param1, param2\n            )\n            returns (uint256 /*spent*/, uint256 /*remaining*/) {\n                // if error is not thrown, we are fine\n            } catch Error(string memory reason) {\n                // This is executed in case revert() was called with a reason\n                revert(reason);\n            } catch {\n                revert UnknownError();\n            }\n        }\n    }\n    \n    function _setCostManager(address costManager_) internal {\n        if (!overrode) {\n            revert OverrideRequired();\n        }\n        \n        costManager = costManager_;\n    }\n\n    \n    /** \n    * @dev viewer the deployer address\n    * @return address of deployer address\n    */\n    function getDeployer() internal view returns(address) {\n        return deployer;\n    }\n    \n    function _sender() internal virtual returns(address);\n}"
      },
      "@intercoin/releasemanager/contracts/CostManagerHelper.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./CostManagerBase.sol\";\n\n/**\n* used for instances that have created(cloned) by factory.\n*/\ncontract CostManagerHelper is CostManagerBase {\n\n    function _sender() internal override view returns(address){\n        return msg.sender;\n    }\n}"
      },
      "@intercoin/releasemanager/contracts/interfaces/ICostManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n//import \"@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol\";\n\ninterface ICostManager/* is IERC165Upgradeable*/ {\n    function accountForOperation(\n        address sender, \n        uint256 info, \n        uint256 param1, \n        uint256 param2\n    ) \n        external \n        returns(uint256, uint256);\n}"
      },
      "@intercoin/releasemanager/contracts/interfaces/ICostManagerFactoryHelper.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ICostManagerFactoryHelper {\n    \n    function canOverrideCostManager(address instance) external view returns (bool);\n}\n"
      },
      "@intercoin/releasemanager/contracts/interfaces/IReleaseManager.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IReleaseManager {\n    function initialize() external;\n    function registerInstance(address instanceAddress) external;\n    function checkInstance(address instanceAddress) external view returns(bool);\n    function checkFactory(address factoryAddress) external view returns(bool);\n}\n"
      },
      "@intercoin/releasemanager/contracts/ReleaseManagerHelper.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./interfaces/IReleaseManager.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\n\nabstract contract ReleaseManagerHelper {\n    using Address for address;\n    address private _releaseManager;\n\n    error ReleaseManagerInvalid(address addr);\n\n    /**\n    * @notice need to register release manager when factory(CommunityCoinFactory, IncomeContractFactory, etc) deployed\n    */\n    constructor(address releaseManagerAddr) {\n        if (\n            releaseManagerAddr.isContract() == false ||\n            releaseManagerAddr == address(0)\n        ) {\n            revert ReleaseManagerInvalid(releaseManagerAddr);\n        }\n\n        _releaseManager = releaseManagerAddr;\n    }\n\n    /**\n    * @notice view release manager address that was regsted when factory deployed\n    */\n    function releaseManager() public view returns(address) {\n        return _releaseManager;\n    }\n\n    /**\n    * @param instanceAddress address that was produced by factory need to be registered in ReleaseManager. Usually such method should be called after produce/produceDeterministic\n    */\n    function registerInstance(address instanceAddress) internal {\n        IReleaseManager(_releaseManager).registerInstance(instanceAddress);\n    }\n    \n}"
      },
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n    address private _owner;\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __Ownable_init() internal onlyInitializing {\n        __Ownable_init_unchained();\n    }\n\n    function __Ownable_init_unchained() internal onlyInitializing {\n        _transferOwnership(_msgSender());\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Indicates that the contract has been initialized.\n     * @custom:oz-retyped-from bool\n     */\n    uint8 private _initialized;\n\n    /**\n     * @dev Indicates that the contract is in the process of being initialized.\n     */\n    bool private _initializing;\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint8 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n     * constructor.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        bool isTopLevelCall = !_initializing;\n        require(\n            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n            \"Initializable: contract is already initialized\"\n        );\n        _initialized = 1;\n        if (isTopLevelCall) {\n            _initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            _initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: setting the version to 255 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint8 version) {\n        require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n        _initialized = version;\n        _initializing = true;\n        _;\n        _initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        require(_initializing, \"Initializable: contract is not initializing\");\n        _;\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        require(!_initializing, \"Initializable: contract is initializing\");\n        if (_initialized != type(uint8).max) {\n            _initialized = type(uint8).max;\n            emit Initialized(type(uint8).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint8) {\n        return _initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _initializing;\n    }\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[49] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\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(address from, address to, uint256 tokenId, bytes calldata data) 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(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\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(address from, address to, uint256 tokenId) 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-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\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     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, \"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(address target, bytes memory data, uint256 value) 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        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or 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            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\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"
      },
      "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\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 ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\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    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n\n    /**\n     * @dev This empty reserved space is put in place to allow future versions to add new\n     * variables without shifting down storage in the inheritance chain.\n     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n     */\n    uint256[50] private __gap;\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {\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/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, \"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(address target, bytes memory data, uint256 value) 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        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, 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        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or 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            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\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"
      },
      "contracts/interfaces/ISubscriptionsHook.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ISubscriptionsHook {\n    function onCharge(address token, uint256 amount) external;\n}\n"
      },
      "contracts/interfaces/ISubscriptionsManagerFactory.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ISubscriptionsManagerFactory {\n    function doCharge(\n        address token,\n        uint256 amount,\n        address from,\n        address to\n    ) external returns (bool success);\n}\n"
      },
      "contracts/interfaces/ISubscriptionsManagerUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ISubscriptionsManagerUpgradeable {\n    enum SubscriptionState {\n        NONE, // Subscription notfound. its like default value for subscription state\n        LAPSED, // (when active in grace period)\n        ACTIVE, //\n        BROKEN, // (when user didnt pay after retries attempt exceeded)\n        EXPIRED, // (when max intervals exceeded)\n        CANCELED // (when user canceled)\n    }\n    struct Subscription {\n        uint256 price; // if not 0, it overrides the global price\n        address subscriber;\n        uint64 startTime;\n        uint64 endTime; // because it was canceled, otherwise it is when it expires\n        uint16 intervals;\n        SubscriptionState state;\n    }\n\n    event Canceled(address subscriber, uint64 cancelTime);\n    event Subscribed(address subscriber, uint64 startTime);\n    event Restored(address subscriber, uint64 restoreTime, uint64 startTime);\n    event Charged(address subscriber, uint256 amount);\n    event ChargeFailed(address subscriber, uint256 amount);\n    event RetriesExpired(address subscriber, uint64 tryTime, uint64 retries);\n    event SubscriptionIsCanceled(address subscriber, uint64 chargeTime);\n    event SubscriptionExpired(address subscriber, uint64 chargeTime);\n    event SubscriptionLapsed(address subscriber, uint64 chargeTime);\n    event StateChanged(address subscriber, SubscriptionState newState);\n\n    error SubscriptionTooLong();\n    error SubscriptionTooShort();\n    error ControllerOnly(address controller);\n    error OwnerOrCallerOnly();\n    error NotSupported();\n    error invalidCommunitySettings();\n    error SubscriptionCantStart();\n\n    function initialize(\n        uint32 interval,\n        uint16 intervalsMax,\n        uint16 intervalsMin,\n        uint8 retries,\n        address token,\n        uint256 price,\n        address controller,\n        address recipient,\n        uint256 recipientTokenId,\n        address hook,\n        address costManager,\n        address producedBy\n    ) external;\n\n    function subscribeFromController(\n        address subscriber,\n        uint256 customPrice,\n        uint16 intervals\n    ) external;\n\n    // called by subscriber himself\n    function subscribe(uint16 intervals) external; // intervals is maximum times to renew\n\n    function cancel() external;\n\n    function restore() external;\n\n    // called by owner\n    function cancel(address[] memory subscribers) external;\n\n    function addCaller(address caller) external;\n\n    function removeCaller(address caller) external;\n\n    // ownerOrCaller\n    // called to charge some subscribers and extend their subscriptions\n    function charge(address[] memory subscribers) external; // ownerOrCaller\n\n    function restore(address[] memory subscribers) external; // ownerOrCaller\n\n    function isActive(\n        address subscriber\n    ) external view returns (bool, SubscriptionState);\n\n    function activeUntil(address subscriber) external view returns (uint64);\n}\n"
      },
      "contracts/SubscriptionsManagerUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport \"@intercoin/releasemanager/contracts/CostManagerHelper.sol\";\nimport \"@intercoin/releasemanager/contracts/ReleaseManagerHelper.sol\";\nimport \"@intercoin/community/contracts/interfaces/ICommunity.sol\";\nimport \"./interfaces/ISubscriptionsManagerUpgradeable.sol\";\nimport \"./interfaces/ISubscriptionsManagerFactory.sol\";\nimport \"./interfaces/ISubscriptionsHook.sol\";\n\ncontract SubscriptionsManagerUpgradeable is\n    OwnableUpgradeable,\n    ISubscriptionsManagerUpgradeable,\n    ReentrancyGuardUpgradeable,\n    CostManagerHelper\n{\n    uint32 public interval;\n    uint16 public intervalsMax; // if 0, no max\n    uint16 public intervalsMin;\n    uint8 public retries;\n    address public token; // the token to charge\n    uint256 public price; // the price to charge\n\n    address public recipient;\n    uint256 public recipientTokenId;\n\n    address public hook;\n\n    mapping(address => Subscription) public subscriptions;\n    mapping(address => bool) public callers;\n\n    address public controller; // optional, smart contract that can start a subscription and pay first charge\n    address public factory; // the factory\n    //address owner; // owner can cancel subscriptions, add callers\n    address public community; // any CommunityContract\n    uint8 public roleId; // the role\n\n    uint8 internal constant OPERATION_SHIFT_BITS = 240; // 256 - 16\n    // Constants representing operations\n    uint8 internal constant OPERATION_INITIALIZE = 0x0;\n\n    modifier onlyController() {\n        if (controller == address(0)) {\n            revert NotSupported();\n        }\n\n        if (controller != _msgSender()) {\n            revert ControllerOnly(controller);\n        }\n\n        _;\n    }\n\n    modifier ownerOrCaller() {\n        address ms = _msgSender();\n        if (owner() != _msgSender() && callers[ms] != true) {\n            revert OwnerOrCallerOnly();\n        }\n        _;\n    }\n\n    constructor() {\n        _disableInitializers();\n    }\n\n    /**\n     * @param interval_ period, day,week,month in seconds\n     * @param intervalsMax_ max interval\n     * @param intervalsMin_ min interval\n     * @param retries_ amount of retries\n     * @param token_ token address to charge\n     * @param price_ price for subsription on single interval\n     * @param controller_ [optional] controller address\n     * @param recipient_ address which will receive the subscription payments\n     * @param recipientTokenId_ if not 0, then recipient_ is interpreted as a NFT contract, while the token owner would be the actual recipient\n     * @param hook_  if present then try to call hook.onCharge\n     * @param costManager_ costManager address\n     * @param producedBy_ producedBy address\n     * @custom:calledby factory\n     * @custom:shortd initialize while factory produce\n     */\n    function initialize(\n        uint32 interval_,\n        uint16 intervalsMax_,\n        uint16 intervalsMin_,\n        uint8 retries_,\n        address token_,\n        uint256 price_,\n        address controller_,\n        address recipient_,\n        uint256 recipientTokenId_,\n        address hook_,\n        address costManager_,\n        address producedBy_\n    ) external override initializer {\n        __CostManagerHelper_init(_msgSender(), costManager_);\n\n        __Ownable_init();\n        __ReentrancyGuard_init();\n\n        factory = owner();\n\n        interval = interval_;\n        intervalsMax = intervalsMax_;\n        intervalsMin = intervalsMin_;\n        retries = retries_;\n        token = token_;\n        price = price_;\n        controller = controller_;\n        recipient = recipient_;\n        recipientTokenId = recipientTokenId_;\n        hook = hook_;\n\n        _accountForOperation(\n            OPERATION_INITIALIZE << OPERATION_SHIFT_BITS,\n            uint256(uint160(producedBy_)),\n            0\n        );\n    }\n\n    ///////////////////////////////////\n    // external\n    ///////////////////////////////////\n\n    /**\n     * @dev called by authorized controller contracts to start subscriptions with custom prices\n     * @param subscriber the address that will be paying\n     * @param customPrice custom price for this subscription\n     * @param desiredIntervals the number of intervals (e.g. weeks) this subscription should last\n     * @custom:calledby controller\n     */\n    function subscribeFromController(\n        address subscriber,\n        uint256 customPrice,\n        uint16 desiredIntervals\n    ) external override onlyController {\n        _subscribe(subscriber, customPrice, desiredIntervals);\n    }\n\n    /**\n     * @dev starts a recurring subscription for msg.sender at the default price\n     * @param desiredIntervals the number of intervals (e.g. weeks) this subscription should last\n     */\n    function subscribe(uint16 desiredIntervals) external override {\n        _subscribe(_msgSender(), price, desiredIntervals);\n    }\n\n    /**\n     * @dev cancels subscription that is currently active for the msg.sender\n     */\n    function cancel() external override {\n        Subscription storage subscription = subscriptions[_msgSender()];\n        if (subscription.state == SubscriptionState.ACTIVE) {\n            _active(subscription, SubscriptionState.CANCELED);\n            subscription.endTime = _currentBlockTimestamp();\n            emit Canceled(subscription.subscriber, _currentBlockTimestamp());\n        }\n    }\n\n    /**\n     * @dev can be called by owner to unilateraly cancel multiple subscriptions\n     * @param subscribers the addresses whose subscriptions to cancel\n     * @custom:calledby owner\n     */\n    function cancel(address[] memory subscribers) external override onlyOwner {\n        uint256 l = subscribers.length;\n        for (uint256 i = 0; i < l; i++) {\n            Subscription storage subscription = subscriptions[subscribers[i]];\n            if (subscription.state == SubscriptionState.ACTIVE) {\n                _active(subscription, SubscriptionState.CANCELED);\n                subscription.endTime = _currentBlockTimestamp();\n            }\n            emit Canceled(subscription.subscriber, _currentBlockTimestamp());\n        }\n    }\n\n    /**\n     * @dev updates any CommunityContract in which roles will be granted and revoked\n     * @param community_ the address of the community contract\n     * @param roleId_ the role to grant/revoke, note that this SubscriptionContract should have a role that is able to grant/revoke roleId\n     * @custom:calledby owner\n     */\n    function setCommunity(\n        address community_,\n        uint8 roleId_\n    ) external onlyOwner {\n        // deployer - it's factory\n        address releaseManagerAddr = ReleaseManagerHelper(getDeployer()).releaseManager();\n        bool isCommunityVerifying;\n        \n        if (community_ != address(0)) {\n            isCommunityVerifying = IReleaseManager(releaseManagerAddr).checkInstance(community_);\n        }\n\n        if (\n            (roleId_ == 0 && community_ != address(0)) ||   //roleID should exists if `community_` specified\n            (community_ != address(0) && !isCommunityVerifying) //`community_` should be in our ecosystem if `community_` specified\n        ) {\n            revert invalidCommunitySettings();\n        }\n\n        //todo: also need to check \"can this contract grant and revoke roleId\"\n\n        community = community_;\n        roleId = roleId_;\n    }\n\n    /**\n     * @dev called by authorized controller contracts to charge subscriptions\n     * @param subscribers the addresses that will be paying\n     * @custom:calledby owner or caller\n     */\n    function charge(\n        address[] memory subscribers\n    ) external override ownerOrCaller {\n        // if all callers fail to do this within an interval\n        // then restore() will have to be called before charge()\n        _charge(subscribers, 1, false);\n    }\n\n    /**\n     * @dev attempt to charge and restore a lapsed subscription from msg.sender\n     */\n    function restore() external override {\n        address[] memory subscribers = new address[](1);\n        subscribers[0] = _msgSender();\n        _restore(subscribers, false);\n    }\n\n    /**\n     * @dev restore subscription\n     * @param subscribers array of subscribers for whom to attempt to charge and restore a lapsed subscription\n     * @custom:calledby owner or one of the added callers\n     */\n    function restore(\n        address[] memory subscribers\n    ) external override ownerOrCaller {\n        _restore(subscribers, true);\n    }\n\n    /**\n     * @dev add an authorized caller who can call methods to charge subscribers or attempt to restore subscriptions\n     * @param caller the address of the caller\n     */\n    function addCaller(address caller) external override onlyOwner {\n        callers[caller] = true;\n    }\n\n    /**\n     * @dev remove an authorized caller who can call methods to charge subscribers or attempt to restore subscriptions\n     * @param caller the address of the caller\n     */\n    function removeCaller(address caller) external override onlyOwner {\n        //callers[caller] = false;\n        delete callers[caller];\n    }\n\n    /**\n     * @dev find out the state of a subscriber\n     * @param subscriber the address of the subscriber\n     * @return active whether the subscription is still active\n     * @return state the state of the subscription (NONE, ACTIVE, EXPRIED, CANCELED)\n     */\n    function isActive(\n        address subscriber\n    ) external view override returns (bool, SubscriptionState) {\n        Subscription storage subscription = subscriptions[subscriber];\n\n        return (\n            (subscription.state == SubscriptionState.ACTIVE ||\n                subscription.state == SubscriptionState.LAPSED),\n            subscription.state\n        );\n    }\n\n    /**\n     * @dev find out the timestamp of when a subscription expires\n     * @param subscriber the address of the subscriber\n     * @return timestamp seconds since Unix epoch\n     */\n    function activeUntil(\n        address subscriber\n    ) external view override returns (uint64) {\n        Subscription storage subscription = subscriptions[subscriber];\n        return subscription.endTime;\n    }\n\n    ///////////////////////////////////\n    // public\n    ///////////////////////////////////\n\n    ///////////////////////////////////\n    // internal\n    ///////////////////////////////////\n    /**\n     * @notice helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**64 - 1]\n     */\n    function _currentBlockTimestamp() internal view returns (uint64) {\n        return uint64(block.timestamp);\n    }\n\n    ///////////////////////////////////\n    // private\n    ///////////////////////////////////\n\n    // must prepay intervalsMin intervals to start a subscription\n    function _subscribe(\n        address subscriber,\n        uint256 fee,\n        uint16 desiredIntervals\n    ) private {\n        if (intervalsMax > 0 && desiredIntervals > intervalsMax) {\n            revert SubscriptionTooLong();\n        }\n        if (desiredIntervals != 0 && desiredIntervals < intervalsMin) {\n            revert SubscriptionTooShort();\n        }\n        subscriptions[subscriber] = Subscription(\n            fee,\n            subscriber,\n            _currentBlockTimestamp(),\n            _currentBlockTimestamp(),\n            desiredIntervals,\n            SubscriptionState.LAPSED\n        );\n\n        //---\n        address[] memory subscribers = new address[](1);\n        subscribers[0] = subscriber;\n        //---\n        uint16 count = _charge(\n            subscribers,\n            intervalsMin > 0 ? intervalsMin : 1,\n            true\n        ); // charge the first intervalsMin intervals\n        if (count > 0) {\n            emit Subscribed(subscriber, _currentBlockTimestamp());\n        }\n    }\n\n    // doesn't just charge but updates valid subscriptions\n    // to be either extended or canceled and set endTime\n    // requiring them to be restored\n    function _charge(\n        address[] memory subscribers,\n        uint16 desiredIntervals,\n        bool firstTime\n    ) private returns (uint16 count) {\n        uint256 l = subscribers.length;\n\n        for (uint256 i = 0; i < l; i++) {\n            address subscriber = subscribers[i];\n            Subscription storage subscription = subscriptions[subscriber];\n\n            if (subscription.endTime > _currentBlockTimestamp()) {\n                // subscription is still active, no need to charge\n                continue;\n            }\n            // will turn into expired state after trying to charge\n            // if (subscription.endTime > _currentBlockTimestamp() - interval*retries) {\n            //     // subscription turn to EXPIRED state, need to charge or manually restore\n            //     _active(subscription, SubscriptionState.EXPIRED);\n            //     emit SubscriptionExpired(subscriber, _currentBlockTimestamp());\n            //     continue;\n            // }\n\n            if (_subscriptionActualize(subscription)) {\n                continue;\n            }\n\n            bool result = ISubscriptionsManagerFactory(factory).doCharge(\n                token,\n                getSubscriptionPrice(subscription) * desiredIntervals,\n                subscriber,\n                recipientTokenId != 0\n                    ? IERC721Upgradeable(recipient).ownerOf(recipientTokenId)\n                    : recipient\n            );\n\n            if (result) {\n                _active(subscription, SubscriptionState.ACTIVE);\n                emit Charged(\n                    subscriber,\n                    getSubscriptionPrice(subscription) * desiredIntervals\n                );\n                subscription.endTime += interval * desiredIntervals;\n                count++;\n\n                if (hook != address(0)) {\n                    ISubscriptionsHook(hook).onCharge(\n                        token,\n                        getSubscriptionPrice(subscription)\n                    );\n                }\n            } else {\n                if (firstTime) {\n                    revert SubscriptionCantStart();\n                } else {\n                    if (subscription.state != SubscriptionState.LAPSED) {\n                        emit SubscriptionLapsed(\n                            subscriber,\n                            _currentBlockTimestamp()\n                        );\n                    }\n\n                    _active(subscription, SubscriptionState.LAPSED);\n                    emit ChargeFailed(\n                        subscriber,\n                        getSubscriptionPrice(subscription)\n                    );\n                }\n            }\n        }\n    }\n\n    function getSubscriptionPrice(\n        Subscription storage subscription\n    ) private view returns (uint256) {\n        return (subscription.price == 0) ? price : subscription.price;\n    }\n\n    function _active(\n        Subscription storage subscription,\n        SubscriptionState newState\n    ) private {\n        if (subscription.state == newState) {\n            return; // nothing to do\n        }\n        subscription.state = newState;\n        emit StateChanged(subscription.subscriber, newState);\n\n        if (community == address(0)) {\n            return; // nothing to do\n        }\n\n        address[] memory _s = new address[](1);\n        uint8[] memory _r = new uint8[](1);\n        _s[0] = subscription.subscriber;\n        _r[0] = roleId;\n        if (newState == SubscriptionState.ACTIVE) {\n            ICommunity(community).grantRoles(_s, _r);\n        } else {\n            ICommunity(community).revokeRoles(_s, _r);\n        }\n    }\n\n    /**\n    // try to check:\n    // - is user interval expired?\n    // - is subscription max interval expire?\n    // - is exceed retries attempt?\n    // - \n    */\n    function _subscriptionActualize(\n        Subscription storage subscription\n    ) private returns (bool skip) {\n        if (subscription.state == SubscriptionState.LAPSED) {\n            if (\n                // subscription turn to BROKEN state as reached maximum retries attempt\n                (subscription.endTime <\n                    _currentBlockTimestamp() - interval * retries) ||\n                // or exceed interval subscription\n                (_currentBlockTimestamp() - subscription.startTime >\n                    interval * subscription.intervals)\n            ) {\n                // turn into the broken state, which can not be restored\n                _active(subscription, SubscriptionState.BROKEN);\n                emit SubscriptionIsCanceled(\n                    subscription.subscriber,\n                    _currentBlockTimestamp()\n                );\n                //continue;\n                skip = true;\n            }\n        }\n    }\n\n    function _restore(\n        address[] memory subscribers,\n        bool ownerOrCaller_\n    ) private {\n        uint256 l = subscribers.length;\n        for (uint256 i = 0; i < l; i++) {\n            address subscriber = subscribers[i];\n            Subscription storage subscription = subscriptions[subscriber];\n\n            if (subscription.state == SubscriptionState.LAPSED) {\n                uint64 difference = uint64(\n                    _currentBlockTimestamp() - subscription.endTime\n                );\n                uint64 diffIntervals = difference / interval + 1; // rounds up to nearest integer\n                if (!ownerOrCaller_ && diffIntervals > uint64(retries)) {\n                    emit RetriesExpired(\n                        subscriber,\n                        _currentBlockTimestamp(),\n                        diffIntervals\n                    );\n                }\n\n                if (\n                    _currentBlockTimestamp() - subscription.startTime >\n                    interval * subscription.intervals\n                ) {\n                    emit SubscriptionExpired(\n                        subscriber,\n                        _currentBlockTimestamp()\n                    );\n                    _active(subscription, SubscriptionState.EXPIRED);\n                    continue;\n                }\n\n                // and turn to broken if\n                // - is user interval expired?\n                // - is subscription max interval expire?\n                // - is exceed retries attempt?\n                // -\n                if (_subscriptionActualize(subscription)) {\n                    continue;\n                }\n\n                uint256 amount = getSubscriptionPrice(subscription);\n\n                bool result = ISubscriptionsManagerFactory(factory).doCharge(\n                    token,\n                    subscription.price * diffIntervals,\n                    subscriber,\n                    recipientTokenId != 0\n                        ? IERC721Upgradeable(recipient).ownerOf(\n                            recipientTokenId\n                        )\n                        : recipient\n                );\n\n                if (result) {\n                    _active(subscription, SubscriptionState.ACTIVE);\n                    emit Restored(\n                        subscriber,\n                        _currentBlockTimestamp(),\n                        subscription.endTime\n                    );\n                    subscription.endTime += interval * diffIntervals;\n                } else {\n                    emit ChargeFailed(subscriber, amount);\n                }\n            }\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 80
      },
      "metadata": {
        "bytecodeHash": "none"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}