creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "contracts/IncomeContractUBI.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\npragma experimental ABIEncoderV2;\n\nimport \"./base/IncomeContractUBIBase.sol\";\nimport \"./interfaces/IIncomeContractUBI.sol\";\n\ncontract IncomeContractUBI is IncomeContractUBIBase, IIncomeContractUBI {\n    \n    /**\n     * @param token  token address of eth\n     * @param community address of community contract\n     * @param role role of contracts who can send stats of prices and ratios\n     * @param ubiRole role of EOA which can obtain ubi\n     */\n    function init(\n        address token, // can be address(0) = 0x0000000000000000000000000000000000000000   mean   ETH\n        address community,\n        uint8 role,\n        uint8 ubiRole\n    )\n        public \n        initializer \n    {\n        __IncomeContractUBI_init(token, community, role, ubiRole);\n    }\n\n    \n}"
      },
      "contracts/base/IncomeContractUBIBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\nimport \"../lib/DateTime.sol\";\n\nimport \"../interfaces/IUBI.sol\";\n\n\nimport \"../base/IncomeContractBase.sol\";\nimport \"./UBIBase.sol\";\n\nabstract contract IncomeContractUBIBase is IUBI, IncomeContractBase, UBIBase {\n    \n    \n    uint8 internal communityStatsRole;\n    \n    uint256 constant sampleSize = 10;\n    uint256 constant multiplier = 1e6;\n    \n    \n    using DateTime for uint256;\n    \n    uint256 private startDateIndex;\n    \n    \n    uint256 private tagsIndex;\n    mapping (bytes32 => uint256) internal _tags;\n    mapping (uint256 => bytes32) internal _tagsIndices;\n    \n    \n    struct RatioStruct {\n        int256 count;\n        int256 total;\n        int256 average;\n        //int256 median;\n        //int256 variance;\n        int256 prevRatio;\n        bool alreadyInit;\n    }\n    \n    mapping(bytes32 => RatioStruct) ratiosData;\n    \n    //      tagname            dayTs       price\n    mapping(bytes32 => mapping(uint256 => uint256)) avgPrices;\n        \n    //      dayTs       ubi\n    mapping(uint256 => uint256) UBIValues;\n    \n    struct UBIStruct {\n        uint256 lastIndex;\n        uint256 claimed;\n        uint256 total;\n        uint256 prevUBI;\n        bool exists;\n    }\n    mapping(address => UBIStruct) users;\n    \n\n    function __IncomeContractUBI_init(\n        address token, // can be address(0) = 0x0000000000000000000000000000000000000000   mean   ETH\n        address communityAddress,\n        uint8 statsRole,\n        uint8 ubiRole\n    )  \n        internal\n        onlyInitializing\n    {\n        tagsIndex = 1;\n        __IncomeContract_init(token);\n        __UBIBase_init(communityAddress, ubiRole); \n        communityStatsRole = statsRole;\n        \n        startDateIndex = getCurrentDateIndex();\n       \n    }\n\n    function getRatioMultiplier() external pure returns(uint256) {\n        return multiplier;\n    }\n\n    // calling by voting\n    function setRatio(\n        bytes32 tag, \n        uint256 ratio\n    ) \n        external \n        override \n    {\n        canRecord(_msgSender(), communityStatsRole);\n        createTag(tag);\n        _record(tag,int256(ratio));\n        \n        uint256 dateIndex = getCurrentDateIndex();\n        \n        setUBI(dateIndex);\n        \n    }\n    \n    function setRatio(\n        bytes32[] calldata tags, \n        uint256[] calldata ratios\n    ) \n        external \n        override \n    {\n        canRecord(_msgSender(), communityStatsRole);\n        uint256 dateIndex = getCurrentDateIndex();\n        for (uint256 i=0; i<tags.length; i++) {\n            createTag(tags[i]);\n            _record(tags[i],int256(ratios[i]));\n        }\n        setUBI(dateIndex);\n    }\n    \n    // calling by Prices\n    function setAvgPrice(\n        bytes32 tag, \n        uint256 price\n    ) \n        external \n        override \n    {\n        canRecord(_msgSender(), communityStatsRole);\n        uint256 dateIndex = getCurrentDateIndex();\n        createTag(tag);\n        avgPrices[tag][dateIndex] = price;\n        \n        setUBI(dateIndex);\n        \n    }\n    function setAvgPrice(\n        bytes32[] calldata tags, \n        uint256[] calldata prices\n    ) \n        external \n        override \n    {\n        canRecord(_msgSender(), communityStatsRole);\n        uint256 dateIndex = getCurrentDateIndex();\n        for (uint256 i=0; i<tags.length; i++) {\n            createTag(tags[i]);\n            avgPrices[tags[i]][dateIndex] = prices[i];\n        }\n        setUBI(dateIndex);\n    }\n\n    function checkUBI(\n    ) \n        external \n        view\n        override \n        returns(uint256 ubi) \n    {   \n        address sender = _msgSender();\n\n        uint256 lastIndex = users[sender].lastIndex;\n        uint256 claimed = users[sender].claimed;\n        uint256 total = users[sender].total;\n        uint256 prevUBI = users[sender].prevUBI;\n        \n        if (users[sender].exists == false) {\n            lastIndex = startDateIndex;\n        }\n       \n        uint256 untilIndex = getCurrentDateIndex(); //.add(DAY_IN_SECONDS);\n        for (uint256 i=lastIndex; i<untilIndex; i=i+DateTime.DAY_IN_SECONDS) {\n            if (UBIValues[i] == 0) {\n            } else {\n               prevUBI = UBIValues[i];\n            }\n            total = total + prevUBI;\n            lastIndex = i + DateTime.DAY_IN_SECONDS;\n            \n        }\n        ubi =  (total - claimed) / multiplier;\n\n    }\n    \n    function claimUBI(\n    ) \n        external \n        override \n    {\n\n        address sender = _msgSender();\n        canObtainUBI(sender);\n        _actualizeUBI(sender);\n        uint256 toPay = users[sender].total - users[sender].claimed;\n        require(toPay / multiplier > 0, \"Amount exceeds balance available to claim\");\n        users[sender].claimed = users[sender].claimed + toPay;\n        bool success = _claim(sender, toPay / multiplier);\n        require(success == true, \"NOT_ENOUGH_FUNDS\");\n        \n    }\n    \n    function _actualizeUBI(\n        address account\n    ) \n        internal \n        override\n        returns(uint256 ubi) \n    {\n        if (users[account].exists == false) {\n            users[account].lastIndex = startDateIndex;\n            users[account].claimed = 0;\n            users[account].total = 0;\n            users[account].prevUBI = 0;\n            users[account].exists = true;\n        }\n        \n        uint256 untilIndex = getCurrentDateIndex(); //.add(DAY_IN_SECONDS);\n        for (uint256 i=users[account].lastIndex; i<untilIndex; i=i+DateTime.DAY_IN_SECONDS) {\n            if (UBIValues[i] == 0) {\n            } else {\n                users[account].prevUBI = UBIValues[i];\n            }\n            users[account].total = users[account].total + users[account].prevUBI;\n            users[account].lastIndex = i + DateTime.DAY_IN_SECONDS;\n            \n        }\n        ubi =  (users[account].total - users[account].claimed) / multiplier;\n\n    }\n    \n    \n    function setUBI(\n        uint256 dateIndex\n    ) \n        private\n    {\n        // UBI = SUM over all tags of ( avgPrice[day] * avgFractionFromVote )\n        \n        uint256 ubi;\n        for (uint256 i=0; i< tagsIndex; i++) {\n            ubi = ubi + (\n                multiplier * (\n                    uint256(ratiosData[_tagsIndices[i]].average) * (avgPrices[_tagsIndices[i]][dateIndex]) / (multiplier)\n                ) / multiplier\n            );\n            \n        }\n        UBIValues[dateIndex] = ubi;\n    }\n    \n    function getCurrentDateIndex(\n    ) \n        internal \n        view \n        returns(uint256 dateIndex) \n    {\n        uint256 y = (block.timestamp).getYear();\n        uint256 m = (block.timestamp).getMonth();\n        uint256 d = (block.timestamp).getDay();\n        dateIndex = (uint256(y)).toTimestamp(uint256(m),uint256(d));\n    }\n    \n    function _record(\n        bytes32 tagBytes32, \n        int256 ratio\n    ) \n        private \n    {\n        ratio = ratio*int256(multiplier);\n        \n        ratiosData[tagBytes32].total = ratiosData[tagBytes32].total + ratio;\n        \n        if (ratiosData[tagBytes32].alreadyInit == false) {\n            ratiosData[tagBytes32].alreadyInit = true;\n            ratiosData[tagBytes32].count = 1;\n            ratiosData[tagBytes32].average = ratio;\n            ratiosData[tagBytes32].prevRatio = ratio;\n        } else {\n            ratiosData[tagBytes32].count = ratiosData[tagBytes32].count + 1;\n            //int256 oldAverage = ratiosData[tagBytes32].average;\n            \n            // https://stackoverflow.com/questions/10930732/c-efficiently-calculating-a-running-median/15150143#15150143\n            // for each sample\n            // average += ( sample - average ) * 0.1f; // rough running average.\n            // median += _copysign( average * 0.01, sample - median );\n            // but \"0.1f\" replace to \"sampleSize\"\n            ratiosData[tagBytes32].average = ratiosData[tagBytes32].average + (\n                (\n                    (\n                        (int256(ratio))- (ratiosData[tagBytes32].average)\n                    ) / (int256(sampleSize))\n                )\n            );\n            \n            ratiosData[tagBytes32].prevRatio = ratio;\n            \n            \n        }\n        \n    }\n    \n    function createTag(bytes32 tag) private {\n        if (_tags[tag] == 0) {\n            _tags[tag] = tagsIndex;\n            _tagsIndices[tagsIndex] = tag;\n            tagsIndex = tagsIndex + 1;\n        }\n       \n    }\n    \n}"
      },
      "contracts/interfaces/IIncomeContractUBI.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IIncomeContractUBI {\n    function init(\n        address token, // can be address(0) = 0x0000000000000000000000000000000000000000   mean   ETH\n        address community,\n        uint8 role,\n        uint8 ubiRole\n    ) external;\n}"
      },
      "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "contracts/lib/DateTime.sol": {
        "content": "// SPDX-License-Identifier: MIT\r\npragma solidity ^0.8.0;\r\npragma experimental ABIEncoderV2;\r\n\r\nlibrary DateTime {\r\n       \r\n        /*\r\n         *  Date and Time utilities for ethereum contracts\r\n         *\r\n         */\r\n        struct _DateTime {\r\n                uint256 year;\r\n                uint256 month;\r\n                uint256 day;\r\n                uint256 hour;\r\n                uint256 minute;\r\n                uint256 second;\r\n                uint256 weekday;\r\n        }\r\n\r\n        uint256 constant DAY_IN_SECONDS = 86400;\r\n        uint256 constant YEAR_IN_SECONDS = 31536000;\r\n        uint256 constant LEAP_YEAR_IN_SECONDS = 31622400;\r\n\r\n        uint256 constant HOUR_IN_SECONDS = 3600;\r\n        uint256 constant MINUTE_IN_SECONDS = 60;\r\n\r\n        uint256 constant ORIGIN_YEAR = 1970;\r\n\r\n        function isLeapYear(uint256 year) internal pure returns (bool) {\r\n                if (year % 4 != 0) {\r\n                        return false;\r\n                }\r\n                if (year % 100 != 0) {\r\n                        return true;\r\n                }\r\n                if (year % 400 != 0) {\r\n                        return false;\r\n                }\r\n                return true;\r\n        }\r\n\r\n        function leapYearsBefore(uint256 year) internal pure returns (uint256) {\r\n                year -= 1;\r\n                return year / 4 - year / 100 + year / 400;\r\n        }\r\n\r\n        function getDaysInMonth(uint256 month, uint256 year) internal pure returns (uint256) {\r\n                if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\r\n                        return 31;\r\n                }\r\n                else if (month == 4 || month == 6 || month == 9 || month == 11) {\r\n                        return 30;\r\n                }\r\n                else if (isLeapYear(year)) {\r\n                        return 29;\r\n                }\r\n                else {\r\n                        return 28;\r\n                }\r\n        }\r\n\r\n        function parseTimestamp(uint256 timestamp) internal pure returns (_DateTime memory dt) {\r\n                uint256 secondsAccountedFor = 0;\r\n                uint256 buf;\r\n                uint256 i;\r\n\r\n                // Year\r\n                dt.year = getYear(timestamp);\r\n                buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);\r\n\r\n                secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;\r\n                secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);\r\n\r\n                // Month\r\n                uint256 secondsInMonth;\r\n                for (i = 1; i <= 12; i++) {\r\n                        secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);\r\n                        if (secondsInMonth + secondsAccountedFor > timestamp) {\r\n                                dt.month = i;\r\n                                break;\r\n                        }\r\n                        secondsAccountedFor += secondsInMonth;\r\n                }\r\n\r\n                // Day\r\n                for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {\r\n                        if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {\r\n                                dt.day = i;\r\n                                break;\r\n                        }\r\n                        secondsAccountedFor += DAY_IN_SECONDS;\r\n                }\r\n\r\n                // Hour\r\n                dt.hour = getHour(timestamp);\r\n\r\n                // Minute\r\n                dt.minute = getMinute(timestamp);\r\n\r\n                // Second\r\n                dt.second = getSecond(timestamp);\r\n\r\n                // Day of week.\r\n                dt.weekday = getWeekday(timestamp);\r\n        }\r\n\r\n        function getYear(uint256 timestamp) internal pure returns (uint256) {\r\n                uint256 secondsAccountedFor = 0;\r\n                uint256 year;\r\n                uint256 numLeapYears;\r\n\r\n                // Year\r\n                year = uint256(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);\r\n                numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);\r\n\r\n                secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;\r\n                secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);\r\n\r\n                while (secondsAccountedFor > timestamp) {\r\n                        if (isLeapYear(uint256(year - 1))) {\r\n                                secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;\r\n                        }\r\n                        else {\r\n                                secondsAccountedFor -= YEAR_IN_SECONDS;\r\n                        }\r\n                        year -= 1;\r\n                }\r\n                return year;\r\n        }\r\n\r\n        function getMonth(uint256 timestamp) internal pure returns (uint256) {\r\n                return parseTimestamp(timestamp).month;\r\n        }\r\n\r\n        function getDay(uint256 timestamp) internal pure returns (uint256) {\r\n                return parseTimestamp(timestamp).day;\r\n        }\r\n\r\n        function getHour(uint256 timestamp) internal pure returns (uint256) {\r\n                return uint256((timestamp / 60 / 60) % 24);\r\n        }\r\n\r\n        function getMinute(uint256 timestamp) internal pure returns (uint256) {\r\n                return uint256((timestamp / 60) % 60);\r\n        }\r\n\r\n        function getSecond(uint256 timestamp) internal pure returns (uint256) {\r\n                return uint256(timestamp % 60);\r\n        }\r\n\r\n        function getWeekday(uint256 timestamp) internal pure returns (uint256) {\r\n                return uint256((timestamp / DAY_IN_SECONDS + 4) % 7);\r\n        }\r\n\r\n        function toTimestamp(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) {\r\n                return toTimestamp(year, month, day, 0, 0, 0);\r\n        }\r\n\r\n        function toTimestamp(uint256 year, uint256 month, uint256 day, uint256 hour) internal pure returns (uint256 timestamp) {\r\n                return toTimestamp(year, month, day, hour, 0, 0);\r\n        }\r\n\r\n        function toTimestamp(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute) internal pure returns (uint256 timestamp) {\r\n                return toTimestamp(year, month, day, hour, minute, 0);\r\n        }\r\n\r\n        function toTimestamp(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (uint256 timestamp) {\r\n                uint256 i;\r\n\r\n                // Year\r\n                for (i = ORIGIN_YEAR; i < year; i++) {\r\n                        if (isLeapYear(i)) {\r\n                                timestamp += LEAP_YEAR_IN_SECONDS;\r\n                        }\r\n                        else {\r\n                                timestamp += YEAR_IN_SECONDS;\r\n                        }\r\n                }\r\n\r\n                // Month\r\n                uint256[12] memory monthDayCounts;\r\n                monthDayCounts[0] = 31;\r\n                if (isLeapYear(year)) {\r\n                        monthDayCounts[1] = 29;\r\n                }\r\n                else {\r\n                        monthDayCounts[1] = 28;\r\n                }\r\n                monthDayCounts[2] = 31;\r\n                monthDayCounts[3] = 30;\r\n                monthDayCounts[4] = 31;\r\n                monthDayCounts[5] = 30;\r\n                monthDayCounts[6] = 31;\r\n                monthDayCounts[7] = 31;\r\n                monthDayCounts[8] = 30;\r\n                monthDayCounts[9] = 31;\r\n                monthDayCounts[10] = 30;\r\n                monthDayCounts[11] = 31;\r\n\r\n                for (i = 1; i < month; i++) {\r\n                        timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];\r\n                }\r\n\r\n                // Day\r\n                timestamp += DAY_IN_SECONDS * (day - 1);\r\n\r\n                // Hour\r\n                timestamp += HOUR_IN_SECONDS * (hour);\r\n\r\n                // Minute\r\n                timestamp += MINUTE_IN_SECONDS * (minute);\r\n\r\n                // Second\r\n                timestamp += second;\r\n\r\n                return timestamp;\r\n        }\r\n}"
      },
      "contracts/interfaces/IUBI.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\ninterface IUBI {\n    function setRatio(bytes32 tag, uint256 ratio) external;\n    function setRatio(bytes32[] calldata tags, uint256[] calldata ratios) external;\n    function setAvgPrice(bytes32 tag, uint256 price) external;\n    function setAvgPrice(bytes32[] calldata tags, uint256[] calldata prices) external;\n    \n    function checkUBI() external view returns(uint256);\n    function claimUBI() external;\n\n}"
      },
      "contracts/base/IncomeContractBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n//import \"../access/TrustedForwarder.sol\";\nimport \"@artman325/trustedforwarder/contracts/TrustedForwarder.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\nabstract contract IncomeContractBase is TrustedForwarder, OwnableUpgradeable, ReentrancyGuardUpgradeable {\n    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n    \n    struct Restrict {\n        uint256 amount;\n        uint256 startTime;\n        uint256 untilTime;\n        bool gradual;\n        uint32 fraction;\n    }\n    \n    struct RestrictParam {\n        uint256 amount;\n        uint256 untilTime;\n        bool gradual;\n        uint32 fraction;\n    }\n        \n    modifier recipientExists(address recipient) {\n        require(recipients[recipient].exists == true, \"NO_SUCH_RECIPIENT\");\n        _;\n    }\n    \n    modifier canManage(address recipient) {\n        require(recipients[recipient].managers.contains(_msgSender()) == true, \"CANNOT_MANAGE\");\n        _;\n    }\n    uint32 constant FRACTION = 100000;\n   \n    struct Recipient {\n        address addr;\n        uint256 amountMax;\n        uint256 amountClaimed; //means how funds recipient have claimed already\n        uint256 amountPaid;     // means how funds manager have paid to recipient\n        Restrict[] restrictions;\n        EnumerableSetUpgradeable.AddressSet managers;\n        bool exists;\n    }\n    \n    mapping(address => Recipient) recipients;\n    address tokenAddr;\n\n    \n    function __IncomeContract_init(\n        address token // can be address(0) = 0x0000000000000000000000000000000000000000   mean   ETH\n    ) \n        internal\n        onlyInitializing\n    {\n        __Ownable_init();\n        __TrustedForwarder_init();\n        __ReentrancyGuard_init();\n        \n        tokenAddr = token;\n    }\n    \n    receive() external payable {\n        // payable fallback to receive and store ETH\n    }\n   \n    ///////////////////////////////////////////////////\n    //////////// owner section ////////////////////////\n    /**\n     * @param recipient recipient\n     */\n    function addRecipient(\n        address recipient\n    ) \n        external \n        onlyOwner \n    {\n        if (recipients[recipient].exists == false) {\n            recipients[recipient].exists = true;\n            recipients[recipient].addr = recipient;\n            recipients[recipient].amountMax = 0;\n            recipients[recipient].amountClaimed = 0;\n            recipients[recipient].amountPaid = 0;\n            \n            \n           // recipients[recipient].gradual = false;\n\n        }\n        \n    }\n\n    /**\n     * @dev setup trusted forwarder address\n     * @param forwarder trustedforwarder's address to set\n     * @custom:shortd setup trusted forwarder\n     * @custom:calledby owner\n     */\n    function setTrustedForwarder(\n        address forwarder\n    ) \n        public \n        override\n        onlyOwner \n        //excludeTrustedForwarder \n    {\n        require(owner() != forwarder, \"FORWARDER_CAN_NOT_BE_OWNER\");\n        _setTrustedForwarder(forwarder);\n    }\n\n    \n    /**\n     * Setup restrictions by owner\n     * @param recipient recipient\n     * @param restrictions restrictions\n     * param amount amount\n     * param untilTime untilTime in unixtimestamp\n     * param gradual gradual\n     */\n    function setLockup(\n        address recipient,\n        RestrictParam[] memory restrictions\n    ) \n        external \n        onlyOwner \n        recipientExists(recipient)\n    {\n\n        //uint256 restrictionIndexesLength = recipients[recipient].restrictionIndexes.length();\n\n        for (uint256 i = 0; i < restrictions.length; i++ ) {\n            // add to amountMax\n            recipients[recipient].amountMax = recipients[recipient].amountMax + restrictions[i].amount;\n            \n            \n            // adding restriction\n            require(restrictions[i].untilTime > block.timestamp, \"untilTime\");\n            \n            recipients[recipient].restrictions.push(Restrict({\n                amount: restrictions[i].amount,\n                startTime: block.timestamp,\n                untilTime: restrictions[i].untilTime,\n                gradual: restrictions[i].gradual,\n                fraction: restrictions[i].fraction\n            }));\n            \n            // recipients[recipient].restrictions[i+restrictionIndexesLength].amount = restrictions[i].amount;\n            // recipients[recipient].restrictions[i+restrictionIndexesLength].startTime = block.timestamp;\n            // recipients[recipient].restrictions[i+restrictionIndexesLength].untilTime = restrictions[i].untilTime;\n            // recipients[recipient].restrictions[i+restrictionIndexesLength].gradual = restrictions[i].gradual;\n            // recipients[recipient].restrictions[i+restrictionIndexesLength].fraction = restrictions[i].fraction;\n            \n            \n        }\n    }\n    \n    /** allow manager pay some funds to recipients\n     * @param recipient recipient\"s address\n     * @param manager manager\"s address\n     */\n    function addManager(\n        address recipient, \n        address manager\n    ) \n        external \n        onlyOwner \n    {\n        recipients[recipient].managers.add(manager);\n    }\n    \n    /** disallow manager pay some funds to recipients\n     * @param recipient recipient\"s address\n     * @param manager manager\"s address\n     */\n    function removeManager(\n        address recipient, \n        address manager\n    ) \n        external \n        onlyOwner \n    {\n        recipients[recipient].managers.remove(manager);\n    }\n    \n    ///////////////////////////////////////////////////\n    //////////// managers section /////////////////////\n    \n    /**\n     * @param recipient recipient\"s address\n     * @param amount amount to pay \n     */\n    function pay(\n        address recipient, \n        uint256 amount\n    ) \n        external \n        recipientExists(recipient)\n        canManage(recipient)\n    {\n        \n        (uint256 maximum, uint256 claimed, uint256 locked, uint256 allowedByManager, ) = _viewLockup(recipient);\n        \n        uint256 availableUnlocked = maximum - claimed - locked;\n        \n        require (amount > 0, \"Amount can not be a zero\");\n\n        require (amount <= availableUnlocked, \"AMOUNT_EXCEEDS_BALANCE\");\n        require (amount <= availableUnlocked - allowedByManager, \"AMOUNT_EXCEEDS_RATE\");\n        \n        recipients[recipient].amountPaid = recipients[recipient].amountPaid + amount;\n        \n    }\n    \n    ///////////////////////////////////////////////////\n    //////////// recipients section ///////////////////\n\n    function claim(\n    ) \n        external \n        recipientExists(_msgSender())\n        nonReentrant()\n    {\n        address ms = _msgSender();\n        \n        _cleanLockup(ms);\n        (,, uint256 locked, uint256 allowedByManager, ) = _viewLockup(ms);\n        \n        uint256 amount = (recipients[ms].managers.length() > 0 && recipients[ms].managers.at(0) == ms)\n            ? locked : allowedByManager;\n        \n        // 40 20 0 10 => 40 30 0 0\n        require (amount > 0, \"NOTHING_AVAILABLE_TO_CLAIM\");\n\n        recipients[ms].amountPaid = 0;\n        recipients[ms].amountClaimed = recipients[ms].amountClaimed + amount;\n        bool success = _claim(ms, amount);\n\n        require(success == true, \"NOT_ENOUGH_FUNDS\");\n        \n    }\n    \n    \n    \n    /**\n     * View restrictions setup by owner\n     * @param recipient recipient\n     * @return maximum maximum\n     * @return claimed claimed\n     * @return locked locked\n     * @return allowedByManager allowedByManager\n     * \n     */\n    function viewLockup(\n        address recipient\n    ) \n        external \n        view\n        returns (\n            uint256 maximum,\n            uint256 claimed,\n            uint256 locked,\n            uint256 allowedByManager\n        )\n    {\n        require(recipients[recipient].exists == true, \"NO_SUCH_RECIPIENT\");\n        (maximum, claimed, locked,allowedByManager,) = _viewLockup(recipient);\n    }\n    \n    /**\n     * @param recipient recipient\"s address\n     */\n    function _claim(\n        address recipient, \n        uint256 amount\n    ) \n        internal \n        returns(\n            bool success\n        ) \n    {\n        uint256 balance = (tokenAddr == address(0))\n            ? address(this).balance\n            : IERC20Upgradeable(tokenAddr).balanceOf(address(this));\n\n\n        if (balance < amount) {\n            success = false;\n        } else {\n            if (tokenAddr == address(0)) {\n                address payable addr = payable(recipient);\n                success = addr.send(amount);\n            } else {\n                success = IERC20Upgradeable(tokenAddr).transfer(recipient, amount);\n            }\n        }\n    }\n    \n    function _calcLock(\n        Restrict[] memory restrictions\n    ) \n        internal \n        view \n        returns(uint256 locked) \n    {\n        locked = 0;\n        uint256 fundsPerSecond;\n        for (uint256 i = 0; i < restrictions.length; i++ ) {\n            if (restrictions[i].untilTime > block.timestamp) {\n                uint256 amount = restrictions[i].amount;\n                \n                if (restrictions[i].fraction > 0) {\n                    uint256 balance = (tokenAddr == address(0))\n                        ? address(this).balance\n                        : IERC20Upgradeable(tokenAddr).balanceOf(address(this));\n                    uint256 relativeAmount = restrictions[i].fraction * balance / FRACTION;\n\n                    if (relativeAmount < amount || amount == 0) {\n                        amount = relativeAmount;\n                    }\n                }\n                if (restrictions[i].gradual == true) {\n                    fundsPerSecond = amount / (restrictions[i].untilTime - restrictions[i].startTime);\n                    locked = locked + (\n                        fundsPerSecond * (restrictions[i].untilTime - block.timestamp)\n                    );\n                    \n                } else {\n                    locked = locked + amount;\n                \n                }\n            }\n        }\n    \n    }\n\n    /**\n    * @dev clean up restriction array if untilTime <= block.timestamp \n    */\n    function _cleanLockup(\n        address recipient\n    ) \n        internal \n    {\n        uint256 len = recipients[recipient].restrictions.length;\n\n        if (len == 0) {\n            return;\n        }\n\n        uint256 leni = len;\n        for (uint256 i = len; i != 0; i--) {\n            \n            if (recipients[recipient].restrictions[i-1].untilTime <= block.timestamp) {\n\n                // 1,2,3,4,x --> 1,2,3,4\n                // 1,2,x,4,5 --> 1,2,5,4\n\n                delete recipients[recipient].restrictions[i-1];\n                //test[(i-1)] = test[leni-1];\n                recipients[recipient].restrictions[i-1] = recipients[recipient].restrictions[leni-1];\n                leni=leni-1;\n                recipients[recipient].restrictions.pop();\n\n       \n                // recipients[recipient].restrictions.push(Restrict({\n                //     amount: restrictions[i].amount,\n                //     startTime: block.timestamp,\n                //     untilTime: restrictions[i].untilTime,\n                //     gradual: restrictions[i].gradual,\n                //     fraction: restrictions[i].fraction\n                // }));\n            }\n        }\n    }\n    \n    /**\n     * @param recipient recipient\"s address\n     */\n    function _viewLockup(\n        address recipient\n    ) \n        internal \n        view\n        returns (\n            uint256 maximum,\n            uint256 claimed,\n            uint256 locked,\n            uint256 allowedByManager,\n            Restrict[] memory restrictions\n        )\n    {\n        \n        maximum = recipients[recipient].amountMax;\n        claimed = recipients[recipient].amountClaimed;\n        locked = _calcLock(recipients[recipient].restrictions);\n        allowedByManager = recipients[recipient].amountPaid;\n        restrictions = recipients[recipient].restrictions;\n        \n    }\n\n    function _msgSender(\n    ) \n        internal \n        view \n        virtual\n        override(ContextUpgradeable, TrustedForwarder)\n        returns (address signer) \n    {\n        return TrustedForwarder._msgSender();\n    }\n\n    \n    function _transferOwnership(\n        address newOwner\n    ) \n        internal \n        virtual \n        override\n    {\n        super._transferOwnership(newOwner);\n        _setTrustedForwarder(address(0));\n    }\n\n\n}\n"
      },
      "contracts/base/UBIBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\nimport \"@artman325/community/contracts/interfaces/ICommunity.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nabstract contract UBIBase is Initializable {\n    ICommunity internal community;\n    uint8 internal ubiRole;\n\n    function actualizeUBI(\n    ) \n        external \n    {\n        _actualizeUBI(msg.sender);\n    }\n\n    function actualizeUBI(\n        address account\n    ) \n        external \n    {\n        _actualizeUBI(account);\n    }\n\n    function __UBIBase_init(\n        address communityAddress,\n        uint8 role\n    )  \n        internal\n        onlyInitializing\n    {\n        community = ICommunity(communityAddress);\n        ubiRole = role;\n    }\n\n    function _checkCommunityRole(address account, uint8 roleIndex) private view {\n        require(community.hasRole(account, roleIndex), \"Sender has not in accessible List\");\n    }\n\n    function canRecord(address account, uint8 role) internal view {\n        _checkCommunityRole(account, role);\n    }\n    \n    function canObtainUBI(address account) internal view {\n        _checkCommunityRole(account, ubiRole);\n    }\n    \n    function _actualizeUBI(address account) internal  virtual returns(uint256 ubi);\n\n}"
      },
      "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../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 anymore. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby removing 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"
      },
      "@artman325/trustedforwarder/contracts/TrustedForwarder.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nabstract contract TrustedForwarder is Initializable {\n\n    address private _trustedForwarder;\n\n    /**\n     * @dev Initializes the contract setting the deployer as the initial owner.\n     */\n    function __TrustedForwarder_init() internal onlyInitializing {\n        _trustedForwarder = address(0);\n    }\n\n\n    /**\n    * @dev setup trusted forwarder address\n    * @param forwarder trustedforwarder's address to set\n    * @custom:shortd setup trusted forwarder\n    * @custom:calledby owner\n    */\n    function _setTrustedForwarder(\n        address forwarder\n    ) \n        internal \n      //  onlyOwner \n        //excludeTrustedForwarder \n    {\n        //require(owner() != forwarder, \"FORWARDER_CAN_NOT_BE_OWNER\");\n        _trustedForwarder = forwarder;\n    }\n    function setTrustedForwarder(address forwarder) public virtual;\n    /**\n    * @dev checking if forwarder is trusted\n    * @param forwarder trustedforwarder's address to check\n    * @custom:shortd checking if forwarder is trusted\n    */\n    function isTrustedForwarder(\n        address forwarder\n    ) \n        external\n        view \n        returns(bool) \n    {\n        return _isTrustedForwarder(forwarder);\n    }\n\n    /**\n    * @dev implemented EIP-2771\n    */\n    function _msgSender(\n    ) \n        internal \n        view \n        virtual\n        returns (address signer) \n    {\n        signer = msg.sender;\n        if (msg.data.length>=20 && _isTrustedForwarder(signer)) {\n            assembly {\n                signer := shr(96,calldataload(sub(calldatasize(),20)))\n            }\n        }    \n    }\n\n    // function transferOwnership(\n    //     address newOwner\n    // ) public \n    //     virtual \n    //     override \n    //     onlyOwner \n    // {\n    //     require(msg.sender != _trustedForwarder, \"DENIED_FOR_FORWARDER\");\n    //     if (newOwner == _trustedForwarder) {\n    //         _trustedForwarder = address(0);\n    //     }\n    //     super.transferOwnership(newOwner);\n        \n    // }\n\n    function _isTrustedForwarder(\n        address forwarder\n    ) \n        internal\n        view \n        returns(bool) \n    {\n        return forwarder == _trustedForwarder;\n    }\n\n\n  \n\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) external returns (bool);\n}\n"
      },
      "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return 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(\n        address target,\n        bytes memory data,\n        uint256 value\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (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 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/security/ReentrancyGuardUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../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 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/utils/ContextUpgradeable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../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    /**\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/proxy/utils/Initializable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (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 * ```\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\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"
      },
      "@artman325/community/contracts/interfaces/ICommunity.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.11;\n\ninterface ICommunity {\n    \n    function initialize(\n        address implState,\n        address implView,\n        address hook, \n        address costManager, \n        string memory name, \n        string memory symbol\n    ) external;\n    \n    function addressesCount(uint8 roleIndex) external view returns(uint256);\n    function getRoles(address[] calldata accounts)external view returns(uint8[][] memory);\n    function getAddresses(uint8[] calldata rolesIndexes) external view returns(address[][] memory);\n    function hasRole(address account, uint8 roleIndex) external view returns(bool);\n    function grantRoles(address[] memory accounts, uint8[] memory roleIndexes) external;\n    function revokeRoles(address[] memory accounts, uint8[] memory roleIndexes) external;\n}"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 100
      },
      "metadata": {
        "bytecodeHash": "none",
        "useLiteralContent": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}