// File: contracts/OrderBook.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./interfaces/OrderBookI.sol";
import "./interfaces/IMGD.sol";
import "./interfaces/ISP.sol";
import "./interfaces/IERC1155SupplyUpgradeable.sol";

contract OrderBook is OrderBookI, OwnableUpgradeable, ERC1155HolderUpgradeable {
    using SafeERC20Upgradeable for IERC20Upgradeable;
    using SafeMathUpgradeable for uint256;

    uint256 public orderCounter;
    uint256 public mintFee;
    uint256 public listingFee;
    address payable public withdrawAddress;

    bool public openListings;

    IMGD public mgd;

    mapping(uint256 => Order) public orders;
    mapping(uint256 => bool) public listedBefore;
    mapping(uint256 => uint256) public primaryTracker;

    uint256 public collectorsFee;

    struct Order {
        uint256 tokenId;
        uint256 askingPrice;
        uint256 amount;
        address creator;
        address token;
        address nft;
        bool orderValid;
        bool lookingFor;
        bool splitPayable;
    }

    struct FulfillBuf {
        address payable nftReceiver;
        address payable paymentReceiver;
        address nftHolder;
        uint256 initialPrice;
        uint256 price;
        uint256 platformFee;
        uint256 fee;
        bool isPrimaryMarket;
        uint256 collectorsFee;
        uint256 numberOfIssues;
    }

      ISP public isp;

    function initialize(address _mgdContract, address payable _withdrawAddress)
        public
        initializer
    {
        OwnableUpgradeable.__Ownable_init();
        ERC1155HolderUpgradeable.__ERC1155Holder_init();
        mgd = IMGD(_mgdContract);
        openListings = false;
        require(
            _withdrawAddress != address(0),
            "Orderbook ERR: withdraw address cannot be zero"
        );
        withdrawAddress = _withdrawAddress;
        mintFee = 150000;
        listingFee = 50000;
        collectorsFee = 30000;
    }

    modifier notPaused() {
        require(!mgd.isPaused(), "Orderbook ERR: MGD platform is paused");
        _;
    }

    modifier onlyIGovernance(address _address) {
        require(mgd.isIGovernance(_address), "MGD ERR: No initialGovernance");
        _;
    }

    /**
  @notice createOrderExisting allows for the creation of a new order for an existing NFT
  @param _tokenId is the id of the NFT token being sold in the order
  @param _askingPrice is the asking price in 1e18
  @param _amount is the amount of tokens in the order
  @param _token is the address of the ERC20 token the NFT will be exchanged for(use 0x0 add for ETH)
  @param _nft is the address of the NFT contract for the NFT being added to the order
  @param _lookingFor is aa bool representing whether or not the asker owns the NFT
  */
    function createOrderExisting(
        uint256 _tokenId,
        uint256 _askingPrice,
        uint256 _amount,
        address _token,
        address _nft,
        bool _lookingFor
    ) public payable override notPaused returns (uint256) {
        IERC1155Upgradeable nft = IERC1155Upgradeable(_nft);
        if (!openListings) {
            require(_nft == address(mgd), "Orderbook ERR: wrong NFT contract");
        }
        if (!_lookingFor) {
            require(
                nft.balanceOf(_msgSender(), _tokenId) >= _amount,
                "Orderbook ERR: doesnt own this amount of NFTs"
            );
            nft.safeTransferFrom(
                _msgSender(),
                address(this),
                _tokenId,
                _amount,
                ""
            );
        } else if (_token != address(0)) {
            IERC20Upgradeable token = IERC20Upgradeable(_token);
            require(
                token.balanceOf(msg.sender) >= _askingPrice,
                "Orderbook ERR: not enough Token"
            );
            token.safeTransferFrom(_msgSender(), address(this), _askingPrice);
        } else {
            require(msg.value == _askingPrice, "Orderbook ERR: Not enough ETH");
        }

        orderCounter++;
        Order storage order = orders[orderCounter];
        order.tokenId = _tokenId;
        order.askingPrice = _askingPrice;
        order.creator = msg.sender;
        order.token = _token;
        order.nft = _nft;
        order.orderValid = true;
        order.amount = _amount;
        order.lookingFor = _lookingFor;

        emit OrderPlaced(
            order.tokenId,
            orderCounter,
            order.askingPrice,
            order.amount,
            msg.sender,
            order.token,
            order.lookingFor,
            true
        );
        return orderCounter;
    }

    /**
  @notice createOrderNew allows for the creation of a new order for new NFT
  @param _orgName string that represents the name of the organizastion the artist belongs to
  @param _metadataUri  is a string where the metadata URI for the NFT is stored
  @param _royaltyReceiver the address taht will receive the royalties when this NFT is traded on the platform
  @param _token is the address of the ERC20 token the NFT will be exchanged for(use 0x0 add for ETH)
  @param _for is the address of the artist the NFT(s) are being minted for
  @param _askingPrice is the asking price in 1e18
  @param _royalty the percentage value of the royalty?
  */
    function createOrderNew(
        string memory _orgName,
        string memory _metadataUri,
        address _royaltyReceiver,
        address _token,
        address _for,
        uint256 _askingPrice,
        uint256 _issues,
        uint24 _royalty,
        bool _splitPayable
    ) external override notPaused returns (uint256) {
        require(
            mgd.hasAuthorization(_for, _orgName),
            "Must have mint permissions"
        );

        uint256 id = mgd.mint(
            _orgName,
            _metadataUri,
            address(this),
            _royaltyReceiver,
            _for,
            _issues,
            _royalty,
            _splitPayable
        );

        orderCounter++;
        Order storage order = orders[orderCounter];
        order.tokenId = id;
        order.askingPrice = _askingPrice;
        order.creator = _for;
        order.token = _token;
        order.nft = address(mgd);
        order.orderValid = true;
        order.amount = _issues;
        order.splitPayable = _splitPayable;

        emit OrderPlaced(
            order.tokenId,
            orderCounter,
            order.askingPrice,
            _issues,
            _for,
            order.token,
            false,
            true
        );
        return orderCounter;
    }

    /**
  @notice fulfillOrder allows for the fulfillment of an order either when the order price is met
            OR when a counter offer has been accepted
  @param _orderId is the id of the order being fulfilled
  @dev this function will mint a new NFT to the fulfiller if the NFT does not yet exist
        this function transfers the funds from the purchaser to the artist/seller AND
        the NFT from the artist/owner
    */
    function fulfillOrder(uint256 _orderId, uint256 _numberOfIssues, bool _splitPayable)
        external
        payable
        override
        notPaused
    {
        Order storage order = orders[_orderId];
        FulfillBuf memory fulBuff;
        uint256 priceNet;
        uint256 priceFinal;
        
        order.splitPayable = _splitPayable;
        fulBuff.numberOfIssues = _numberOfIssues;

        fulBuff.initialPrice = fulBuff.numberOfIssues.mul(order.askingPrice);
        fulBuff.collectorsFee = ((fulBuff.initialPrice * collectorsFee) /
            1000000);

        IERC1155Upgradeable nft = IERC1155Upgradeable(order.nft);

        //check order is valid
        require(order.orderValid, "Orderbook ERR: order not valid");

        if (order.nft == address(mgd)) {
            if (!listedBefore[order.tokenId]) {
                listedBefore[order.tokenId] = true;
                IERC1155SupplyUpgradeable mgdSupply = IERC1155SupplyUpgradeable(
                    order.nft
                );
                primaryTracker[order.tokenId] = mgdSupply.totalSupply(
                    order.tokenId
                );
                fulBuff.fee = mintFee;
                fulBuff.isPrimaryMarket = true;
                primaryTracker[order.tokenId] = primaryTracker[order.tokenId]
                    .sub(fulBuff.numberOfIssues);
            } else if (primaryTracker[order.tokenId] > 0) {
                fulBuff.fee = mintFee;
                fulBuff.isPrimaryMarket = true;
                if (fulBuff.numberOfIssues >= primaryTracker[order.tokenId]) {
                    primaryTracker[order.tokenId] = 0;
                } else {
                    primaryTracker[order.tokenId] = primaryTracker[
                        order.tokenId
                    ].sub(fulBuff.numberOfIssues);
                }
            } else {
                fulBuff.fee = listingFee;
                fulBuff.isPrimaryMarket = false;
            }
        } else {
            fulBuff.fee = listingFee;
            fulBuff.isPrimaryMarket = false;
        }

        fulBuff.platformFee = ((fulBuff.initialPrice * fulBuff.fee) / 1000000);
        priceNet = fulBuff.initialPrice.sub(fulBuff.platformFee);
        //calculate royalties
        (address _receiver, uint256 _royaltyAmount) = mgd.royaltyInfo(
            order.tokenId,
            priceNet
        );
        priceFinal = (priceNet -_royaltyAmount);
        address payable artist = payable(_receiver);

        ///check if order is to buy or sell NFT
        if (!order.lookingFor) {
            //Listing

            //Artist
            fulBuff.paymentReceiver = payable(order.creator);

            //Collector
            fulBuff.nftReceiver = payable(msg.sender);

            //Orderbook
            fulBuff.nftHolder = address(this);
        } else {
            //Bids

            //Artist
            fulBuff.paymentReceiver = payable(msg.sender);

            //Collector
            fulBuff.nftReceiver = payable(order.creator);

            //artist
            fulBuff.nftHolder = msg.sender;
        }
        //transfer the money
        //if buying in ETH
        if (order.token == address(0)) {
            if (!order.lookingFor) {
                //if listing
                require(
                    msg.value == fulBuff.initialPrice + fulBuff.collectorsFee,
                    "OrderBook ERR: not enough ETH"
                );
            }
            (bool success, bytes memory returndata) = withdrawAddress.call{
                value: fulBuff.platformFee + fulBuff.collectorsFee,
                gas: 5000
            }("");
            require(success, string(returndata));
            if (order.splitPayable) {
              isp = ISP(_receiver);
              isp.splitPayment{value:priceFinal, gas: uint256(gasleft() / 2)}(
                  fulBuff.nftReceiver
              );
            } else {
                fulBuff.paymentReceiver.transfer(priceFinal);
            }
            (bool success2,) = artist.call{value: _royaltyAmount, gas: uint256(gasleft() / 2)}("");
            require(success2);
        } else if (!order.lookingFor) {
            //If buying list in token
            IERC20Upgradeable token = IERC20Upgradeable(order.token);
            token.safeTransferFrom(
                fulBuff.nftReceiver,
                withdrawAddress,
                fulBuff.platformFee + fulBuff.collectorsFee
            );
            if (order.splitPayable) {
                    isp.splitPaymentERC20(
                        fulBuff.nftReceiver,
                        order.token,
                        priceFinal
                    );
            } else {
                token.safeTransferFrom(
                    fulBuff.nftReceiver,
                    fulBuff.paymentReceiver,
                    (priceFinal)
                );
            }
            token.safeTransferFrom(fulBuff.nftReceiver, artist, _royaltyAmount);
        } else {
            //If fulfilling bid in token

            //Token Address
        IERC20Upgradeable token = IERC20Upgradeable(order.token);

        if(order.splitPayable) {
            isp.splitPaymentERC20(fulBuff.paymentReceiver, order.token,  priceFinal);

            //Platform fee: From Collector to withdraw address
            token.safeTransfer(
                withdrawAddress,
                fulBuff.platformFee + fulBuff.collectorsFee
            );

            //Royalty Amount: From Collector to artist.
            token.safeTransfer(artist, _royaltyAmount);
            token.safeTransfer(
                fulBuff.paymentReceiver,
                (priceFinal)
            );
        }
   }
        //transfer the NFT
        nft.safeTransferFrom(
            fulBuff.nftHolder,
            fulBuff.nftReceiver,
            order.tokenId,
            fulBuff.numberOfIssues,
            ""
        );

        order.amount = order.amount.sub(fulBuff.numberOfIssues);

        if (order.amount == 0) {
            order.orderValid = false;
        }

        emit OrderFulfilled(
            _orderId,
            fulBuff.initialPrice,
            fulBuff.platformFee,
            _royaltyAmount,
            fulBuff.paymentReceiver,
            fulBuff.numberOfIssues,
            fulBuff.isPrimaryMarket,
            msg.sender
        );
    }

    /**
  @notice cancelOrder allows for the cancleation of an order
  @param _orderId is the id of the order being fulfilled
*/
    function cancelOrder(uint256 _orderId) external override notPaused {
        Order storage order = orders[_orderId];
        require(
            msg.sender == order.creator,
            "OrderBook ERR: does not have permission to cancel order"
        );
        order.orderValid = false;
        if (!order.lookingFor) {
            IERC1155Upgradeable nft = IERC1155Upgradeable(order.nft);
            nft.safeTransferFrom(
                address(this),
                order.creator,
                order.tokenId,
                order.amount,
                ""
            );
        } else {
            if (order.token == address(0)) {
                address payable creator = payable(order.creator);
                creator.transfer(order.askingPrice);
            } else {
                IERC20Upgradeable token = IERC20Upgradeable(order.token);
                token.safeTransfer(order.creator, order.askingPrice);
            }
        }
        emit OrderCanceled(_orderId);
    }

    /**
    @notice unlockPlatform allows for owner of this contract to open up the platforms listings to
            non MGD NFT types
    */
    function unlockPlatform() external override onlyIGovernance(_msgSender()) {
        openListings = true;
    }

    /**
    @notice setMintFee allows the owner to set the fee for minting and listing through the orderbook
    @param _fee is the value representing the percentage of a sale taken as a platform fee
    */
    function setMintFee(uint256 _fee)
        external
        override
        onlyIGovernance(_msgSender())
    {
        mintFee = _fee;
    }

    /**
    @notice setListingFee allows the owner to set the fee for secondary listings through the orderbook
    @param _fee is the value representing the percentage of a sale taken as a platform fee
    */
    function setListingFee(uint256 _fee)
        external
        override
        onlyIGovernance(_msgSender())
    {
        listingFee = _fee;
    }

    /**
    @notice setCollectorsFee allows the owner to set a collectors fee (paid out to MGD)
    @param _fee is the value representing the percentage of a sale taken as a platform fee
    */
    function setCollectorsFee(uint256 _fee)
        external
        onlyIGovernance(_msgSender())
    {
        collectorsFee = _fee;
    }

    /**
    @notice setFeeAdd allows the owner to set the fee address
    @param _add is the address that will receive the fee's
    */
    function setFeeAdd(address _add)
        external
        override
        onlyIGovernance(_msgSender())
    {
        withdrawAddress = payable(_add);
    }
}

// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

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

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        require(_initializing || !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal initializer {
        __Context_init_unchained();
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal initializer {
        _setOwner(_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 {
        _setOwner(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");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
    uint256[49] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
    using AddressUpgradeable for address;

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

    function safeTransferFrom(
        IERC20Upgradeable 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(
        IERC20Upgradeable 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'
        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(
        IERC20Upgradeable 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(
        IERC20Upgradeable 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(IERC20Upgradeable 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
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.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 IERC1155Upgradeable is IERC165Upgradeable {
    /**
     * @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: @openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./ERC1155ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";

/**
 * @dev _Available since v3.1._
 */
contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable {
    function __ERC1155Holder_init() internal initializer {
        __ERC165_init_unchained();
        __ERC1155Receiver_init_unchained();
        __ERC1155Holder_init_unchained();
    }

    function __ERC1155Holder_init_unchained() internal initializer {
    }
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
    uint256[50] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
 * now has built in overflow checking.
 */
library SafeMathUpgradeable {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting 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) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting 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,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * 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,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

// File: contracts/interfaces/OrderBookI.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;

import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";

interface OrderBookI {
    event OrderPlaced(
        uint256 indexed tokenID,
        uint256 indexed orderID,
        uint256 indexed askingPrice,
        uint256 amountForSale,
        address account,
        address token,
        bool lookingFor,
        bool primary
    );

    event OrderFulfilled(
        uint256 indexed orderID,
        uint256 salePrice,
        uint256 platformFee,
        uint256 royaltyAmount,
        address indexed royaltyReceiver,
        uint256 amountSold,
        bool    isPrimaryMarket,
        address indexed fulfilledBy
    );

    event OrderCanceled(uint256 indexed _orderId);

    /**
    @notice createOrderExisting allows for the creation of a new order for an existing NFT
    @param _tokenId is the id of the NFT token being sold in the order
    @param _askingPrice is the asking price in 1e18
    @param _amount is the amount of tokens in the order
    @param _token is the address of the ERC20 token the NFT will be exchanged for(use 0x0 add for ETH)
    @param _nft is the address of the NFT contract for the NFT being added to the order
    @param _lookingFor is aa bool representing whether or not the asker owns the NFT
  */
    function createOrderExisting(
        uint256 _tokenId,
        uint256 _askingPrice,
        uint256 _amount,
        address _token,
        address _nft,
        bool _lookingFor
    ) external payable returns (uint256);

    /**
  @notice createOrderNew allows for the creation of a new order for new NFT
  @param _orgName string that represents the name of the organizastion the artist belongs to
  @param _metadataUri  is a string where the metadata URI for the NFT is stored
  @param _royaltyReceiver the address taht will receive the royalties when this NFT is traded on the platform
  @param _token is the address of the ERC20 token the NFT will be exchanged for(use 0x0 add for ETH)
  @param _for is the address of the artist the NFT(s) are being minted for
  @param _askingPrice is the asking price in 1e18
  @param _royalty the percentage value of the royalty?
  */
    function createOrderNew(
        string memory _orgName,
        string memory _metadataUri,
        address _royaltyReceiver,
        address _token,
        address _for,
        uint256 _askingPrice,
        uint256 _issues,
        uint24 _royalty,
        bool _splitPayable
    ) external returns (uint256);

    /**
    @notice fulfillOrder allows for the fulfillment of an order either when the order price is met
              OR when a counter offer has been accepted
    @param _orderId is the id of the order being fulfilled
    @dev this function will mint a new NFT to the fulfiller if the NFT does not yet exist
          this function transfers the funds from the purchaser to the artist/seller AND
          the NFT from the artist/owner
  */
    function fulfillOrder(uint256 _orderId, uint256 _numberOfIssues, bool _splitPayable)
        external
        payable;

    /**
    @notice cancelOrder allows for the cancleation of an order
    @param _orderId is the id of the order being fulfilled
  */
    function cancelOrder(uint256 _orderId) external;

    /**
    @notice unlockPlatform allows for owner of this contract to open up the platforms listings to
              non MGD NFT types
  */
    function unlockPlatform() external;

    /**
    @notice setMintFee allows a the owner to set the fee for minting and listing through the orderbook
    @param _fee is the value representing the percentage of a sale taken as a platform fee
  */
    function setMintFee(uint256 _fee) external;

    /**
    @notice setListingFee allows a the owner to set the fee for secondary listings through the orderbook
    @param _fee is the value representing the percentage of a sale taken as a platform fee
  */
    function setListingFee(uint256 _fee) external;

    /**
    @notice setFeeAdd allows the owner to set the fee address
    @param _add is the address that will receive the fee's
    */
    function setFeeAdd(address _add) external;
}

// File: contracts/interfaces/IMGD.sol



//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.6;

import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";

interface IMGD is IERC1155Upgradeable {
    event OrganizationCreated(
        string organization,
        string metadata,
        address orgAdmin
    );

    event GovernanceAdded(address _address);

    event GovernanceRemoved(address _address);

    event OrgGovernanceAdded(string organization, address _address);

    event ArtistAdded(address artist, string organization, string metadata);

    event Mint(
        uint256 id,
        address indexed author,
        address indexed to,
        address royaltyReceiver,
        uint24 royalty,
        uint256 issues,
        string metadataUri,
        bool splitPayable
    );

    event MintOrg(uint256 tokenId, string orgName);

    event MetadataUpdate(
        uint256 indexed id,
        address author,
        string metadataUri,
        address indexed royaltyReceiver,
        uint24 royalty
    );

    event OrgDataUpdated(string _orgName, string newURI);

    event OrgGovernanceRemoved(string _orgName, address _address);

    event ArtistRemoved(string _orgName, address _address);

    event NFTflagged(uint256 tokenId);

    event PlatformPaused(bool _isPaused);

    /**Protocol Admin functions **/

    /**
    @notice setMGDcontract allows the Governance to give a contract mint permissions
    @dev this is a protected function that only the Governance can call
    */
    function setMGDcontract(address _contract) external;

    /**
    @notice createOrganization allows the Governance to create organizations
    @param _orgName is the name of the org being created
    @param _orgData is the orgs informational URI
    @param _address is the first Governance address of an org
    */
    function createOrganization(
        string memory _orgName,
        string memory _orgData,
        address _address
    ) external;

    /**
    @notice add Governance allows a governance address to add other addresses to the Governance list
    @param _address is the address of the new Governance
    */
    function addGovernance(address _address) external;

    /**
    @notice add Governance allows a governance address to add other addresses to the Governance list
    @param _address is the address of the new Governance
    */
    function addIGovernance(address _address) external;

    /**
    @notice removeGovernance allows a governance address to remove other addresses from the Governance list
    @param _address is the address from the Governance list being removed
    */
    function removeGovernance(address _address) external;

    /**
    @notice removeGovernance allows a governance address to remove other addresses from the Governance list
    @param _address is the address from the Governance list being removed
    */
    function removeIGovernance(address _address) external;

    /**Org Admin functions **/

    /**
    @notice addOrgGovernance allows an Org Governance to add another Governance address to an organizastion
    @param _orgName is the name of the organizastion
    @param _address is the address of the Governance
    */
    function addOrgGovernance(string memory _orgName, address _address) external;

    /**
    @notice addArtistToOrg allows an Org Governance to add an artist to an organization
    @param _orgName is the name of the organizastion
    @param _artistData is the URI for an artists data
    @param _address is the address of the artist being added
    */
    function addArtistToOrg(
        string memory _orgName,
        string memory _artistData,
        address _address
    ) external;

    /**
    @notice removeOrgGovernance allows an Org Governance to remove an Org Governance address
    @param _orgName is the name of the org
    @param _address is the address of the Org Governance being removed
    */
    function removeOrgGovernance(string memory _orgName, address _address) external;

    /**
    @notice removeArtist allows an Org Governance to remove an artist
    @param _orgName is the name of the org
    @param _address is the address of the artist being removed
    */
    function removeArtist(string memory _orgName, address _address) external;


    /**Artist functions **/

    /**
    @notice mint allows an artist to mint a new NFT
    @param _orgName is the name of the org
    @param _metadataUri is the new NFTs metadata URI
    @param _to is the address the NFT is being minted to
    @param _royaltyReceiver is the address of the royalty receiver
    @param _author is the author of the NFT
    @param _issues is the number of issues of an NFT to mint
    @param _royalty is the royalty percentage of a sale that is sent to the artist
    */
    function mint(
        string memory _orgName,
        string memory _metadataUri,
        address _to,
        address _royaltyReceiver,
        address _author,
        uint256 _issues,
        uint24 _royalty,
        bool _splitPayable
    ) external returns (uint256 tokenId_);

    /**
    @notice updateMetadata allows an artist to edit an NFT's metadata URI
    @param _tokenId is the NFT's token ID
    @param _metadataUri is the new metadata URI
    @param _royaltyReceiver is the address of the royalty receiver
    @param _royalty is the royalty percentage of a sale that is sent to the artist
    */
    function updateMetadata(
        uint256 _tokenId,
        string memory _metadataUri,
        address _royaltyReceiver,
        uint24 _royalty
    ) external;

    /** view functions **/

    /**
    @notice Called with the sale price to determine how much royalty
              is owed and to whom.
    @param _tokenId - the NFT asset queried for royalty information
    @param _value - the sale price of the NFT asset specified by _tokenId
    @return _receiver - address of who should be sent the royalty payment
    @return _royaltyAmount - the royalty payment amount for _value sale price
    @dev percentages should be set as parts per million 1000000 == 100% and 100000 == 10%
    */
    function royaltyInfo(
        uint256 _tokenId,
        uint256 _value
    )
        external
        view
        returns (
            address _receiver,
            uint256 _royaltyAmount
        );

      /**
    @notice isIGovernance returns a bool representing whether or not an address in included in initialGovernance list
    @param _address is the address in question
    */
  function isIGovernance(address _address)
    external
    view
    returns (bool);

    /**
        @notice hasAuthorization returns a bool representing whether or not an address has mint permissions
        @param _address is the address in question
        @param _orgName is the name of the org in question
        */
    function hasAuthorization(address _address, string memory _orgName)
        external
        view
        returns (bool);

    /**
        @notice pausePlatform allows one of the initial Protocol Admins to pause or unpause the functions
                of the MGD platform
        */
    function triggerPause() external;

    function isPaused() external returns (bool);
}

// File: contracts/interfaces/ISP.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

interface ISP {  
  event CollaboratorAdded(address collaborator, uint256 split);
  event PaymentTransferred(address collaborator, uint256 amount);
  event PaymentReceived(address from, uint256 amount);

    function initialize(address[] memory collaborators, uint256[] memory splits) external;

   function splitPaymentERC20(address from, address tokenAddress, uint256 totalAmount) external;

   function splitPayment(address from) external payable;

   function getTotalSplits() external returns(uint256);

}
// File: contracts/interfaces/IERC1155SupplyUpgradeable.sol



//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.6;

interface IERC1155SupplyUpgradeable {
    /**
     * @dev Total amount of tokens in with a given id.
     */
    function totalSupply(uint256 id) external view returns (uint256);
}

// File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal initializer {
        __Context_init_unchained();
    }

    function __Context_init_unchained() internal initializer {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
    uint256[50] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @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;
        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");

        (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");

        (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");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

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

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.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 IERC165Upgradeable {
    /**
     * @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: @openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155ReceiverUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../IERC1155ReceiverUpgradeable.sol";
import "../../../utils/introspection/ERC165Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable {
    function __ERC1155Receiver_init() internal initializer {
        __ERC165_init_unchained();
        __ERC1155Receiver_init_unchained();
    }

    function __ERC1155Receiver_init_unchained() internal initializer {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
        return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }
    uint256[50] private __gap;
}

// File: @openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165Upgradeable.sol";

/**
 * @dev _Available since v3.1._
 */
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
    /**
        @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: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal initializer {
        __ERC165_init_unchained();
    }

    function __ERC165_init_unchained() internal initializer {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }
    uint256[50] private __gap;
}