// File: Address.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

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

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

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

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

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

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

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: Context.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: EnumerableMap.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./EnumerableSet.sol";

/**
 * @dev Library for managing an enumerable variant of Solidity's
 * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
 * type.
 *
 * Maps have the following properties:
 *
 * - Entries are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Entries are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableMap for EnumerableMap.UintToAddressMap;
 *
 *     // Declare a set state variable
 *     EnumerableMap.UintToAddressMap private myMap;
 * }
 * ```
 *
 * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
 * supported.
 */
library EnumerableMap {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Map type with
    // bytes32 keys and values.
    // The Map implementation uses private functions, and user-facing
    // implementations (such as Uint256ToAddressMap) are just wrappers around
    // the underlying Map.
    // This means that we can only create new EnumerableMaps for types that fit
    // in bytes32.

    struct Map {
        // Storage of keys
        EnumerableSet.Bytes32Set _keys;

        mapping (bytes32 => bytes32) _values;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
        map._values[key] = value;
        return map._keys.add(key);
    }

    /**
     * @dev Removes a key-value pair from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function _remove(Map storage map, bytes32 key) private returns (bool) {
        delete map._values[key];
        return map._keys.remove(key);
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function _contains(Map storage map, bytes32 key) private view returns (bool) {
        return map._keys.contains(key);
    }

    /**
     * @dev Returns the number of key-value pairs in the map. O(1).
     */
    function _length(Map storage map) private view returns (uint256) {
        return map._keys.length();
    }

   /**
    * @dev Returns the key-value pair stored at position `index` in the map. O(1).
    *
    * Note that there are no guarantees on the ordering of entries inside the
    * array, and it may change when more entries are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
        bytes32 key = map._keys.at(index);
        return (key, map._values[key]);
    }

    /**
     * @dev Tries to returns the value associated with `key`.  O(1).
     * Does not revert if `key` is not in the map.
     */
    function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
        bytes32 value = map._values[key];
        if (value == bytes32(0)) {
            return (_contains(map, key), bytes32(0));
        } else {
            return (true, value);
        }
    }

    /**
     * @dev Returns the value associated with `key`.  O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function _get(Map storage map, bytes32 key) private view returns (bytes32) {
        bytes32 value = map._values[key];
        require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
        return value;
    }

    /**
     * @dev Same as {_get}, with a custom error message when `key` is not in the map.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {_tryGet}.
     */
    function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
        bytes32 value = map._values[key];
        require(value != 0 || _contains(map, key), errorMessage);
        return value;
    }

    // UintToAddressMap

    struct UintToAddressMap {
        Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
        return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
        return _remove(map._inner, bytes32(key));
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
        return _contains(map._inner, bytes32(key));
    }

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToAddressMap storage map) internal view returns (uint256) {
        return _length(map._inner);
    }

   /**
    * @dev Returns the element stored at position `index` in the set. O(1).
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
        (bytes32 key, bytes32 value) = _at(map._inner, index);
        return (uint256(key), address(uint160(uint256(value))));
    }

    /**
     * @dev Tries to returns the value associated with `key`.  O(1).
     * Does not revert if `key` is not in the map.
     *
     * _Available since v3.4._
     */
    function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
        (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
        return (success, address(uint160(uint256(value))));
    }

    /**
     * @dev Returns the value associated with `key`.  O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
        return address(uint160(uint256(_get(map._inner, bytes32(key)))));
    }

    /**
     * @dev Same as {get}, with a custom error message when `key` is not in the map.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryGet}.
     */
    function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
        return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
    }
}

// File: EnumerableSet.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }


    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
}

// File: ERC1155.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./IERC1155MetadataURI.sol";
import "./Address.sol";
import "./Context.sol";
import "./ERC165.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 *
 * _Available since v3.1._
 */
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
    using Address for address;

    // Mapping from token ID to account balances
    mapping (uint256 => mapping(address => uint256)) private _balances;

    // Mapping from account to operator approvals
    mapping (address => mapping(address => bool)) private _operatorApprovals;

    // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
    string private _uri;

    /**
     * @dev See {_setURI}.
     */
    constructor (string memory uri_) {
        _setURI(uri_);
    }

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

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256) public view virtual override returns (string memory) {
        return _uri;
    }

    /**
     * @dev See {IERC1155-balanceOf}.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
        require(account != address(0), "ERC1155: balance query for the zero address");
        return _balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] memory accounts,
        uint256[] memory ids
    )
        public
        view
        virtual
        override
        returns (uint256[] memory)
    {
        require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts[i], ids[i]);
        }

        return batchBalances;
    }

    /**
     * @dev See {IERC1155-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        require(_msgSender() != operator, "ERC1155: setting approval status for self");

        _operatorApprovals[_msgSender()][operator] = approved;
        emit ApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC1155-isApprovedForAll}.
     */
    function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[account][operator];
    }

    /**
     * @dev See {IERC1155-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    )
        public
        virtual
        override
    {
        require(to != address(0), "ERC1155: transfer to the zero address");
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: caller is not owner nor approved"
        );

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
        _balances[id][from] = fromBalance - amount;
        _balances[id][to] += amount;

        emit TransferSingle(operator, from, to, id, amount);

        _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
    }

    /**
     * @dev See {IERC1155-safeBatchTransferFrom}.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    )
        public
        virtual
        override
    {
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");
        require(
            from == _msgSender() || isApprovedForAll(from, _msgSender()),
            "ERC1155: transfer caller is not owner nor approved"
        );

        address operator = _msgSender();

        _beforeTokenTransfer(operator, from, to, ids, amounts, data);

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
            _balances[id][from] = fromBalance - amount;
            _balances[id][to] += amount;
        }

        emit TransferBatch(operator, from, to, ids, amounts);

        _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the amounts in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        _uri = newuri;
    }

    /**
     * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
        require(account != address(0), "ERC1155: mint to the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);

        _balances[id][account] += amount;
        emit TransferSingle(operator, address(0), account, id, amount);

        _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);

        for (uint i = 0; i < ids.length; i++) {
            _balances[ids[i]][to] += amounts[i];
        }

        emit TransferBatch(operator, address(0), to, ids, amounts);

        _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
    }

    /**
     * @dev Destroys `amount` tokens of token type `id` from `account`
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens of token type `id`.
     */
    function _burn(address account, uint256 id, uint256 amount) internal virtual {
        require(account != address(0), "ERC1155: burn from the zero address");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");

        uint256 accountBalance = _balances[id][account];
        require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
        _balances[id][account] = accountBalance - amount;

        emit TransferSingle(operator, account, address(0), id, amount);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     */
    function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
        require(account != address(0), "ERC1155: burn from the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

        _beforeTokenTransfer(operator, account, address(0), ids, amounts, "");

        for (uint i = 0; i < ids.length; i++) {
            uint256 id = ids[i];
            uint256 amount = amounts[i];

            uint256 accountBalance = _balances[id][account];
            require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
            _balances[id][account] = accountBalance - amount;
        }

        emit TransferBatch(operator, account, address(0), ids, amounts);
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning, as well as batched variants.
     *
     * The same hook is called on both single and batched variants. For single
     * transfers, the length of the `id` and `amount` arrays will be 1.
     *
     * Calling conditions (for each `id` and `amount` pair):
     *
     * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * of token type `id` will be  transferred to `to`.
     * - When `from` is zero, `amount` tokens of token type `id` will be minted
     * for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
     * will be burned.
     * - `from` and `to` are never both zero.
     * - `ids` and `amounts` have the same, non-zero length.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    )
        internal
        virtual
    { }

    function _doSafeTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    )
        private
    {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
                if (response != IERC1155Receiver(to).onERC1155Received.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _doSafeBatchTransferAcceptanceCheck(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    )
        private
    {
        if (to.isContract()) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
                if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
                    revert("ERC1155: ERC1155Receiver rejected tokens");
                }
            } catch Error(string memory reason) {
                revert(reason);
            } catch {
                revert("ERC1155: transfer to non ERC1155Receiver implementer");
            }
        }
    }

    function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
        uint256[] memory array = new uint256[](1);
        array[0] = element;

        return array;
    }
}

// File: ERC1155Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC1155Receiver.sol";
import "./ERC165.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId
            || super.supportsInterface(interfaceId);
    }
}

// File: ERC165.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

// File: IERC1155.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}

// File: IERC1155MetadataURI.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC1155.sol";

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

// File: IERC1155Receiver.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {

    /**
        @dev Handles the receipt of a single ERC1155 token type. This function is
        called at the end of a `safeTransferFrom` after the balance has been updated.
        To accept the transfer, this must return
        `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
        (i.e. 0xf23a6e61, or its own function selector).
        @param operator The address which initiated the transfer (i.e. msg.sender)
        @param from The address which previously owned the token
        @param id The ID of the token being transferred
        @param value The amount of tokens being transferred
        @param data Additional data with no specified format
        @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
    */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    )
        external
        returns(bytes4);

    /**
        @dev Handles the receipt of a multiple ERC1155 token types. This function
        is called at the end of a `safeBatchTransferFrom` after the balances have
        been updated. To accept the transfer(s), this must return
        `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
        (i.e. 0xbc197c81, or its own function selector).
        @param operator The address which initiated the batch transfer (i.e. msg.sender)
        @param from The address which previously owned the token
        @param ids An array containing ids of each token being transferred (order and length must match values array)
        @param values An array containing amounts of each token being transferred (order and length must match ids array)
        @param data Additional data with no specified format
        @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
    */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    )
        external
        returns(bytes4);
}

// File: IERC1155_EXT.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "./IERC1155.sol";

interface IERC1155_EXT is IERC1155 {
    //function mint(address to, uint256 value, bytes memory data) external;
    function mint(
        address to,
        uint256 value,
        string calldata _hash,
        bytes memory data
    ) external;

    function mintBatch(
        address to,
        uint256[] memory values,
        string[] memory _hash,
        bytes memory data
    ) external;

    function getHashFromTokenID(uint256 tokenId)
        external
        view
        returns (string memory);

    function getTokenIdFromHash(string memory) external view returns (uint256);

    function ownerOf(address owner, uint256 id) external view returns (bool);

    function getTokenAmount(address owner) external view returns (uint256);

    function getAllTokenIds(address owner)
        external
        view
        returns (uint256[] memory);
}

// File: IERC165.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC20 {
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Transfer(address indexed from, address indexed to, uint256 value);

    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);
    function totalSupply() external view returns (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 value) external returns (bool);
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}


// File: IMultiERC20Handler.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./IERC20.sol";

interface IMultiERC20Handler {

    function registerERC20Token(address value) external;

    function removeERC20Token(uint256 key) external;

    function isValidToken(address value) external view returns (bool);

    function isValidSymbol(string memory symbol) external view returns (bool);

    function isValidSymbols(string[] memory symbols) external view returns (bool);

    function ERC20TokensContainsKey(uint256 key) external view returns (bool);

    function ERC20TokensLength() external view returns (uint256);

    function ERC20TokensAt(uint256 index) external view returns (uint256 key, address value);

    function tryGetERC20Token(uint256 key) external view returns (bool, address);

    function getERC20Token(uint256 key) external view returns (address);

    function getERC20TokenWithMessage(uint256 key, string calldata errorMessage) external view returns (address);

    function symbolToIERC20(string memory symbol) external view returns (IERC20);

    function symbolToAddress(string memory symbol) external view returns (address);

    function getAllSymbols() external view returns (string[] memory);

    function getCurrentKeys() external view returns (uint256[] memory);
}

// File: Math.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

library Math {
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }
}

// File: Migrations.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Migrations {
  address public owner = msg.sender;
  uint public last_completed_migration;

  modifier restricted() {
    require(
      msg.sender == owner,
      "This function is restricted to the contract's owner"
    );
    _;
  }

  function setCompleted(uint completed) public restricted {
    last_completed_migration = completed;
  }
}

// File: MuCitadel.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155.sol";
import "./EnumerableSet.sol";
import "./Ownable.sol";
import "./IERC1155_EXT.sol";


contract MuCitadel is IERC1155_EXT, ERC1155, Ownable {
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableSet for EnumerableSet.AddressSet;

    uint256 public nextID = 1;

    mapping(uint256 => address) internal _tokenMaker;
    mapping(uint256 => uint256) internal _tokenInitAmount;

    mapping(uint256 => EnumerableSet.AddressSet) internal _tokenIdToOwners;
    mapping(address => EnumerableSet.UintSet) internal _ownedTokens;
    mapping(uint256 => string) internal _tokenIdToHash;
    mapping(string => uint256) public override getTokenIdFromHash;
    mapping(uint256 => uint256) internal _tokenInitAmountHandler;
    mapping(string => bool) internal existHash;


    constructor() ERC1155("") {
        // solhint-disable-previous-line no-empty-blocks
    }

    function mint(
        address to,
        uint256 value,
        string memory _hash,
        bytes memory data
    ) external override {
        require(!existHash[_hash],'Invalid hash');
        _mint(to, nextID, value, data);
        processSetHashFromMint(_hash);
    }

    function mintBatch(
        address to,
        uint256[] memory values,
        string[] memory _hash,
        bytes memory data
    ) external override {
        require(values.length > 0, "");
        require(values.length == _hash.length, "");
        uint256[] memory ids = new uint256[](_hash.length);
        for (uint256 i; i < _hash.length; ++i) {
            require(!existHash[_hash[i]],'Invalid hash');
            ids[i] = nextID;
            processSetHashFromMint(_hash[i]);
        }
        _mintBatch(to, ids, values, data);
    }

    function burn(
        uint256 id,
        uint256 value
    ) public  {
        require(_ownedTokens[_msgSender()].contains(id),"Not Token Owner");
        _burn(_msgSender(), id, value);
        burnHashHandler(id,value);
    }

    function burnHashHandler(uint256 id,uint256 value ) internal {
        _tokenInitAmountHandler[id] =  _tokenInitAmountHandler[id]  - value;
        if(_tokenInitAmountHandler[id] ==0){
        string memory oldHash =  _tokenIdToHash[id];
        delete getTokenIdFromHash[oldHash];
        delete existHash[oldHash];
        delete _tokenIdToHash[id];
        }
    }


    function ownerOf(address owner, uint256 id)
        external
        view
        override
        returns (bool)
    {
        return _ownedTokens[owner].contains(id);
    }

    function getHashFromTokenID(uint256 tokenId)
        public
        view
        override
        returns (string memory)
    {
        return _tokenIdToHash[tokenId];
    }

    function getTokenAmount(address owner)
        external
        view
        override
        returns (uint256)
    {
        return _ownedTokens[owner].length();
    }

    function getHashBatch(uint256[] memory tokenIds)
        external
        view
        returns (string[] memory)
    {
        string[] memory tokenHash = new string[](tokenIds.length);
        for (uint256 i = 0; i < tokenIds.length; i++) {
            tokenHash[i] = getHashFromTokenID(tokenIds[i]);
        }
        return tokenHash;
    }

    function getOwnersFromTokenId(uint256 tokenId)
        external
        view
        returns (address[] memory)
    {
        uint256 index = _tokenIdToOwners[tokenId].length();
        address[] memory owners = new address[](index);
        for (uint256 i; i < index; i++) {
            owners[i] = _tokenIdToOwners[tokenId].at(i);
        }
        return owners;
    }

    function getTokenMaker(uint256 tokenId) external view returns (address) {
        return _tokenMaker[tokenId];
    }

    function getTokenInitAmount(uint256 tokenId)
        external
        view
        returns (uint256)
    {
        return _tokenInitAmount[tokenId];
    }

    function getAllTokenHash(address owner)
        external
        view
        returns (string[] memory)
    {
        uint256[] memory tokenIds = this.getAllTokenIds(owner);
        string[] memory tokenHash = new string[](tokenIds.length);
        for (uint256 i = 0; i < tokenIds.length; i++) {
            tokenHash[i] = getHashFromTokenID(tokenIds[i]);
        }
        return tokenHash;
    }

    function getAllTokenIds(address owner)
        external
        view
        override
        returns (uint256[] memory)
    {
        uint256 index = _ownedTokens[owner].length();
        uint256[] memory tokenIds = new uint256[](index);
        for (uint256 i = 0; i < index; i++) {
            tokenIds[i] = _ownedTokens[owner].at(i);
        }
        return tokenIds;
    }

    function processSetHashFromMint(string memory newHash) private {
        require(bytes(newHash).length > 0, "hash_ can not be empty string");
        setHashToTokenID(nextID, newHash);
        nextID++;
    }

    function setHashToTokenID(uint256 tokenId, string memory newHash) internal {
        _tokenIdToHash[tokenId] = newHash;
        existHash[newHash]=true;
        getTokenIdFromHash[newHash] = tokenId;
    }

    function updateTokenID(
        address from,
        address to,
        uint256 id,
        uint256 amount
    ) internal {
        if (from == address(0)) {
            _tokenMaker[id] = to;
            _tokenInitAmount[id] = amount;
            _tokenInitAmountHandler[id] = amount;
        }

        if (from != address(0)) {
            uint256 fromBalance = balanceOf(from, id);
            if (amount == fromBalance) {
                _ownedTokens[from].remove(id);
                _tokenIdToOwners[id].remove(from);
            }
        }

        if (to != address(0)) {
            _ownedTokens[to].add(id);
            _tokenIdToOwners[id].add(to);
        }
    }

    function _beforeTokenTransfer(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual override {
        for (uint256 i = 0; i < ids.length; i++) {
            updateTokenID(from, to, ids[i], amounts[i]);
        }
    }
}
// File: MuCitadelMarketPlace.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./EnumerableMap.sol";
import "./Ownable.sol";
import "./IERC1155_EXT.sol";
import "./IMultiERC20Handler.sol";
import "./SafeMath.sol";
import "./SafeERC20.sol";
import "./Math.sol";
import "./ERC1155Receiver.sol";

// 0xc4E523243551359d71a2f2986D0EC3c388e7191B
// binance - 0xF9a34a112357959a465b6d250dab294EDF69B72e

contract MuCitadelMarketPlace is  Ownable, ERC1155Receiver {
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableMap for EnumerableMap.UintToAddressMap;
    using SafeERC20 for IERC20;
    using SafeMath for uint256;
    using Address for address;

    IERC1155_EXT public nft;
    IMultiERC20Handler public ERC20Handler;

    uint256 private order;

    EnumerableSet.UintSet internal _asksMap;

    mapping(uint256 => Order) private _tokenSellers;

    address payable public feeAddr;
	// a fee of 1 equals 0.1%, 10 to 1%, 100 to 10%, 1000 to 100%
    uint256 public makerFee;
	uint256 public takerFee;
	uint256 constant public PERCENTS_DIVIDER = 1000;

    mapping(address => EnumerableSet.UintSet) private _userSellingOrder;

	IERC20 public priorityToken;

    struct TokenPrice {
        string symbol;
        uint256 price;
    }

    struct OrderShow {
        address owner;
        string _hash;
        uint256 quantity;
        uint256 tokenID;
        uint256 ethPrice;
        TokenPrice[] tokenPrices;
    }

    struct Order {
        address owner;
        uint256 quantity;
        uint256 tokenID;
        uint256 ethPrice;
        mapping(string => uint256) tokenPrices;
    }

    event Ask(
        address indexed seller,
        uint256 indexed order,
        uint256 ethPrice,
        TokenPrice[] indexed tokenPrices,
		uint256 fee
    );
    event Trade(
        address indexed seller,
        address indexed buyer,
        uint256 tokenId,
        bool byToken,
        string symbol,
        uint256 quantity,
        uint256 price,
        uint256 fee
    );
    event CancelSellToken(address indexed seller, uint256 indexed order);
    event FeeAddressTransferred(
        address indexed previousOwner,
        address indexed newOwner
    );

	event SetMakerFeePercent(address indexed setBy, uint256 oldFeePercent, uint256 newFeePercent);

    event SetTakerFeeFeePercent(address indexed setBy, uint256 oldFeePercent, uint256 newFeePercent);

    event setPrices(
        address indexed seller,
        uint256 indexed order,
        uint256 ethPrice,
        TokenPrice[] indexed tokenPrices
    );

    event SetPriorityToken (string priorityToken);

    constructor(
        address _nftAddress,
        address _tokenHandler,
        address _priorityToken,
        address _feeAddr,
		uint256 _makerFee,
        uint256 _takerFee
    ) {
        require(_nftAddress.isContract() && _nftAddress != address(0) && _nftAddress != address(this));
        require(_tokenHandler.isContract() && _tokenHandler != address(this));
        require(_priorityToken.isContract());
        setPriorityToken(_priorityToken);
        nft = IERC1155_EXT(_nftAddress);
        ERC20Handler = IMultiERC20Handler(_tokenHandler);
        feeAddr = payable(_feeAddr);
		makerFee = _makerFee;
        takerFee = _takerFee;

        emit SetMakerFeePercent(_msgSender(), 0, _takerFee);
        emit SetTakerFeeFeePercent(_msgSender(), 0, _makerFee);
    }

    function setCurrentPrice(
        uint256 _order,
        uint256 ethPrice,
        string[] memory _symbols,
        uint256[] memory _prices
    ) external  {
        require(
            _userSellingOrder[_msgSender()].contains(_order),
            "Only Seller can update price"
        );
        require(
            _symbols.length == _prices.length,
            "diferent number of symbols and prices"
        );
        Order storage order_ = _tokenSellers[_order];
        order_.ethPrice = ethPrice;
        uint256 priceCount = ethPrice;
        TokenPrice[] memory PriceDAta = new TokenPrice[](_prices.length);
        if (_symbols.length > 0) {
            for (uint256 i = 0; i < _prices.length; i++) {
                require(
                    ERC20Handler.isValidSymbol(_symbols[i]),
                    "token is not valid"
                );
                order_.tokenPrices[_symbols[i]] = _prices[i];
                priceCount = priceCount.add(_prices[i]);
                PriceDAta[i].price = _prices[i];
                PriceDAta[i].symbol = _symbols[i];
            }
        }
        require(ethPrice > 0, "Price must be granter than zero");

        emit setPrices(order_.owner, _order, ethPrice, PriceDAta);
    }

    function readyToSellToken (
        uint256 _tokenId,
        uint256 _quantity,
        uint256 ethPrice,
        string[] memory _symbols,
        uint256[] memory _prices
    ) external  payable {
        readyToSellTokenTo(
            _tokenId,
            _quantity,
            ethPrice,
            _symbols,
            _prices,
            _msgSender()
        );
    }

	//this function is used to change the priority token.
    function setPriorityToken(address Addrs) public {
        priorityToken = IERC20(Addrs);
        emit SetPriorityToken(PRIORITY_TOKEN());
    }

    function PRIORITY_TOKEN() public view returns(string memory) {
        return priorityToken.symbol();
    }

    function readyToSellTokenTo(
        uint256 _tokenId,
        uint256 _quantity,
        uint256 ethPrice,
        string[] memory _symbols,
        uint256[] memory _prices,
        address _from
    ) internal  {
        require(
            nft.ownerOf(_from, _tokenId),
            "Only Token Owner can sell token"
        );
        require(
            _symbols.length == _prices.length,
            "diferent number of symbols and prices"
        );
        require(_quantity > 0, "insufficient quantity");

        TokenPrice[] memory PriceDAta = new TokenPrice[](_prices.length);
        order++;
        Order storage nft_ = _tokenSellers[order];
        if (_prices.length == 0) {
            require(ethPrice > 0, "Price must be granter than zero");
        } else {
            for (uint256 i = 0; i < _prices.length; i++) {
                require(_prices[i] > 0, "Price must be granter than zero");
                require(
                    ERC20Handler.isValidSymbol(_symbols[i]),
                    "token is not valid"
                );
                PriceDAta[i].price = _prices[i];
                PriceDAta[i].symbol = _symbols[i];
                nft_.tokenPrices[_symbols[i]] = _prices[i];
            }
        }

		bool hasPriorityToken = nft_.tokenPrices[PRIORITY_TOKEN()] > 0;
		bool hasEthPrice = ethPrice > 0;
		uint256 feeAmt;
		if(hasEthPrice && !hasPriorityToken) {
			feeAmt = ethPrice.mul(makerFee).div(PERCENTS_DIVIDER);
			require(msg.value == feeAmt, "invalid pay amount");
            if (feeAmt > 0) {
                feeAddr.transfer(feeAmt);
            }
		}
		else {
			require(msg.value == 0, "invalid pay amount");
			string memory _symbol;
			if(!hasPriorityToken) {
				_symbol = _symbols[0];
				feeAmt = _prices[0].mul(makerFee).div(PERCENTS_DIVIDER);
			}
			else {
				_symbol = PRIORITY_TOKEN();
				feeAmt = nft_.tokenPrices[_symbol].mul(makerFee).div(PERCENTS_DIVIDER);
			}

			IERC20 token = ERC20Handler.symbolToIERC20(_symbol);
			if(feeAmt > 0) {
				token.safeTransferFrom(_from, feeAddr, feeAmt);
            }

		}

        _asksMap.add(order);
        nft_.owner = _from;
        nft_.tokenID = _tokenId;
        nft_.quantity = _quantity;
        nft_.ethPrice = ethPrice;
        _userSellingOrder[_from].add(order);

        nft.safeTransferFrom(_from, address(this), _tokenId, _quantity, "0x");

        emit Ask(_from, order, ethPrice, PriceDAta, feeAmt);
    }

    function buyToken(
        uint256 _order,
        string memory symbol,
        uint256 _quantity
    ) external payable  {
        buyTokenTo(_order, _msgSender(), symbol, _quantity);
    }

    function buyTokenTo(
        uint256 _order,
        address _to,
        string memory symbol,
        uint256 _quantity
    ) internal  {
        require(_to != address(0) && (_to != address(this)), "Wrong buyer");
        require(_asksMap.contains(_order), "Token not in sell book");
        require(_quantity > 0, "insufficient quantity");
        Order storage nft_ = _tokenSellers[_order];
        uint256 quantityOrder = nft_.quantity;
        require(quantityOrder >= _quantity, "excessive quantity");
        uint256 price = nft_.tokenPrices[symbol];
        bool byToken = true;
        if (price == 0) {
            price = nft_.ethPrice;
            require(price > 0, "token no valid");
            byToken = false;
        }
        price = price.mul(_quantity);
        uint256 feeAmount = price.mul(takerFee).div(PERCENTS_DIVIDER);
        if (!byToken) {
            require(msg.value == price, "invalid pay amount");
            if (feeAmount > 0) {
                feeAddr.transfer(feeAmount);
            }
            payable(nft_.owner).transfer(price.sub(feeAmount));
        } else {
            require(ERC20Handler.isValidSymbol(symbol), "token no valid");
            IERC20 token = ERC20Handler.symbolToIERC20(symbol);
            if (feeAmount > 0) {
                token.safeTransferFrom(_to, feeAddr, feeAmount);
            }
            token.safeTransferFrom(_to, nft_.owner, price.sub(feeAmount));
        }
        uint256 _tokenId = nft_.tokenID;
        uint256 deltaQuantity = quantityOrder.sub(_quantity);

        if (deltaQuantity == 0) {
            _asksMap.remove(_order);
            _userSellingOrder[nft_.owner].remove(_order);
            delete _tokenSellers[_order];
        } else {
            nft_.quantity = deltaQuantity;
        }

        nft.safeTransferFrom(address(this), _to, _tokenId, _quantity, "0x");
        emit Trade(
            nft_.owner,
            _to,
            _tokenId,
            byToken,
            symbol,
            _quantity,
            price,
            feeAmount
        );
    }

    function cancelSellToken(uint256 _order) external  {
        require(
            _userSellingOrder[_msgSender()].contains(_order),
            "Only Seller can cancel sell token"
        );
        Order storage order_ = _tokenSellers[_order];
        nft.safeTransferFrom(
            address(this),
            _msgSender(),
            order_.tokenID,
            order_.quantity,
            "0x"
        );
        _asksMap.remove(_order);
        _userSellingOrder[_msgSender()].remove(_order);
        delete _tokenSellers[_order];
        emit CancelSellToken(_msgSender(), _order);
    }

    function convertOrderToOrderShow(Order storage _order)
        internal
        view
        returns (OrderShow memory orderShow)
    {
        orderShow.owner = _order.owner;
		uint256 _id = _order.tokenID;
        orderShow._hash = nft.getHashFromTokenID(_id);
        orderShow.quantity = _order.quantity;
        orderShow.tokenID = _id;
        orderShow.ethPrice = _order.ethPrice;
        string[] memory simbols = ERC20Handler.getAllSymbols();
        uint256 j;
        orderShow.tokenPrices = new TokenPrice[](simbols.length);
        for (uint256 i; i < simbols.length; i++) {
            if (_order.tokenPrices[simbols[i]] == 0) continue;
            orderShow.tokenPrices[j].symbol = simbols[i];
            orderShow.tokenPrices[j].price = _order.tokenPrices[simbols[i]];
            j++;
        }

        return orderShow;
    }

    function getAskLength() external view returns (uint256) {
        return _asksMap.length();
    }

    function getAsks() external view returns (OrderShow[] memory) {
        OrderShow[] memory asks = new OrderShow[](_asksMap.length());

        for (uint256 i; i < _asksMap.length(); i++) {
            uint256 orderNum = _asksMap.at(i);
            asks[i] = convertOrderToOrderShow(_tokenSellers[orderNum]);
        }
        return asks;
    }

    function transferFeeAddress(address _feeAddr) external onlyOwner {
        require(_feeAddr != feeAddr, "Not need update");
        feeAddr = payable(_feeAddr);
        emit FeeAddressTransferred(_msgSender(), feeAddr);
    }

    function setMakerFee(uint256 _makerPercent) external onlyOwner {
        require(makerFee != _makerPercent, "Not need update");
        emit SetMakerFeePercent(_msgSender(), makerFee, _makerPercent);
        makerFee = _makerPercent;
    }

    function setFeeTakerFee(uint256 _takerPercent) external onlyOwner {
        require(takerFee != _takerPercent, "Not need update");
        emit SetTakerFeeFeePercent(_msgSender(), takerFee, _takerPercent);
        takerFee = _takerPercent;
    }

    function getAsksByUser(address user)
        external
        view
        returns (OrderShow[] memory)
    {
        OrderShow[] memory asks =
            new OrderShow[](_userSellingOrder[user].length());

        for (uint256 i; i < _userSellingOrder[user].length(); i++) {
            uint256 orderNum = _userSellingOrder[user].at(i);
            asks[i] = convertOrderToOrderShow(_tokenSellers[orderNum]);
        }
        return asks;
    }


    function getOrdersKeyFromUser(address user)
        external
        view
        returns (uint256[] memory)
    {
        uint256[] memory keys = new uint256[](_userSellingOrder[user].length());
        for (uint256 i; i < keys.length; i++) {
            keys[i] = _userSellingOrder[user].at(i);
        }
        return keys;
    }

    function getOrder(uint256 _order) external view returns (OrderShow memory) {
        Order storage order_ = _tokenSellers[_order];
        if (order_.quantity == 0)
            return convertOrderToOrderShow(_tokenSellers[0]);
        return convertOrderToOrderShow(_tokenSellers[_order]);
    }

    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external override returns (bytes4) {
        return (
            bytes4(
                keccak256(
                    "onERC1155Received(address,address,uint256,uint256,bytes)"
                )
            )
        );
    }

    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external override returns (bytes4) {
        //Not allowed
        revert();
        return "";
    }
}
// File: MultiERC20Handler.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./EnumerableMap.sol";
import "./Address.sol";
import "./Ownable.sol";
import "./IMultiERC20Handler.sol";
import "./IERC20.sol";


contract MultiERC20Handler is Ownable, IMultiERC20Handler {
    using EnumerableMap for EnumerableMap.UintToAddressMap;
    using Address for address;
    event OperationResult(bool result);

    EnumerableMap.UintToAddressMap private _map;

    mapping(uint256 => ERC20Available) public ERC20Tokens;
    mapping(string => uint256) public tokenSymbolToKey;

    struct ERC20Available {
        string symbol;
        address addrs;
        uint256 key;
    }

    function registerERC20Token(address value) external override onlyOwner {
        require(value.isContract(), "set contract address");
        require(
            !isValidToken(value),
            "token or symbol has already been registered"
        );
        setERC20Tokens(ERC20TokensLength() + 1, value);
    }

    function isValidToken(address value) public view override returns (bool) {
        return isValidSymbol(IERC20(value).symbol());
    }

    function isValidSymbol(string memory symbol) public view override returns (bool) {
        return tokenSymbolToKey[symbol] != 0;
    }

    function isValidSymbols(string[] memory symbols)
        public
        view
        override returns (bool)
    {
        for (uint256 i = 0; i < symbols.length; i++) {
            if (!isValidSymbol(symbols[i])) return false;
        }
        return true;
    }

    function setERC20Tokens(uint256 key, address value) internal {
        require(key > 0, "the key must be greater than zero");
        IERC20 tokenHandler = IERC20(value);
        bool result = _map.set(key, value);
        ERC20Available storage token_ = ERC20Tokens[key];
        token_.symbol = tokenHandler.symbol();
        token_.addrs = value;
        token_.key = key;
        tokenSymbolToKey[tokenHandler.symbol()] = key;
        emit OperationResult(result);
    }

    function removeERC20Token(uint256 key) public override onlyOwner {
        _map.remove(key);
        delete tokenSymbolToKey[ERC20Tokens[key].symbol];
        delete ERC20Tokens[key];
    }

    function ERC20TokensContainsKey(uint256 key) public view override returns (bool) {
        return _map.contains(key);
    }

    function ERC20TokensLength() public view override returns (uint256) {
        return _map.length();
    }

    function ERC20TokensAt(uint256 index)
        public
        view override
        returns (uint256 key, address value)
    {
        return _map.at(index);
    }

    function tryGetERC20Token(uint256 key) public view override returns (bool, address) {
        return _map.tryGet(key);
    }

    function getERC20Token(uint256 key) public view override returns (address) {
        return _map.get(key);
    }

    function getERC20TokenWithMessage(uint256 key, string calldata errorMessage)
        public
        view
        override returns (address)
    {
        return _map.get(key, errorMessage);
    }

    function getTokenBySymbol(string memory symbol)
        public
        view
        returns (ERC20Available memory)
    {
        (uint256 _key, ) = ERC20TokensAt(tokenSymbolToKey[symbol]);
        return ERC20Tokens[_key];
    }

    function symbolToIERC20(string memory symbol) public view override returns (IERC20) {
        require(isValidSymbol(symbol), "token is not valid");
        return IERC20(getERC20Token(tokenSymbolToKey[symbol]));
    }

    function symbolToAddress(string memory symbol)
        public
        view
       override returns (address)
    {
        require(isValidSymbol(symbol), "token is not valid");
        return getERC20Token(tokenSymbolToKey[symbol]);
    }

    function getAllAvatibleTokens()
        public
        view
        returns (ERC20Available[] memory)
    {
        ERC20Available[] memory allTokens =
            new ERC20Available[](ERC20TokensLength());
        for (uint256 i; i < allTokens.length; i++) {
            (uint256 _key, ) = ERC20TokensAt(i);
            allTokens[i] = ERC20Tokens[_key];
        }
        return allTokens;
    }

    function getAllSymbols() public view override returns(string[] memory) {
        string[] memory allSymbols = new string[](ERC20TokensLength());
        for (uint256 i; i < allSymbols.length; i++) {
            (uint256 _key, ) = ERC20TokensAt(i);
            allSymbols[i] = ERC20Tokens[_key].symbol;
        }
        return allSymbols;
    }

    function getCurrentKeys() public view override returns(uint256[] memory) {
        uint256[] memory allSymbols = new uint256[](ERC20TokensLength());
        for (uint256 i; i < allSymbols.length; i++) {
            (uint256 _key, ) = ERC20TokensAt(i);
            allSymbols[i] = _key;
        }
        return allSymbols;
    }
}
// File: Ownable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: SafeERC20.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        // solhint-disable-next-line max-line-length
        require((value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) { // Return data is optional
            // solhint-disable-next-line max-line-length
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// File: SafeMath.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;

library SafeMath {

    function add(uint x, uint y) internal pure returns (uint z) {
        require((z = x + y) >= x, 'ds-math-add-overflow');
    }

    function sub(uint x, uint y) internal pure returns (uint z) {
        require((z = x - y) <= x, 'ds-math-sub-underflow');
    }

    function mul(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
    }

    /**
     * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * Reverts with custom message when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b != 0, "SafeMath: modulo by zero");
        return a % b;
    }
}