// File: contracts/exchange/TrashArtExchange.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "./ArrayUtils.sol";
import "./IAtomicMatchHandler.sol";
import "./IHasSecondarySaleFees.sol";

contract TrashArtExchange is ReentrancyGuard, Ownable {
  using SafeERC20 for IERC20;
  using ERC165Checker for address;

  /*
   * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f
   * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb
   *
   * => 0x0ebd4c7f ^ 0xb9c4d9fb == 0xb7799584
   */
  bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584;

  /* Cancelled / finalized orders, by hash. */
  mapping(bytes32 => bool) public cancelledOrFinalized;

  /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */
  mapping(bytes32 => bool) public approvedOrders;

  /** referrers */
  mapping(address => address) public referrers; // user address => referrer address
  mapping(address => uint256) public referralsCount; // referrer address => referrals count

  /* Recipient of protocol fees. */
  // address public protocolFeeRecipient;

  /* Relayer info (Fees has two decimals by default, so 100 => 1%) */
  struct Relayer {
    address protocolFeeRecipient;
    address relayerAddress;
    uint256 relayerFee;
    uint256 protocolFee;
    uint256 referralFee;
    ReferralSide referralSide;
    bool referralEnabled; // True if referral system is enabled
    bool referralRegistrationEnabled; // True if new referrals are enabled
    IAtomicMatchHandler atomicMatchHandler;
  }

  /* Registerd Relayers */
  mapping(address => Relayer) public registeredRelayers;

  /* Registererd Payment Tokens */
  mapping(address => bool) public registeredPaymentTokens;

  /* Discount for payment tokens of relayers if available else 0 
    (Discount on native relayer token can be used for early incentives) */
  mapping(address => mapping(address => uint256)) public paymentTokenDiscounts;

  /* An ECDSA signature. */
  struct Sig {
    /* v parameter */
    uint8 v;
    /* r parameter */
    bytes32 r;
    /* s parameter */
    bytes32 s;
  }

  /**
   * Side: buy or sell.
   */
  enum Side {
    Buy,
    Sell
  }

  /**
   * Currently supported kinds of sale.
   */
  enum SaleKind {
    FixedPrice,
    DutchAuction,
    EnglishAuction
  }

  /**
   * Type of the asset.
   */
  enum AssetType {
    ERC721,
    ERC1155
  }

  /**
   * From which side to take the referral discount
   */
  enum ReferralSide {
    Protocol,
    Relayer,
    Seller
  }

  /* An order on the exchange. */
  struct Order {
    /* Asset address (ERC165 | ERC721 | ERC1155)*/
    address asset;
    /* Asset ID */
    uint256 assetId;
    /* Asset Amount (Used for ERC1155 collections) */
    uint256 assetAmount;
    /* Asset Type (ERC721 | ERC1155)*/
    AssetType assetType;
    /* Exchange address. */
    address exchange;
    /* Relayer address. */
    address relayer;
    /* Order maker address. */
    address maker;
    /* Order taker address, if specified. */
    address taker;
    /* Relayer Fee of the order. */
    uint256 relayerFee;
    /* Protocol fee of the order.*/
    uint256 protocolFee;
    /* Side (buy/sell). */
    Side side;
    /* Kind of sale. */
    SaleKind saleKind;
    /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
    address paymentToken;
    /* Opening price of the order (in paymentTokens). 
        (This is the initial price for english auction & the opening price for dutch auction) */
    uint256 basePrice;
    /* Auction reserve parameter - minimum bid increment for English auctions, starting/ending price difference. */
    uint256 reservePrice;
    /* Listing timestamp. */
    uint256 listingTime;
    /* Expiration timestamp - 0 for no expiry. */
    uint256 expirationTime;
    /* Order salt, used to prevent duplicate hashes. */
    uint256 salt;
  }

  // address is 0x14 bytes, uint256 has 0x20 bytes, enum is 1
  uint256 constant ORDER_SIZE = ((0x14 * 6) + (0x20 * 9) + 3);

  event OrderApprovedPartOne(
    bytes32 indexed hash,
    address asset,
    uint256 assetId,
    uint256 assetAmount,
    AssetType assetType,
    address exchange,
    address relayer,
    address indexed maker,
    address taker,
    uint256 relayerFee,
    uint256 protocolFee,
    Side side,
    SaleKind saleKind
  );
  event OrderApprovedPartTwo(
    bytes32 indexed hash,
    address paymentToken,
    uint256 basePrice,
    uint256 topPrice,
    uint256 listingTime,
    uint256 expirationTime,
    uint256 salt,
    bool orderbookInclusionDesired
  );
  event OrderCancelled(bytes32 indexed hash);
  event OrdersMatched(bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint256 price);
  event ReferralRecorded(address user, address referrer);
  event ReferralPaid(address user, address referrer, address paymentToken, uint256 amount);
  event RelayerAdded(Relayer indexed relayer);

  constructor(Relayer memory relayer) {
    setRelayer(relayer);
  }

  function changeFee(uint256 fee) public {
    require(registeredRelayers[msg.sender].protocolFeeRecipient != address(0), "TrashArtExchange: not authorized");
    Relayer storage _relayer = registeredRelayers[msg.sender];
    _relayer.relayerFee = fee;
  }

  /**
   * Registers/Updates a relayer address and its relevant fee
   */
  function setRelayer(Relayer memory relayer) public onlyOwner {
    require(relayer.relayerAddress != address(0), "TrashArtExchange: relayerAddress zero address");
    require(relayer.protocolFeeRecipient != address(0), "TrashArtExchange: protocolFeeRecipient zero address");
    if (address(registeredRelayers[relayer.relayerAddress].relayerAddress) == address(0)) emit RelayerAdded(relayer);
    registeredRelayers[relayer.relayerAddress] = relayer;
  }

  /**
   * Set the payment token discount for relayers
   */
  function setPaymentTokenDiscount(
    address relayer,
    address token,
    uint256 discount
  ) internal onlyOwner {
    require(discount > 0 && discount <= 10000, "Invalid Discount!");
    paymentTokenDiscounts[relayer][token] = discount;
  }

  /**
   * @dev Change the protocol fee recipient (owner only)
   * @param newProtocolFeeRecipient New protocol fee recipient address
   */
  function changeProtocolFeeRecipient(address relayer, address newProtocolFeeRecipient) internal onlyOwner {
    registeredRelayers[relayer].protocolFeeRecipient = newProtocolFeeRecipient;
  }

  /**
   * @dev Hash an order, returning the canonical order hash, without the message prefix
   * @param order Order to hash
   * @return hash of order
   */
  function hashOrder(Order memory order) internal pure returns (bytes32 hash) {
    /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
    bytes memory array = new bytes(ORDER_SIZE);
    uint256 index;
    assembly {
      index := add(array, 0x20)
    }
    index = ArrayUtils.unsafeWriteAddress(index, order.asset);
    index = ArrayUtils.unsafeWriteUint(index, order.assetId);
    index = ArrayUtils.unsafeWriteUint(index, order.assetAmount);
    index = ArrayUtils.unsafeWriteUint8(index, uint8(order.assetType));
    index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
    index = ArrayUtils.unsafeWriteAddress(index, order.relayer);
    index = ArrayUtils.unsafeWriteAddress(index, order.maker);
    index = ArrayUtils.unsafeWriteAddress(index, order.taker);
    index = ArrayUtils.unsafeWriteUint(index, order.relayerFee);
    index = ArrayUtils.unsafeWriteUint(index, order.protocolFee);
    index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
    index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
    index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
    index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
    index = ArrayUtils.unsafeWriteUint(index, order.reservePrice);
    index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
    index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
    index = ArrayUtils.unsafeWriteUint(index, order.salt);
    assembly {
      hash := keccak256(add(array, 0x20), ORDER_SIZE)
    }
    return hash;
  }

  /**
   * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
   * @param order Order to hash
   * @return Hash of message prefix and order hash per Ethereum format
   */
  function hashToSign(Order memory order) internal pure returns (bytes32) {
    return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
  }

  function getHash(Order memory order) external pure returns (bytes32, bytes32) {
    return (hashOrder(order), hashToSign(order));
  }

  /**
   * @dev Assert an order is valid and return its hash
   * @param order Order to validate
   * @param sig ECDSA signature
   */
  function requireValidOrder(Order memory order, Sig memory sig) public view returns (bytes32) {
    bytes32 hash = hashToSign(order);
    require(validateOrder(hash, order, sig), "Invalid Order");
    return hash;
  }

  /**
   * @dev Validate order parameters (does *not* check signature validity)
   * @param order Order to validate
   */
  function validateOrderParameters(Order memory order) public view returns (bool) {
    /* Order must be targeted at this protocol version (this Exchange contract). */
    if (order.exchange != address(this)) {
      return false;
    }

    // only allow transactions for relayers
    if (registeredRelayers[order.relayer].relayerAddress == address(0)) {
      return false;
    }

    /* Order must possess valid sale kind parameter combination. */
    if (!validateParameters(order.saleKind, order.expirationTime)) {
      return false;
    }

    /** Order must have current valid fee. */
    if (
      order.protocolFee < registeredRelayers[order.relayer].protocolFee ||
      order.relayerFee < registeredRelayers[order.relayer].relayerFee
    ) {
      return false;
    }

    return true;
  }

  /**
   * @dev Validate a provided previously approved / signed order, hash, and signature.
   * @param hash Order hash (already calculated, passed to avoid recalculation)
   * @param order Order to validate
   * @param sig ECDSA signature
   */
  function validateOrder(
    bytes32 hash,
    Order memory order,
    Sig memory sig
  ) public view returns (bool) {
    /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */

    /* Order must have valid parameters. */
    if (!validateOrderParameters(order)) {
      return false;
    }

    /* Order must have not been canceled or already filled. */
    if (cancelledOrFinalized[hash]) {
      return false;
    }

    /* Order authentication. Order must be either:
        /* (a) previously approved */
    if (approvedOrders[hash]) {
      return true;
    }

    /* or (b) ECDSA-signed by maker. */
    if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
      return true;
    }

    return false;
  }

  /**
   * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order
   * @param order Order to approve
   * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks
   */
  function approveOrder(Order memory order, bool orderbookInclusionDesired) public {
    /* CHECKS */

    /* Assert sender is authorized to approve order. */
    require(msg.sender == order.maker, "Not approved");

    /* Calculate order hash. */
    bytes32 hash = hashToSign(order);

    /* Assert order has not already been approved. */
    require(!approvedOrders[hash], "Not approved");

    /* EFFECTS */

    /* Mark order as approved. */
    approvedOrders[hash] = true;

    /* Log approval event. Must be split in two due to Solidity stack size limitations. */
    {
      emit OrderApprovedPartOne(
        hash,
        order.asset,
        order.assetId,
        order.assetAmount,
        order.assetType,
        order.exchange,
        order.relayer,
        order.maker,
        order.taker,
        order.relayerFee,
        order.protocolFee,
        order.side,
        order.saleKind
      );
    }
    {
      emit OrderApprovedPartTwo(
        hash,
        order.paymentToken,
        order.basePrice,
        order.reservePrice,
        order.listingTime,
        order.expirationTime,
        order.salt,
        orderbookInclusionDesired
      );
    }
  }

  /**
   * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order
   * @param order Order to cancel
   * @param sig ECDSA signature
   */
  function cancelOrder(Order memory order, Sig memory sig) public {
    /* CHECKS */

    /* Calculate order hash. */
    bytes32 hash = requireValidOrder(order, sig);

    /* Assert sender is authorized to cancel order. */
    require(msg.sender == order.maker, "Not authorized");

    /* EFFECTS */

    /* Mark order as cancelled, preventing it from being matched. */
    cancelledOrFinalized[hash] = true;

    /* Log cancel event. */
    emit OrderCancelled(hash);
  }

  /**
   * @dev Calculate the current price of an order (convenience function)
   * @param order Order to calculate the price of
   * @return The current price of the order
   */
  function calculateCurrentPrice(Order memory order) public view returns (uint256) {
    if (order.saleKind == SaleKind.DutchAuction) return calculateDutchAuctionCurrentPrice(order);
    return order.basePrice;
  }

  /**
   * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures)
   * @param buy Buy-side order
   * @param sell Sell-side order
   * @return Whether or not the two orders can be matched
   */
  function ordersCanMatch(Order memory buy, Order memory sell) public view returns (bool) {
    return (/* Must be opposite-side. */
    (buy.side == Side.Buy && sell.side == Side.Sell) &&
      /* Must use same asset. */
      (buy.asset == sell.asset) &&
      (buy.assetId == sell.assetId) &&
      (buy.assetType == sell.assetType) &&
      /* Must use same payment token. */
      (buy.paymentToken == sell.paymentToken) &&
      /* Must match maker/taker addresses. */
      (sell.taker == address(0) || sell.taker == buy.maker) &&
      (buy.taker == address(0) || buy.taker == sell.maker) &&
      /** Buy price must satify sell price */
      canPriceMatch(sell, buy) &&
      /* Buy-side order must be settleable. */
      canSettleOrder(buy.listingTime, buy.expirationTime) &&
      /* Sell-side order must be settleable. */
      canSettleOrder(sell.listingTime, sell.expirationTime));
  }

  function recordReferral(address _user, address _referrer) internal {
    if (_user != address(0) && _referrer != address(0) && _user != _referrer && referrers[_user] == address(0)) {
      referrers[_user] = _referrer;
      referralsCount[_referrer] += 1;
      emit ReferralRecorded(_user, _referrer);
    }
  }

  /**
   * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
   * @param buy Buy-side order
   * @param buySig Buy-side order signature
   * @param sell Sell-side order
   * @param sellSig Sell-side order signature
   */
  function atomicMatch(
    Order memory buy,
    Sig memory buySig,
    Order memory sell,
    Sig memory sellSig,
    address referrer
  ) external payable nonReentrant {
    /** Record Referral */
    recordReferral(sell.maker, referrer);

    /* CHECKS */

    /* Ensure buy order validity and calculate hash if necessary. */
    bytes32 buyHash;
    if (buy.maker == msg.sender) {
      require(validateOrderParameters(buy), "Invalid order params!");
    } else {
      buyHash = requireValidOrder(buy, buySig);
    }

    /* Ensure sell order validity and calculate hash if necessary. */
    bytes32 sellHash;
    if (sell.maker == msg.sender) {
      require(validateOrderParameters(sell), "Invalid order params!");
    } else {
      sellHash = requireValidOrder(sell, sellSig);
    }

    /* Must be matchable. */
    require(ordersCanMatch(buy, sell), "Order Failed to match!");

    /* EFFECTS */

    /* Mark previously signed or approved orders as finalized. */
    if (msg.sender != buy.maker) {
      cancelledOrFinalized[buyHash] = true;
    }
    if (msg.sender != sell.maker) {
      cancelledOrFinalized[sellHash] = true;
    }

    /* INTERACTIONS */

    /* Execute funds transfer and pay fees. */
    uint256 price = executeFundsTransfer(buy, sell);

    /* Execute Asset transfer according to AssetType */
    executeAssetTransfer(sell.maker, buy.maker, sell.asset, sell.assetId, sell.assetAmount, sell.assetType);

    IAtomicMatchHandler atomicMatchHandler = registeredRelayers[sell.relayer].atomicMatchHandler;
    if (address(atomicMatchHandler) != address(0))
      atomicMatchHandler.onAtomicMatch(sell.asset, sell.assetId, sell.assetAmount, sell.maker, buy.maker, price);

    /* Log match event. */
    emit OrdersMatched(buyHash, sellHash, sell.maker, buy.maker, price);
  }

  /**
   * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
   * @param buy Buy-side order
   * @param sell Sell-side order
   */
  function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint256) {
    /* Only payable in the special case of unwrapped Ether. */
    if (sell.paymentToken != address(0)) {
      require(msg.value == 0, "Invalid Payment");
    }

    /* Calculate match price. */
    uint256 price = calculateCurrentPrice(sell);

    uint256 totalFee = chargeFee(sell, price, buy.maker);

    /* Special-case Ether, order must be matched by buyer. */
    if (sell.paymentToken == address(0)) {
      require(msg.value >= price, "Invalid Payment");
      payable(sell.maker).transfer(price - totalFee);
      /* Allow overshoot for variable-price auctions, refund difference. */
      uint256 extra = msg.value - price;
      if (extra > 0) {
        payable(buy.maker).transfer(extra);
      }
    }
    /** If ERC20 token payment method is used */
    else {
      IERC20(sell.paymentToken).safeTransferFrom(buy.maker, sell.maker, price - totalFee);
    }

    /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
    return price;
  }

  /**
   * @dev Charge a fee in Eth or Tokens
   * @param sellOrder sell order
   * @param amount amount of order
   * @param buyer Relayer address
   */
  function chargeFee(
    Order memory sellOrder,
    uint256 amount,
    address buyer
  ) internal returns (uint256) {
    uint256 totalFee;
    Relayer memory relayerInfo = registeredRelayers[sellOrder.relayer];
    uint256 referralFee = payReferrerCommission(sellOrder.maker, buyer, amount, sellOrder.paymentToken, relayerInfo);
    totalFee += referralFee; // if referral side is seller, don't need to do anything after this, else need to subtract referral fee from either protocol or relayer fee
    if (relayerInfo.protocolFee != 0) {
      uint256 feeAmount = (amount * relayerInfo.protocolFee) / 10000;
      if (referralFee != 0 && relayerInfo.referralSide == ReferralSide.Protocol) {
        feeAmount -= referralFee;
      }
      totalFee = feeAmount;
      /** Eth as payment method */
      if (sellOrder.paymentToken == address(0))
        payable(relayerInfo.protocolFeeRecipient).transfer(feeAmount);
        /** Token as payment method */
      else IERC20(sellOrder.paymentToken).safeTransferFrom(buyer, relayerInfo.protocolFeeRecipient, feeAmount);
    }
    // Charge fee if RelayerFee is not zero and Relayer discount for this token is not 100%
    uint256 tokenDiscount = paymentTokenDiscounts[sellOrder.relayer][sellOrder.paymentToken];
    if (relayerInfo.relayerFee != 0 && tokenDiscount != 10000) {
      uint256 feeAmount = (amount * relayerInfo.protocolFee) / 10000;
      if (referralFee != 0 && relayerInfo.referralSide == ReferralSide.Relayer) {
        feeAmount -= referralFee;
      }
      /** apply discount if available */
      if (tokenDiscount > 0) feeAmount = feeAmount - ((feeAmount * tokenDiscount) / 10000);
      totalFee += feeAmount;
      /** Eth as payment method */
      if (sellOrder.paymentToken == address(0))
        payable(sellOrder.relayer).transfer(feeAmount);
        /** Token as payment method */
      else IERC20(sellOrder.paymentToken).safeTransferFrom(buyer, sellOrder.relayer, feeAmount);
    }
    // Charge Royalty fee if any
    if (sellOrder.asset.supportsInterface(_INTERFACE_ID_FEES)) {
      address payable[] memory recipients = IHasSecondarySaleFees(sellOrder.asset).getFeeRecipients(sellOrder.assetId);
      uint256[] memory fees = IHasSecondarySaleFees(sellOrder.asset).getFeeBps(sellOrder.assetId);
      if (recipients.length > 0) {
        for (uint256 i = 0; i < recipients.length; i++) {
          uint256 fee = (amount * fees[i]) / 10000;
          totalFee += fee;
          if (sellOrder.paymentToken == address(0)) recipients[i].transfer(fee);
          else IERC20(sellOrder.paymentToken).safeTransferFrom(buyer, recipients[i], fees[i]);
        }
      }
    }
    return totalFee;
  }

  function payReferrerCommission(
    address seller,
    address buyer,
    uint256 amount,
    address paymentToken,
    Relayer memory relayerInfo
  ) internal returns (uint256) {
    if (!relayerInfo.referralEnabled) return 0;

    uint256 referrerCommission = (amount * relayerInfo.referralFee) / 10000;
    address referrer = referrers[seller];
    if (referrer != address(0)) {
      if (paymentToken == address(0)) payable(referrer).transfer(referrerCommission);
      else IERC20(paymentToken).safeTransferFrom(buyer, referrer, referrerCommission);
    }
    emit ReferralPaid(seller, referrer, paymentToken, referrerCommission);
    return referrerCommission;
  }

  /** Transfer Asset */
  function executeAssetTransfer(
    address from,
    address to,
    address asset,
    uint256 assetId,
    uint256 assetAmount,
    AssetType assetType
  ) internal {
    if (assetType == AssetType.ERC721) {
      IERC721(asset).safeTransferFrom(from, to, assetId);
    } else {
      IERC1155(asset).safeTransferFrom(from, to, assetId, assetAmount, "");
    }
  }

  /**
   * @dev Check whether the parameters of a sale are valid
   * @param saleKind Kind of sale
   * @param expirationTime Order expiration time
   * @return Whether the parameters were valid
   */
  function validateParameters(SaleKind saleKind, uint256 expirationTime) public pure returns (bool) {
    /* Auctions must have a set expiration date. */
    return (saleKind == SaleKind.FixedPrice || expirationTime > 0);
  }

  /**
   * @dev Return whether or not an order can be settled
   * @dev Precondition: parameters have passed validateParameters
   * @param listingTime Order listing time
   * @param expirationTime Order expiration time
   */
  function canSettleOrder(uint256 listingTime, uint256 expirationTime) public view returns (bool) {
    return (listingTime < block.timestamp) && (expirationTime == 0 || block.timestamp < expirationTime);
  }

  /** Verify if price for both orders can match
   * @param sell Sell order
   * @param buy Buy Order
   */
  function canPriceMatch(Order memory sell, Order memory buy) internal view returns (bool) {
    return
      sell.saleKind == SaleKind.DutchAuction
        ? buy.basePrice >= calculateDutchAuctionCurrentPrice(sell)
        : buy.basePrice >= sell.basePrice;
  }

  /**
   * @dev Calculate the settlement price of an order
   * @dev Precondition: parameters have passed validateParameters.
   * @param sellOrder Dutch Auction Order
   */
  function calculateDutchAuctionCurrentPrice(Order memory sellOrder) public view returns (uint256 finalPrice) {
    uint256 diff = ((sellOrder.basePrice - sellOrder.reservePrice) * (block.timestamp - sellOrder.listingTime)) /
      (sellOrder.expirationTime - sellOrder.listingTime);
    return sellOrder.basePrice - diff;
  }

  /** This contract should not hold any eth, if sent directly by mistake, should be returned immediately to the sender */
  receive() external payable {
    payable(msg.sender).transfer(msg.value);
  }

  /** This contract should not hold any ERC20 tokens, if sent by mistake, this method can be used to drain them.
        If you are the sender, feel free to contact us, we would be glad to return them :)
        NOTE: Approved tokens for orders cannot be drain by this method! 
    */
  function drainERC20Token(
    IERC20 token,
    uint256 amount,
    address to
  ) external onlyOwner {
    token.safeTransfer(to, amount);
  }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, 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 `from` to `to` 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 from,
        address to,
        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/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/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: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/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() {
        _transferOwnership(_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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/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'
        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
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

// File: @openzeppelin/contracts/utils/introspection/ERC165Checker.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface,
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            _supportsERC165Interface(account, type(IERC165).interfaceId) &&
            !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
        internal
        view
        returns (bool[] memory)
    {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in _interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!_supportsERC165Interface(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     * Interface identification is specified in ERC-165.
     */
    function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
        (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
        if (result.length < 32) return false;
        return success && abi.decode(result, (bool));
    }
}

// File: contracts/exchange/ArrayUtils.sol



// SPDX-License-Identifier: MIT

/*

  Various functions for manipulating arrays in Solidity.
  This library is completely inlined and does not need to be deployed or linked.

*/

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/math/SafeMath.sol";

/**
 * @title ArrayUtils
 * @author Project Wyvern Developers
 */
library ArrayUtils {
  /**
   * Replace bytes in an array with bytes in another array, guarded by a bitmask
   * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower)
   *
   * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed.
   * @param array The original array
   * @param desired The target array
   * @param mask The mask specifying which bits can be changed
   * returns The updated byte array (the parameter will be modified inplace)
   */
  function guardedArrayReplace(
    bytes memory array,
    bytes memory desired,
    bytes memory mask
  ) internal pure {
    require(array.length == desired.length);
    require(array.length == mask.length);

    uint256 words = array.length / 0x20;
    uint256 index = words * 0x20;
    assert(index / 0x20 == words);
    uint256 i;

    for (i = 0; i < words; i++) {
      /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */
      assembly {
        let commonIndex := mul(0x20, add(1, i))
        let maskValue := mload(add(mask, commonIndex))
        mstore(
          add(array, commonIndex),
          or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))
        )
      }
    }

    /* Deal with the last section of the byte array. */
    if (words > 0) {
      /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */
      i = words;
      assembly {
        let commonIndex := mul(0x20, add(1, i))
        let maskValue := mload(add(mask, commonIndex))
        mstore(
          add(array, commonIndex),
          or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))
        )
      }
    } else {
      /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise.
               (bounds checks could still probably be optimized away in assembly, but this is a rare case) */
      for (i = index; i < array.length; i++) {
        array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]);
      }
    }
  }

  /**
   * Test if two arrays are equal
   * Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
   *
   * @dev Arrays must be of equal length, otherwise will return false
   * @param a First array
   * @param b Second array
   * @return Whether or not all bytes in the arrays are equal
   */
  function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) {
    bool success = true;

    assembly {
      let length := mload(a)

      // if lengths don't match the arrays are not equal
      switch eq(length, mload(b))
      case 1 {
        // cb is a circuit breaker in the for loop since there's
        //  no said feature for inline assembly loops
        // cb = 1 - don't breaker
        // cb = 0 - break
        let cb := 1

        let mc := add(a, 0x20)
        let end := add(mc, length)

        for {
          let cc := add(b, 0x20)
          // the next line is the loop condition:
          // while(uint(mc < end) + cb == 2)
        } eq(add(lt(mc, end), cb), 2) {
          mc := add(mc, 0x20)
          cc := add(cc, 0x20)
        } {
          // if any of these checks fails then arrays are not equal
          if iszero(eq(mload(mc), mload(cc))) {
            // unsuccess:
            success := 0
            cb := 0
          }
        }
      }
      default {
        // unsuccess:
        success := 0
      }
    }

    return success;
  }

  /**
   * Unsafe write byte array into a memory location
   *
   * @param index Memory location
   * @param source Byte array to write
   * @return End memory index
   */
  function unsafeWriteBytes(uint256 index, bytes memory source) internal pure returns (uint256) {
    if (source.length > 0) {
      assembly {
        let length := mload(source)
        let end := add(source, add(0x20, length))
        let arrIndex := add(source, 0x20)
        let tempIndex := index
        for {

        } eq(lt(arrIndex, end), 1) {
          arrIndex := add(arrIndex, 0x20)
          tempIndex := add(tempIndex, 0x20)
        } {
          mstore(tempIndex, mload(arrIndex))
        }
        index := add(index, length)
      }
    }
    return index;
  }

  /**
   * Unsafe write address into a memory location
   *
   * @param index Memory location
   * @param source Address to write
   * @return End memory index
   */
  function unsafeWriteAddress(uint256 index, address source) internal pure returns (uint256) {
    uint256 conv = uint256(uint160(source)) << 0x60;
    assembly {
      mstore(index, conv)
      index := add(index, 0x14)
    }
    return index;
  }

  /**
   * Unsafe write uint into a memory location
   *
   * @param index Memory location
   * @param source uint to write
   * @return End memory index
   */
  function unsafeWriteUint(uint256 index, uint256 source) internal pure returns (uint256) {
    assembly {
      mstore(index, source)
      index := add(index, 0x20)
    }
    return index;
  }

  /**
   * Unsafe write uint8 into a memory location
   *
   * @param index Memory location
   * @param source uint8 to write
   * @return End memory index
   */
  function unsafeWriteUint8(uint256 index, uint8 source) internal pure returns (uint256) {
    assembly {
      mstore8(index, source)
      index := add(index, 0x1)
    }
    return index;
  }
}

// File: contracts/exchange/IAtomicMatchHandler.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IAtomicMatchHandler {
  function onAtomicMatch(
    address asset,
    uint256 assetId,
    uint256 assetAmount,
    address seller,
    address buyer,
    uint256 price
  ) external;
}

// File: contracts/exchange/IHasSecondarySaleFees.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IHasSecondarySaleFees {
  function getFeeRecipients(uint256 id) external view returns (address payable[] memory);

  function getFeeBps(uint256 id) external view returns (uint256[] memory);
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

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: @openzeppelin/contracts/utils/Context.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

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) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/utils/Address.sol



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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

        (bool success, bytes memory returndata) = target.delegatecall(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/utils/math/SafeMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)

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 generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @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;
        }
    }
}