// File: contracts/Entangler.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol"; // Included for marketplaces
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";

// =============================================================================
// =============================== STRUCTS =====================================
/**
* @notice The TokenType struct holds all the data that defines a collection of
* tokens within this contract
* @param id  The id of the collection
* @param supplyCap  The total number of tokens of the collection type that can
* exist
* @param cost  The cost to mint a token of the collection
* @param initialMintAmount  The amount of tokens to premint when the collection
* is created
* @param defaultStorageSchema  The default location/protocol used to store and
* retrieve the metadata of tokens in the collection
* @param totalSupply  The total circulating supply of the collection (i.e. the
* amount of tokens that have been minted from the collection so far)
* @param maxMultiplier  Nft collections that are part of this contract pay
* royalties to their beneficaries (charitable organizations that align with the
* collection's mandates). A multiplier can be applied to the royalty values so
* that a higer portion of a transaction goes to the beneficaries and less goes
* to the other recipient of the transaction. The max multiplier ensures that the
* multiplier never causes the royalty protion to be more than 100% of the
* transaction's value
* @param maxMint  The max number of tokens that can be minted from the collection
* in a single mint transaction
* @param fungible  True if it is a collection of fungible tokens, false if it
* is a collection of non-fungible tokens
* @param locked  True if the collection has been locked, false if it has not been.
* When a collection has been locked its supplyCap, cost, maxMint and mintable
* values can no longer be modified
* @param initialMintTo  Recipient of premint tokens
* @param mandates  Mandates that define the mission/purpose of a collection
* @param baseUris  The uri strings for retrieving the metadata of the tokens in
* the collection. Follows the erc1155 id substitution format
*/
struct TokenType {
  uint256 id;
  uint256 supplyCap;
  uint256 cost;
  uint256 initialMintAmount;
  string defaultStorageSchema;
  uint256 totalSupply;
  uint256 maxMultiplier;
  uint256 maxMint;
  bool fungible;
  bool mintable;
  bool locked;
  address initialMintTo;
  Mandate[] mandates;
  mapping(string => string[]) baseUris;
}

/**
* @notice Mandates define the purpose around which a colection of nfts is aligned
* @param description  A description of the cause that the mandate supports
* @param receiver  The ethereum address that's used for collecting funds that
* will be used for supporting charitable organizations whose work is aligned with
* the purpose of the mandate
*/
struct Mandate {
  string description;
  address payable receiver;
}

/**
* @dev  Data format that is passed to the contract to create new collections
*/
struct NewTokenType {
  uint256 id;
  uint256 supplyCap;
  uint256 cost;
  uint256 initialMintAmount;
  string defaultStorageSchema;
  uint256 maxMultiplier;
  uint256 maxMint;
  bool fungible;
  bool mintable;
  bool locked;
  address initialMintTo;
  Mandate[] mandates;
}


// =============================================================================
// ================== LIBRARY FOR CREATING NEW TOKEN TYPES =====================
library TokenTypeLib {
  function createTokenType(
    TokenType storage self,
    NewTokenType memory newTokenType,
    string[] calldata startingStorageSchemas,
    string[] calldata startingBaseUris
  ) public {
    self.id = newTokenType.id;
    self.fungible = newTokenType.fungible;
    self.supplyCap = newTokenType.supplyCap;
    self.cost = newTokenType.cost;
    self.mintable = newTokenType.mintable;
    self.maxMultiplier = newTokenType.maxMultiplier;
    self.maxMint = newTokenType.maxMint;
    self.initialMintTo = newTokenType.initialMintTo;
    self.initialMintAmount = newTokenType.initialMintAmount;
    self.defaultStorageSchema = newTokenType.defaultStorageSchema;
    self.locked = newTokenType.locked;

    // Set the mandates of the new token type
    for(uint i = 0; i < newTokenType.mandates.length; i++) {
      Mandate memory m;

      m.description = newTokenType.mandates[i].description;
      m.receiver = newTokenType.mandates[i].receiver;

      self.mandates.push(m);
    }

    // Set the storage schema mappings for the new token type
    for(uint i = 0; i < startingStorageSchemas.length; i++) {
      self.baseUris[startingStorageSchemas[i]].push(string(abi.encodePacked(startingBaseUris[i], '{id}.json')));
    }
  }
}


// =============================================================================
// ============================ CORE CONTRACT ==================================
contract Entangler is ERC1155, ERC1155Receiver, IERC2981, AccessControl, Ownable {
  using TokenTypeLib for TokenType;

  /* Mapping of collection ids (typeId) to the data that defines that collection */
  mapping(uint256 => TokenType) public tokenTypes;

  /**
  * Sequential records of the transaction logs that were used to tally up the
  * amounts due to beneficiries
  */
  string[] public beneficiaryAccountingRecords;

  /**
  * The merkle root against which beneficiries can claim their allocations of
  * funds
  */
  bytes32 public claimsMerkleRoot;

  /* List of claims that have been redeemed so that they can't be redeemed again */
  mapping(bytes32 => bool) beneficaryFundsClaimed;

  /**
  * This is the deliminator in a non-fungible token id. Numbers in digits 1-7
  * repersent individual token ids. Numbers from the 8th digit onward denote the
  * collection to which the individual token belongs
  */
  uint256 constant public supplyCapPerTokenType = 10000000;

  /**
  * Token ids can be no larger than this value. The length of this value is
  * also the number of digits that must be reverved for token ids in the least
  * significant digits of a value that is being sent to this contract as a
  * royalty payment so that the payment can be attributed the nft which it
  * involves
  */
  uint256 public tokenIdSpace;

  /* Percentages are calculated in basis points (10000bps = 100%) */
  uint256 constant public percentDenominator = 10000;

  /**
  * Current amount that third parties have stored in the contract and can
  * withdraw at any time
  */
  mapping(address => uint256) public withdrawalAmounts;

  /**
  * The royalty amounts of each nft, in basis points. Each of the token's
  * royalties correspond to the mandates of the collection to which the token
  * belongs
  */
  mapping(uint => uint16[]) public royalties;

  /**
  * Beneficary withdrawals will need to be paused for the time inbetween taking
  * a snapshot to determine new withdrawal amounts and the commitment of the new
  * merkle tree root
  */
  bool public beneficaryWithdrawalsPaused = false;

  /* Address used by the contract owner to withdraw mint payments from the contract */
  address payable ownerWithdrawalAddress;

  /* Uri of the contract level metadata */
  string public contractUri;


  // =============================== ROLES =====================================
  bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
  bytes32 public constant ACCOUNTANT_ROLE = keccak256("ACCOUNTANT_ROLE");
  bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE");


  // =============================== EVENTS ====================================
  /**
  * @dev  The royaltyReceived event will be emitted any time that ether is sent
  * to this contract that is intended as a royalty payment to be donated to the
  * beneficaries of an nft. Attribution of which nfts are responsiable for which
  * payments is done off-chain using these events. In order to tell which nft is
  * responsible for the donation, the id of the nft must be included in the least
  * significant digits of the value of the transaction
  */
  event royaltyReceived(uint256 indexed amount);

  /**
  * @dev  Erc1155 royalty received events are used for the same purpose as base
  * ether royalty received events, except that the id of the nft involved can be
  * explicitly included in the data field of the transaction in which case
  * including the nfts id in the value of the transaction is not necessary
  */
  event erc1155RoyaltyReceived(address indexed contractAddress, uint256 indexed token, uint256 indexed amount, bytes id);
  event erc1155BatchRoyaltyReceived(address indexed contractAddress, uint256[] tokens, uint256[] amounts, bytes ids);

  /**
  * @dev  Royalty withdrawn events are used to monitor when beneficaries have
  * claimed their funds from the contract so that any unclaimed allotments can
  * be rolled over into the next merkle tree of claims
  */
  event royaltyWithdrawn(address indexed beneficary, uint256 indexed amount);
  event erc20RoyaltyWithdrawn(address indexed contractAddress, address indexed beneficary, uint256 indexed amount);
  event erc1155RoyaltyWithdrawn(address indexed contractAddress, uint256 indexed token, address indexed beneficary, uint256 amount);

  /**
  * @dev  The beneficaryClaimsUpdated event signals that a new merkle tree root
  * has been committed to the contract and there may be new allotments that
  * beneficaries can claim
  */
  event beneficaryClaimsUpdated(bytes32 indexed merkleRoot, uint256 indexed accountsRecordIndex);

  /**
  * @dev  The tokenIdSpaceChanged event signals that the length of the token id
  * space has changed. As a result the number of digits that must be reserved for
  * token ids in the value of transactions must be updated accordingly
  */
  event tokenIdSpaceChanged(uint256 indexed newTokenIdSpace);

  /**
  * @notice  The storageSchemaAdded event signals that a new storage schema for
  * metadata has been added to a collection
  */
  event storageSchemaAdded(uint256 typeId, string storageSchema);


  // ============================= MODIFIERS ===================================
  /**
  * @notice  Checks to make sure that a mint request is valid as per the rules of
  * this contract and the rules of the collection to which the tokens belong
  * @param typeId  Specifies the collection to mint from
  * @param count  The number of tokens to be minted
  */
  modifier preMintChecks(uint256 typeId, uint256 count) {
    require(tokenTypes[typeId].mintable, "Token not currently mintable");
    require(count > 0, "Mint amount cannot be less than one");
    require(count <= tokenTypes[typeId].maxMint, "Mint amount too high");
    require(tokenTypes[typeId].totalSupply + count <= tokenTypes[typeId].supplyCap, "Mint amount exceeds total supply of the token type");
    require(msg.value == tokenTypes[typeId].cost * count, "Not enough or too many funds provided");
    _;
  }

  /**
  * @notice  Checks to make sure that a new collection can be validly created
  */
  modifier tokenCreationChecks(
    NewTokenType memory newTokenType,
    string[] calldata startingStorageSchemas,
    string[] calldata startingBaseUris
  ) {
    require(tokenTypes[newTokenType.id].totalSupply == 0, "This typeId has already been set");
    require(tokenTypes[newTokenType.id].supplyCap == 0, "Token type has already been initialized");
    require(startingStorageSchemas.length == startingBaseUris.length, "Each uri schema must be initialized");
    require(newTokenType.id % supplyCapPerTokenType == 0, "Token type id invalid");

    if(!newTokenType.fungible) {
      require(newTokenType.supplyCap < supplyCapPerTokenType, "Cannot exceed the universal supply cap of this contract");
    }
    _;
  }

  /**
  * @notice  Checks that everything is valid when setting the royalties of a token
  * @param tokenId  Id of the token for which to set royalties
  * @param _royalties  Array of royalty values to be set. One royalty value per
  * beneficary of the collection to which the token belongs. Royalty values are
  * in basis points
  */
  modifier setTokenRoyaltiesCheck(uint256 tokenId, uint16[] calldata _royalties) {
    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;
    require(tokenTypes[typeId].mandates.length == _royalties.length, "Tokens must pay all the beneficaries of their type");
    require(!tokenTypes[typeId].fungible, "Only non fungible tokens pay royalties");
    require(royalties[tokenId].length == 0, "A tokens royalties can only ever be set once");
    tokenId = tokenId - typeId;
    require(tokenId < tokenTypes[typeId].totalSupply, "Token has not been minted yet");

    for(uint i = 0; i < _royalties.length; i++) {
      require(_royalties[i] < uint16(percentDenominator), "Maximum royalty is 10000 basis points (100%)");
    }
    _;
  }

  /**
  * @notice  Ensures that certain parameters of a collection are no longer mutable
  * after that collection has been locked
  * @param typeId  Id of the collection
  */
  modifier isLocked(uint256 typeId) {
    require(!tokenTypes[typeId].locked);
    _;
  }

  /**
  * @notice  Pauses the ability to make withdrawals via merkle tree proof. This
  * is needed so that unclaimed amounts included in one merkle tree root can be
  * rolled into the next merkle tree root without risk of the funds being claimed
  * in the time between the creation of the mew merkle root and its commitment
  * to the contract. If this were to happen, the funds could be claimed twice;
  * once using the first merkle tree root and once using the second merkle tree
  * root
  */
  modifier withdrawalsPaused() {
    require(!beneficaryWithdrawalsPaused, "Beneficary withdrawals are paused for a snapshot");
    _;
  }

  // ===========================================================================
  // ========================== CORE FUNCTIONS =================================
  constructor(
    string memory defaultUri,
    address defaultAdminAddress,
    address operatorAddress,
    address lockerAddress,
    address accountantAddress,
    address payable _ownerWithdrawalAddress,
    uint256 _tokenIdSpace,
    string memory _contractUri
  )
    ERC1155(defaultUri)
  {
    _grantRole(DEFAULT_ADMIN_ROLE, defaultAdminAddress);
    _grantRole(OPERATOR_ROLE, operatorAddress);
    _grantRole(LOCKER_ROLE, lockerAddress);
    _grantRole(ACCOUNTANT_ROLE, accountantAddress);

    ownerWithdrawalAddress = _ownerWithdrawalAddress;
    tokenIdSpace = _tokenIdSpace;
    contractUri = _contractUri;

    emit tokenIdSpaceChanged(tokenIdSpace);
  }

  function supportsInterface(bytes4 interfaceId)
    public
    view
    virtual
    override(ERC1155, ERC1155Receiver, AccessControl, IERC165)
    returns (bool)
  {
    return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
  }

  /**
  * @notice  Mints tokens of the specified collection
  * @param to  The address that the tokens will be minted to
  * @param typeId  The nft collection to mint from
  * @param count  The number of nfts to mint
  */
  function mint(address to, uint256 typeId, uint256 count)
    public
    payable
    preMintChecks(typeId, count)
  {
    if(tokenTypes[typeId].fungible) {
      tokenTypes[typeId].totalSupply += count;
      _mint(to, typeId, count, "");
    } else {
      for(uint i = 0; i < count; i++) {
        uint256 tokenId = typeId + tokenTypes[typeId].totalSupply;
        tokenTypes[typeId].totalSupply++;
        _mint(to, tokenId, 1, "");
      }
    }
  }


  // ============================== PAYMENTS ===================================
  /**
  * @notice  This function will be called if ether is sent directly to the
  * contract (as opposed to sending ether to the contract by calling a specific
  * function of the contract). If the nft id has been properly included in the
  * least significant digits of the value of the transaction, the full value of
  * the transaction will be attributed to that nft
  */
  receive() external payable {
    emit royaltyReceived(msg.value);
  }

  /**
  * @dev  Allows for transactions involving an nft to be split so that royalty
  * payments are made and the rest of the value is stored in the contract and
  * can be withdrawn by the recipient of the transaction at any time (ex. an
  * nft has been incorporated into a game. An in-game purchase involving the nft
  * is made. The nfts royalties are taken from the transaction and the rest of
  * the value is stored in this contract to be claimed at any time by the game's
  * developer)
  */
  function payWithRoyalties(uint256 tokenId, address recipient, uint256 multiplier)
    external
    payable
  {
    require(royalties[tokenId].length > 0, 'Token royalties not set');
    require(msg.value >= tokenId, 'Value must be at least the tokenId');

    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;

    require(multiplier >= 1, "Multiplier too low");
    require(multiplier <= tokenTypes[typeId].maxMultiplier, "Multiplier too high");

    uint256 amountWithMultiplier = msg.value * multiplier;
    (, uint256 royaltyAmount) = royaltyInfo(tokenId, amountWithMultiplier);

    require(msg.value >= royaltyAmount);

    withdrawalAmounts[recipient] += msg.value - royaltyAmount;

    emit royaltyReceived(royaltyAmount);
  }

  /**
  * @dev  Allows third parties to withdraw their ether from the contract.
  * Withdraws the total amount of ether that they currently have waiting for
  * them in the contract
  * @param withdrawalAddress  The address of the party with ether stored in the
  * contract
  */
  function withdraw(address withdrawalAddress) external {
    require(withdrawalAmounts[withdrawalAddress] > 0, "Account does not have any ether allocated to it");

    uint256 withdrawalAmount = withdrawalAmounts[withdrawalAddress];
    withdrawalAmounts[withdrawalAddress] = 0;

    payable(withdrawalAddress).transfer(withdrawalAmount);
  }

  /**
  * @dev  Allows beneficaries to withdraw ether from the contract using a merkle
  * proof. The parameters must match the values that were included in the merkle
  * tree
  * @param beneficary  The address where the beneficary's funds will be sent
  * @param amount  The amount of ether to be transferred
  * @param merkleProof  The merkle proof containing sibling hashes on the branch
  * from the leaf that is being claimed to the root of the merkle tree
  */
  function withdraw(address beneficary, uint256 amount, bytes32[] calldata merkleProof)
    external
    withdrawalsPaused()
  {
    bytes32 leaf = keccak256(abi.encodePacked(beneficary, amount));
    bytes32 claimReceipt = keccak256(abi.encodePacked(leaf, claimsMerkleRoot));

    require(!beneficaryFundsClaimed[claimReceipt], "Claim already made");
    require(MerkleProof.verify(merkleProof, claimsMerkleRoot, leaf), "Merkle proof failed");

    beneficaryFundsClaimed[claimReceipt] = true;
    emit royaltyWithdrawn(beneficary, amount);

    payable(beneficary).transfer(amount);
  }

  /**
  * @dev  Allows beneficaries to withdraw erc20 tokens from the contract using a
  * merkle tree proof. The parameters must match the values that were included in
  * the merkle tree
  * @param beneficary  The address where the beneficary's funds will be sent
  * @param contractAddress  The address of the erc20 contract that administers
  * the tokens being used in the transaction
  * @param amount  The amount of the token to be transferred
  * @param merkleProof  The merkle proof containing sibling hashes on the branch
  * from the leaf that is being claimed to the root of the merkle tree
  */
  function withdrawErc20(address beneficary, address contractAddress, uint256 amount, bytes32[] calldata merkleProof)
    external
    withdrawalsPaused()
  {
    bytes32 leaf = keccak256(abi.encodePacked(beneficary, contractAddress, amount));
    bytes32 claimReceipt = keccak256(abi.encodePacked(leaf, claimsMerkleRoot));

    require(!beneficaryFundsClaimed[claimReceipt], "Claim already made");
    require(MerkleProof.verify(merkleProof, claimsMerkleRoot, leaf), "Merkle proof failed");

    beneficaryFundsClaimed[claimReceipt] = true;
    emit erc20RoyaltyWithdrawn(contractAddress, beneficary, amount);

    require(IERC20(contractAddress).transfer(beneficary, amount));
  }

  /**
  * @dev  Allows beneficaries to withdraw erc1155 tokens from the contract using
  * a merkle tree proof. The parameters must match the values that were included
  * in the merkle tree
  * @param beneficary  The address where the beneficary's funds will be sent
  * @param contractAddress  The address of the erc1155 contract that administers
  * the tokens being used in the transaction
  * @param token  The specific token of the erc1155 contract that is to be used
  * in this transaction
  * @param amount  The amount of the token to be transferred
  * @param merkleProof  The merkle proof containing sibling hashes on the branch
  * from the leaf that is being claimed to the root of the merkle tree
  */
  function withdrawErc1155(
    address beneficary,
    address contractAddress,
    uint256 token,
    uint256 amount,
    bytes32[] calldata merkleProof
  )
    external
    withdrawalsPaused()
  {
    bytes32 leaf = keccak256(abi.encodePacked(beneficary, contractAddress, token, amount));
    bytes32 claimReceipt = keccak256(abi.encodePacked(leaf, claimsMerkleRoot));

    require(!beneficaryFundsClaimed[claimReceipt], "Claim already made");
    require(MerkleProof.verify(merkleProof, claimsMerkleRoot, leaf), "Merkle proof failed");

    beneficaryFundsClaimed[claimReceipt] = true;
    emit erc1155RoyaltyWithdrawn(contractAddress, token, beneficary, amount);

    IERC1155(contractAddress).safeTransferFrom(address(this), beneficary, token, amount, "");
  }

  /**
  * @dev  Allows beneficaries to make batch erc1155 withdrawals. The parameters
  * must match the values that were included in the merkle tree
  * @param beneficary  The address where the beneficary's funds will be sent
  * @param contractAddress  The address of the erc1155 contract that administers
  * the tokens being used in the transaction
  * @param tokens The array specific tokens of the erc1155 contract that are to
  * be used in this transaction
  * @param amounts  Array of the amounts of each token to be transferred
  * @param merkleProofs  The merkle proofs containing sibling hashes on the
  * branch from the leaves that are being claimed to the root of the merkle tree
  */
  function withdrawErc1155Batch(
    address beneficary,
    address contractAddress,
    uint256[] calldata tokens,
    uint256[] calldata amounts,
    bytes32[][] calldata merkleProofs
  )
    external
    withdrawalsPaused()
  {
    require(tokens.length == amounts.length);

    for(uint i = 0; i < tokens.length; i++) {
      bytes32 leaf = keccak256(abi.encodePacked(beneficary, contractAddress, tokens[i], amounts[i]));
      bytes32 claimReceipt = keccak256(abi.encodePacked(leaf, claimsMerkleRoot));

      require(!beneficaryFundsClaimed[claimReceipt], "Claim already made");
      require(MerkleProof.verify(merkleProofs[i], claimsMerkleRoot, leaf), "Merkle proof failed");

      beneficaryFundsClaimed[claimReceipt] = true;
      emit erc1155RoyaltyWithdrawn(contractAddress, tokens[i], beneficary, amounts[i]);
    }

    IERC1155(contractAddress).safeBatchTransferFrom(address(this), beneficary, tokens, amounts, "");
  }

  function onERC1155Received(
        address _operator,
        address _from,
        uint256 _id,
        uint256 _value,
        bytes memory _data
  ) public virtual override returns (bytes4) {
      emit erc1155RoyaltyReceived(msg.sender, _id, _value, _data);
      return this.onERC1155Received.selector;
  }

  function onERC1155BatchReceived(
      address _operator,
      address _from,
      uint256[] memory _ids,
      uint256[] memory _values,
      bytes memory _data
  ) public virtual override returns (bytes4) {
      emit erc1155BatchRoyaltyReceived(msg.sender, _ids, _values, _data);
      return this.onERC1155BatchReceived.selector;
  }

  /**
  * @dev  Implements erc2891 royalties. Importantly the last digits of the
  * returned value are the id of the nft involved in the transaction. It is
  * necessary to include this for the off-chain attribution of which royalty
  * payments involved which nfts.
  * @param tokenId  The id of the nft with which the transaction is associated
  * @param salePrice  The value of the transaction
  * @return address  The address to send the royalty payment to (this contract's
  * address)
  * @return uint256  The value that the transaction should send
  */
  function royaltyInfo(uint256 tokenId, uint256 salePrice) public view override returns (address, uint256) {
    require(royalties[tokenId].length > 0, "This token has not been minted yet or does not pay royalties");

    uint256 royaltyAmount;

    for(uint i = 0; i < royalties[tokenId].length; i++) {
      royaltyAmount += (salePrice * royalties[tokenId][i]) / percentDenominator;
    }

    royaltyAmount = ((royaltyAmount / tokenIdSpace) * tokenIdSpace) + tokenId;

    return (address(this), royaltyAmount);
  }


  // ========================== ADMIN FUNCTIONS ================================
  /**
  * @notice  Used to instantiate a new collection of tokens
  */
  function createNewTokenType(
    NewTokenType memory newTokenType,
    string[] calldata startingStorageSchemas,
    string[] calldata startingBaseUris
  )
    external
    payable
    onlyRole(OPERATOR_ROLE)
    tokenCreationChecks(newTokenType, startingStorageSchemas, startingBaseUris)
  {
    tokenTypes[newTokenType.id].createTokenType(newTokenType, startingStorageSchemas, startingBaseUris);

    if(newTokenType.initialMintAmount > 0) {
      mint(newTokenType.initialMintTo, newTokenType.id, newTokenType.initialMintAmount);
    }

    for(uint i = 0; i < startingStorageSchemas.length; i++) {
      emit storageSchemaAdded(newTokenType.id, startingStorageSchemas[i]);
    }
  }

  /**
  * @notice  Sets a new merkle tree root that can be used by beneficaries to
  * withdraw their funds from the contract
  * @param newAccountRecord  Record of the accounting that determined the
  * allotment of beneficary claims
  * @param newClaimsMerkleRoot  The new merkle tree root that will be used to
  * verify that claims are valid
  */
  function updateBeneficaryClaims(string calldata newAccountRecord, bytes32 newClaimsMerkleRoot)
    external
    onlyRole(ACCOUNTANT_ROLE)
  {
    beneficiaryAccountingRecords.push(newAccountRecord);
    claimsMerkleRoot = newClaimsMerkleRoot;

    emit beneficaryClaimsUpdated(newClaimsMerkleRoot, beneficiaryAccountingRecords.length);
  }

  /**
  * @notice  Sets the royalties of the specified token (once set, they are
  * immutable and can never be changed)
  */
  function setTokenRoyalties(uint256 tokenId, uint16[] calldata _royalties)
    external
    onlyRole(OPERATOR_ROLE)
    setTokenRoyaltiesCheck(tokenId, _royalties)
  {
    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;

    royalties[tokenId] = _royalties;

    // Calculate how much to credit the balances of each party for the nft mint
    (, uint256 royaltyAmount) = royaltyInfo(tokenId, tokenTypes[typeId].cost);

    withdrawalAmounts[ownerWithdrawalAddress] += tokenTypes[typeId].cost - royaltyAmount;
    emit royaltyReceived(royaltyAmount);
  }

  /**
  * @notice  Updates the mint price of a token
  */
  function setTokenCost(uint256 typeId, uint256 newCost)
    external
    onlyRole(OPERATOR_ROLE)
    isLocked(typeId)
  {
    tokenTypes[typeId].cost = newCost;
  }

  /**
  * @notice  Allows the supply of a collection to be increased (only available
  * before the collection is locked)
  */
  function setTokenSupplyCap(uint256 typeId, uint256 newSupplyCap)
    external
    onlyRole(OPERATOR_ROLE)
    isLocked(typeId)
  {
    tokenTypes[typeId].supplyCap = newSupplyCap;
  }

  /**
  * @notice  Pauses/unpauses minting of the specified collection
  */
  function toggleMintable(uint256 typeId)
    external
    onlyRole(OPERATOR_ROLE)
    isLocked(typeId)
  {
    tokenTypes[typeId].mintable = !tokenTypes[typeId].mintable;
  }

  /**
  * @notice  Adds a new version of the metadata to the specified storage schema
  */
  function updateStorageSchema(uint256 typeId, string calldata storageSchema, string calldata newBaseUri)
    external
    onlyRole(OPERATOR_ROLE)
  {
    tokenTypes[typeId].baseUris[storageSchema].push(string(abi.encodePacked(newBaseUri, '{id}.json')));
  }

  /**
  * @notice  Used to add access to new locations where token metadata is stored
  */
  function addStorageSchema(uint256 typeId, string calldata storageSchema, string calldata baseUri)
    external
    onlyRole(OPERATOR_ROLE)
  {
    require(tokenTypes[typeId].baseUris[storageSchema].length == 0, "This storage schema already exists");
    tokenTypes[typeId].baseUris[storageSchema].push(string(abi.encodePacked(baseUri, '{id}.json')));
    emit storageSchemaAdded(typeId, storageSchema);
  }

  function setDefaultStorageSchema(uint256 typeId, string calldata newDefaultStorageSchema)
    external
    onlyRole(OPERATOR_ROLE)
  {
    tokenTypes[typeId].defaultStorageSchema = newDefaultStorageSchema;
  }

  function setownerWithdrawalAddress(address payable _ownerWithdrawalAddress)
    external
    onlyRole(OPERATOR_ROLE)
  {
    ownerWithdrawalAddress = _ownerWithdrawalAddress;
  }

  function setTokenIdSpace(uint256 _tokenIdSpace)
    external
    onlyRole(OPERATOR_ROLE)
  {
    tokenIdSpace = _tokenIdSpace;
    emit tokenIdSpaceChanged(tokenIdSpace);
  }

  /**
  * @notice  Can be used to change the max number of tokens that can be minted in
  * a single transaction for the specified collection
  */
  function setMaxMint(uint256 typeId, uint256 newMaxMint)
    external
    onlyRole(OPERATOR_ROLE)
    isLocked(typeId)
  {
    tokenTypes[typeId].maxMint = newMaxMint;
  }

  /**
  * @notice  Can be used to update the address at which a beneficary receives
  * payments
  */
  function setMandateReceiverAddress(uint256 typeId, uint256 mandateIndex, address payable newMandateReceiver)
    external
    onlyRole(OPERATOR_ROLE)
  {
    tokenTypes[typeId].mandates[mandateIndex].receiver = newMandateReceiver;
  }

  /**
  * @notice  Pauses/unpauses the ability to make withdrawals via merkle tree proofs
  */
  function toggleBeneficaryWithdrawals()
    external
    onlyRole(OPERATOR_ROLE)
  {
    beneficaryWithdrawalsPaused = !beneficaryWithdrawalsPaused;
  }

  /**
  * @notice  Sets a new uri for the contract level metadata
  */
  function setContractUri(string calldata _contractUri)
    external
    onlyRole(OPERATOR_ROLE)
  {
    contractUri = _contractUri;
  }

  /**
  * @notice  Locks in the current maxMint amount, mintability, supplyCap and token
  * cost of the specified collection so that they can never be adjusted again
  */
  function lockToken(uint256 typeId)
    external
    onlyRole(OPERATOR_ROLE)
  {
    tokenTypes[typeId].locked = true;
  }


  // ============================== GETTERS ====================================
  /**
  * @notice  Returns the uri of the contract level metadata
  */
  function contractURI() public view returns (string memory) {
      return contractUri;
  }

  /**
  * @notice  Returns the uri of the default metadata schema for a token
  * @param tokenId  Id of the token whose metadata you wish to retrieve
  * @return string  The uri where the metadata can be found
  */
  function uri(uint256 tokenId) override public view returns (string memory) {
    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;
    string memory defaultStorageSchema = tokenTypes[typeId].defaultStorageSchema;

    uint schemasLength = tokenTypes[typeId].baseUris[defaultStorageSchema].length;
    string memory baseUri = tokenTypes[typeId].baseUris[defaultStorageSchema][schemasLength - 1];

    return baseUri;
  }

  /**
  * @notice  Returns the uri of the specified metadata schema for a token
  * @param tokenId  Id of the token whose metadata you wish to retrieve
  * @param storageSchema  The id of the storage you wish to pull the metadata
  * from (i.e. 'http,' 'ipfs,' 'arweave' or other locations where the metadata
  * has been stored)
  * @return string  The uri where the metadata can be found
  */
  function uri(uint256 tokenId, string calldata storageSchema) external view returns (string memory) {
    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;

    uint schemasLength = tokenTypes[typeId].baseUris[storageSchema].length;
    string memory baseUri = tokenTypes[typeId].baseUris[storageSchema][schemasLength - 1];

    return baseUri;
  }

  /**
  * @notice  Returns the uri of the specified metadata schema at the specified
  * metadata version number for a token
  * @param tokenId  Id of the token whose metadata you wish to retrieve
  * @param storageSchema  The id of the storage you wish to pull the metadata
  * from (i.e. 'http,' 'ipfs,' 'arweave' or other locations where the metadata
  * has been stored)
  * @param schemaIndex  The version number of the metadata that you wish to
  * retrieve
  * @return string  The uri where the metadata can be found
  */
  function uri(uint256 tokenId, string calldata storageSchema, uint256 schemaIndex) external view returns (string memory) {
    uint256 typeId = (tokenId / supplyCapPerTokenType) * supplyCapPerTokenType;

    string memory baseUri = tokenTypes[typeId].baseUris[storageSchema][schemaIndex];

    return baseUri;
  }

  /**
  * @notice  Returns the latest version number of the metadata for the specified
  * metadata storage schema of the specified collection
  */
  function getStorageSchemaCurrentIndex(uint typeId, string calldata storageSchema) external view returns (uint) {
    return tokenTypes[typeId].baseUris[storageSchema].length - 1;
  }

  /**
  * @notice  Returns the mandates for the specified collection
  */
  function getTokenTypeMandates(uint typeId) external view returns (Mandate[] memory) {
    return tokenTypes[typeId].mandates;
  }

  /**
  * @notice  Returns the index of the current beneficary accounting record
  */
  function getBeneficiaryAccountingRecordsLength() external view returns (uint256) {
    return beneficiaryAccountingRecords.length;
  }

}

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



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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

        return batchBalances;
    }

    /**
     * @dev See {IERC1155-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

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

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

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

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `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 memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

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

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

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

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

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

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - 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[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
        require(to != address(0), "ERC1155: transfer to the zero address");

        address operator = _msgSender();

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

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

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

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

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

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

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

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

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

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

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

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

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

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * 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 _mintBatch(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        require(to != address(0), "ERC1155: mint to the zero address");
        require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");

        address operator = _msgSender();

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

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

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

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

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

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

        address operator = _msgSender();
        uint256[] memory ids = _asSingletonArray(id);
        uint256[] memory amounts = _asSingletonArray(amount);

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

        uint256 fromBalance = _balances[id][from];
        require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
        unchecked {
            _balances[id][from] = fromBalance - amount;
        }

        emit TransferSingle(operator, from, address(0), id, amount);

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

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

        address operator = _msgSender();

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

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

            uint256 fromBalance = _balances[id][from];
            require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
            unchecked {
                _balances[id][from] = fromBalance - amount;
            }
        }

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

        _afterTokenTransfer(operator, from, address(0), ids, amounts, "");
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC1155: setting approval status for self");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

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

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

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

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

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

        return array;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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/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/access/AccessControl.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

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

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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 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/utils/cryptography/MerkleProof.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The proofs can be generated using the JavaScript library
 * https://github.com/miguelmota/merkletreejs[merkletreejs].
 * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
 *
 * See `test/utils/cryptography/MerkleProof.test.js` for some examples.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf
    ) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be proved to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and the sibling nodes in `proof`,
     * consuming from one or the other at each step according to the instructions given by
     * `proofFlags`.
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            return hashes[totalHashes - 1];
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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/interfaces/IERC2981.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address receiver, uint256 royaltyAmount);
}

// 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/extensions/IERC1155MetadataURI.sol



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

pragma solidity ^0.8.0;

import "../IERC1155.sol";

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

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

// 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/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/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/access/IAccessControl.sol



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

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

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



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

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}