// File: /contracts/PaymentSender.sol



// SPDX-License-Identifier: GPL-3.0
// solhint-disable-next-line
pragma solidity 0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

/// @notice Contract to receive and distribute payments on ETH or ERC20 tokens

contract PaymentSender is
  ERC1155Holder,
  IERC721Receiver,
  Ownable,
  ReentrancyGuard
{
  /// @notice ETH amount still not distributed
  uint256 public reserveBalance;
  /// @notice ETH amount for contributions (coming from taxes)
  uint256 public contributionsBalance;
  /// @notice Perc of taxes to take on deposits
  uint256 public taxesPerc;
  /// @notice Address of the wallet that signs messages
  address public secret;

  /// @notice Mapping of ETH balances for each wallet address
  mapping(address => uint256) public ethBalance;

  /// @notice Mapping of used signatures
  mapping(bytes => bool) public usedSignatures;
  /// @notice Mapping of allowed wallets
  mapping(address => bool) public isAllowed;

  /// @notice Event emitted when ETH is deposited to reserve balance
  event Deposit(uint256 amount, address operator);
  /// @notice Event emitted when ETH is deposited to contributions balance
  event Contribution(uint256 amount, address operator);
  /// @notice Event emitted when ETH is distributed
  event Distribute(uint256[] amounts, address[] recipients, address operator);
  /// @notice Event emitted ETH is sent
  event SendETH(uint256[] amounts, address[] recipients, address operator);
  /// @notice Event emitted when someone withdraws ETH
  event WithdrawETH(uint256 amount, address recipient, address operator);

  /// @notice Event emitted when someone withdraws ERC20 tokens
  event WithdrawERC20(
    address token,
    uint256 amount,
    address recipient,
    address operator
  );

  /// @notice Event emitted when someone withdraws ERC721 or ERC1155 tokens
  event WithdrawNFT(
    address token,
    uint256 tokenId,
    uint256 amount,
    address recipient,
    address operator
  );

  /// @notice Event emitted when a new signer is set
  event SetSigner(address signer);

  /// @notice Event emitted when a new allowed wallet is set
  event SetAllowed(address wallet, bool allowed);

  /// @notice Event emitted when a signature is marked as used without withdrawing anything
  event UseSignature(bytes signature);

  /// @notice Event emitted when ETH is unassigned from a recipient
  event UnassignETH(uint256 amount, address recipient);

  /// @notice Event emitted when taxes percentage is set
  event SetTaxesPerc(uint256 taxesPerc);

  constructor() {}

  /// @notice Fall back function to receive ETH
  receive() external payable {
    depositToReserve(msg.value, taxesPerc);
  }

  /// @notice modifier of wallets allowed to use restricted functions
  modifier onlyAllowed() {
    require(
      isAllowed[msg.sender] || msg.sender == owner(),
      "onlyAllowed: Not allowed"
    );
    _;
  }

  /// @notice Function to deposit ETH and distribute it to recipients
  /// @param amounts Amounts of ETH to distribute
  /// @param recipients Addresses to distribute ETH to
  /// @dev Only assign the ETH to the recipients, doesn't send it, use sendFunds for that
  function distribute(
    uint256[] memory amounts,
    address[] memory recipients,
    uint256 taxToTake,
    bool fromContributions
  ) external payable onlyAllowed nonReentrant {
    _handleFunds(amounts, recipients, true, taxToTake, fromContributions);

    emit Distribute(amounts, recipients, msg.sender);
  }

  /// @notice Function to send ETH to recipients
  /// @param amounts Amounts of ETH to send
  /// @param recipients Addresses to send ETH to
  /// @dev Only send the ETH to the recipients, doesn't assign it, use distribute for that
  function sendFunds(
    uint256[] memory amounts,
    address[] memory recipients,
    uint256 taxToTake,
    bool fromContributions
  ) external payable onlyAllowed nonReentrant {
    _handleFunds(amounts, recipients, false, taxToTake, fromContributions);

    emit SendETH(amounts, recipients, msg.sender);
  }

  /// @notice Function to withdraw ETH
  /// @param amount Amount of ETH to withdraw
  /// @param recipient Address to withdraw ETH to
  /// @dev Withdraw from the ETH balance of the sender
  function withdrawETH(uint256 amount, address payable recipient) external {
    require(amount > 0, "withdraw: Amount must be greater than 0");
    require(
      ethBalance[msg.sender] >= amount,
      "withdraw: Not enough ETH in your balance to withdraw"
    );

    ethBalance[msg.sender] -= amount;

    recipient.transfer(amount);

    emit WithdrawETH(amount, recipient, msg.sender);
  }

  /// @notice use a signature to withdraw ETH without having any assigned
  /// @param amount Amount of ETH to withdraw
  /// @param recipient Address to withdraw ETH to
  /// @param checkId Id to check if the signature was used
  /// @param signature Signature to use
  function withdrawETHWithSignature(
    uint256 amount,
    address recipient,
    uint256 checkId,
    bytes memory signature
  ) external {
    require(
      amount <= reserveBalance,
      "withdrawETHWithSignature: Not enough ETH in reserve to withdraw"
    );

    bytes32 hash = keccak256(
      abi.encode(recipient, amount, checkId, "withdrawETHWithSignature")
    );

    _handleSignature(hash, signature);

    reserveBalance -= amount;

    payable(recipient).transfer(amount);

    emit WithdrawETH(amount, recipient, msg.sender);
  }

  /// @notice use a signature to withdraw ERC20 tokens
  /// @param token Address of the ERC20 token
  /// @param amount Amount of ERC20 tokens to withdraw
  /// @param recipient Address to withdraw ERC20 tokens to
  /// @param checkId Id to check if the signature was used
  /// @param signature Signature to use
  function withdrawERC20WithSignature(
    address token,
    uint256 amount,
    address recipient,
    uint256 checkId,
    bytes memory signature
  ) external {
    require(
      amount <= IERC20(token).balanceOf(address(this)),
      "withdrawERC20WithSignature: Not enough ERC20 tokens in reserve to withdraw"
    );

    bytes32 hash = keccak256(
      abi.encode(
        token,
        recipient,
        amount,
        checkId,
        "withdrawERC20WithSignature"
      )
    );

    _handleSignature(hash, signature);

    IERC20(token).transfer(recipient, amount);

    emit WithdrawERC20(token, amount, recipient, msg.sender);
  }

  /// @notice use a signature to withdraw ERC721 or ERC1155 tokens
  /// @param token Address of the ERC721 or ERC1155 token
  /// @param tokenId Id of the ERC721 or ERC1155 token
  /// @param amount Amount of ERC1155 token to withdraw (ERC721 = 0, amount not required)
  /// @param recipient Address to withdraw ERC721 or ERC1155 tokens to
  /// @param checkId Id to check if the signature was used
  /// @param signature Signature to use
  function withdrawNFTWithSignature(
    address token,
    uint256 tokenId,
    uint256 amount,
    address recipient,
    uint256 checkId,
    bytes memory signature
  ) external {
    bytes32 hash = keccak256(
      abi.encode(
        token,
        tokenId,
        recipient,
        amount,
        checkId,
        "withdrawNFTWithSignature"
      )
    );

    _handleSignature(hash, signature);

    if (amount == 0) {
      require(
        IERC721(token).ownerOf(tokenId) == address(this),
        "withdrawNFTWithSignature: Not enough ERC721 tokens in reserve to withdraw"
      );

      IERC721(token).safeTransferFrom(address(this), recipient, tokenId);
    } else {
      require(
        amount <= IERC1155(token).balanceOf(address(this), tokenId),
        "withdrawNFTWithSignature: Not enough ERC1155 tokens in reserve to withdraw"
      );

      IERC1155(token).safeTransferFrom(
        address(this),
        recipient,
        tokenId,
        amount,
        ""
      );
    }

    emit WithdrawNFT(token, tokenId, amount, recipient, msg.sender);
  }

  /// INTERNAL FUNCTIONS

  /// @notice Helper function to deposit ETH
  function depositToReserve(uint256 amount, uint256 taxToTake) internal {
    if (taxToTake > 0) {
      uint256 taxes = (amount * taxToTake) / 10000;
      contributionsBalance += taxes;
      amount -= taxes;
      emit Contribution(taxes, msg.sender);
    }

    reserveBalance += amount;

    emit Deposit(amount, msg.sender);
  }

  function _handleSignature(bytes32 hash, bytes memory signature) internal {
    require(
      _verifyHashSignature(hash, signature),
      "handleSignature: Invalid signature"
    );

    require(
      !usedSignatures[signature],
      "handleSignature: Signature already used"
    );

    usedSignatures[signature] = true;
  }

  /// @notice Function to deposit ETH and distribute it to recipients
  /// @param amounts Amounts of ETH to handle
  /// @param recipients Addresses to handle ETH for
  /// @param isDistribute Whether to distribute (true) or send (false)
  function _handleFunds(
    uint256[] memory amounts,
    address[] memory recipients,
    bool isDistribute,
    uint256 taxToTake,
    bool fromContributions
  ) internal {
    require(
      amounts.length == recipients.length,
      "handleFunds: Arrays must have the same length"
    );

    if (msg.value > 0) {
      depositToReserve(msg.value, taxToTake);
    }

    uint256 totalAmount;

    for (uint256 i = 0; i < amounts.length; i++) {
      uint256 amount = amounts[i];
      totalAmount += amount;

      if (isDistribute) {
        ethBalance[recipients[i]] += amount;
      } else {
        payable(recipients[i]).transfer(amount);
      }
    }

    if (fromContributions) {
      require(
        totalAmount <= contributionsBalance,
        "handleFunds: Not enough ETH in contributions balance"
      );

      contributionsBalance -= totalAmount;
    } else {
      require(
        totalAmount <= reserveBalance,
        "handleFunds: Not enough ETH in reserve balance"
      );

      reserveBalance -= totalAmount;
    }
  }

  /// OWNER FUNCTIONS

  /// @notice Function to set a new signer
  /// @param newSigner: Address of the new signer
  /// @dev Only the owner can set a new signer
  function setSigner(address newSigner) external onlyOwner {
    require(newSigner != address(0), "Invalid address");
    secret = newSigner;

    emit SetSigner(newSigner);
  }

  /// @notice Function to set a new allowed wallet
  /// @param wallet: Address of the new allowed wallet
  /// @param allowed: Boolean to set if the wallet is allowed or not
  /// @dev Only the owner can set a new allowed wallet
  function setAllowed(address wallet, bool allowed) external onlyOwner {
    require(wallet != address(0), "Invalid address");
    isAllowed[wallet] = allowed;

    emit SetAllowed(wallet, allowed);
  }

  /// @notice Function to set the taxes percentage
  /// @param _taxesPerc: New taxes percentage
  /// @dev Only the owner can set the taxes percentage
  function setTaxesPerc(uint256 _taxesPerc) external onlyOwner {
    require(_taxesPerc <= 10000, "setTaxesPerc: Taxes percentage too high");

    taxesPerc = _taxesPerc;

    emit SetTaxesPerc(_taxesPerc);
  }

  /// @notice Mark a signature as used without withdrawing anything
  /// @param signature Signature to use
  function useSignature(bytes memory signature) external nonReentrant {
    require(!usedSignatures[signature], "useSignature: Signature already used");

    usedSignatures[signature] = true;

    emit UseSignature(signature);
  }

  /// @notice Unassign ETH from a recipient
  /// @param amount Amount of ETH to unassign
  /// @param recipient Address to unassign ETH from
  function unassignETH(uint256 amount, address recipient) external onlyOwner {
    require(
      ethBalance[recipient] >= amount,
      "unassignETH: Not enough ETH in recipient balance"
    );

    ethBalance[recipient] -= amount;

    reserveBalance += amount;

    emit UnassignETH(amount, recipient);
  }

  /// EMERGENCY FUNCTIONS

  /// @notice Emergency function to withdraw ETH
  function emergencyWithdrawETH() external onlyOwner {
    uint256 contractBalance = address(this).balance;

    payable(msg.sender).transfer(reserveBalance);

    emit WithdrawETH(contractBalance, msg.sender, msg.sender);
  }

  /// @notice Emergency function to withdraw ERC20 tokens
  /// @param token Address of the ERC20 token
  function emergencyWithdrawERC20(address token) external onlyOwner {
    uint256 contractBalance = IERC20(token).balanceOf(address(this));

    require(
      contractBalance > 0,
      "emergencyWithdrawERC20: No tokens to withdraw"
    );

    IERC20(token).transfer(msg.sender, contractBalance);

    emit WithdrawERC20(token, contractBalance, msg.sender, msg.sender);
  }

  /// @notice Emergency function to withdraw ERC721 or ERC1155 tokens
  /// @param token Address of the ERC721 or ERC1155 token
  /// @param tokenId Id of the ERC721 or ERC1155 token
  /// @param amount Amount of ERC1155 token to withdraw (ERC721 = 0, amount not required)
  function emergencyWithdrawNFT(
    address token,
    uint256 tokenId,
    uint256 amount
  ) external onlyOwner {
    if (amount == 0) {
      IERC721(token).safeTransferFrom(address(this), msg.sender, tokenId);
    } else {
      IERC1155(token).safeTransferFrom(
        address(this),
        msg.sender,
        tokenId,
        amount,
        ""
      );
    }

    emit WithdrawNFT(token, tokenId, amount, msg.sender, msg.sender);
  }

  /// @notice Internal function to check if a signature is valid
  /// @param freshHash: Hash to check
  /// @param signature: Signature to check
  function _verifyHashSignature(
    bytes32 freshHash,
    bytes memory signature
  ) internal view returns (bool) {
    bytes32 hash = keccak256(
      abi.encodePacked("\x19Ethereum Signed Message:\n32", freshHash)
    );

    bytes32 r;
    bytes32 s;
    uint8 v;

    if (signature.length != 65) {
      return false;
    }
    assembly {
      r := mload(add(signature, 32))
      s := mload(add(signature, 64))
      v := byte(0, mload(add(signature, 96)))
    }

    if (v < 27) {
      v += 27;
    }

    address signer = address(0);
    if (v == 27 || v == 28) {
      // solium-disable-next-line arg-overflow
      signer = ecrecover(hash, v, r, s);
    }
    return secret == signer;
  }

  // TODO: if we want to support ERC721, we need to implement this function
  function onERC721Received(
    address,
    address,
    uint256,
    bytes memory
  ) external virtual override returns (bytes4) {
    return this.onERC721Received.selector;
  }
}

// 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/introspection/ERC165.sol



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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

// File: @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/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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`.
     *
     * 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;

    /**
     * @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 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * 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 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 the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @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);
}

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



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @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);
}

// File: @openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol



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

pragma solidity ^0.8.0;

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

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

// File: @openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol



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

pragma solidity ^0.8.0;

import "./ERC1155Receiver.sol";

/**
 * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 *
 * @dev _Available since v3.1._
 */
contract ERC1155Holder is ERC1155Receiver {
    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;
    }
}

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



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

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: 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.
     *
     * NOTE: 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/token/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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 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/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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 Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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);
    }
}