// File: src/GarageSale.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";

/**
 * @title Garage Sale
 *
 * @notice this contract implements a simple "garage sale" protocol to facilitate
 * the resale of low value NFTs in shuffled bundles via ongoing dutch auctions.
 */
contract GarageSale is
    Ownable2Step,
    IERC721Receiver,
    IERC1155Receiver,
    ReentrancyGuard
{
    // events
    event Sell(
        address indexed seller,
        address indexed token,
        uint16 type_,
        uint256 id,
        uint256 amount
    );
    event Buy(
        address indexed buyer,
        address[] tokens,
        uint16[] types,
        uint256[] ids,
        uint256[] amounts
    );
    event OfferUpdated(uint256 offer);
    event AuctionUpdated(uint96 min, uint96 max, uint32 duration);
    event BundleUpdated(uint8 bundle);
    event TokenUpdated(address indexed token, uint16 type_);
    event ControllerUpdated(address controller);
    event InventoryUpdated(uint192 inventory);
    event Funded(uint256 amount);
    event Withdrawn(uint256 amount);

    // types
    enum TokenType {
        Unknown,
        ERC721,
        ERC1155
    }
    struct Item {
        address token;
        uint96 id;
    }

    // config
    uint256 public offer; // wei
    uint96 public min; // wei
    uint96 public max; // wei
    uint32 public duration; // seconds
    uint8 public bundle; // size
    address public controller;

    // data
    mapping(address => TokenType) public tokens;
    Item[] public inventory;
    mapping(uint256 => bool) public exists; // need this for ERC1155 only
    uint192 public available; // last inventory size
    uint64 public nonce; // last auction window purchased

    /**
     * @notice initialize garage sale contract with reasonable defaults
     * @param owner address of initial owner
     */
    constructor(address owner) Ownable(owner) {
        offer = 1e12; // 0.000001 ether
        min = 1e16; // 0.01 ether
        max = 1e17; // 0.1 ether
        duration = 15 * 60; // 15 minutes
        bundle = 4;
        controller = owner;
    }

    modifier onlyController() {
        require(
            msg.sender == controller || msg.sender == owner(),
            "sender is not controller"
        );
        _;
    }

    /**
     * @notice erc165 check for standard interface support
     * @param interfaceId interface id in question
     */
    function supportsInterface(
        bytes4 interfaceId
    ) external pure returns (bool) {
        return
            interfaceId == type(IERC721Receiver).interfaceId ||
            interfaceId == type(IERC1155Receiver).interfaceId;
    }

    // --- sell ---------------------------------------------------------------

    /**
     * @notice handles receipt and purchase of an ERC721 token
     * @param from address of token sender
     * @param tokenId uint256 id of token
     */
    function onERC721Received(
        address /*operator*/,
        address from,
        uint256 tokenId,
        bytes calldata /*data*/
    ) external nonReentrant returns (bytes4) {
        require(tokens[msg.sender] == TokenType.ERC721, "unknown token");
        uint256 offer_ = offer;
        require(address(this).balance >= offer_, "insufficient funds");

        inventory.push(Item(msg.sender, uint96(tokenId)));

        (bool sent, ) = payable(from).call{value: offer_}("");
        require(sent, "ether transfer failed");

        emit Sell(from, msg.sender, uint16(TokenType.ERC721), tokenId, 1);
        return this.onERC721Received.selector;
    }

    /**
     * @notice handles receipt and purchase of an ERC1155 token
     * @param from address of token sender
     * @param id uint256 class id of token
     * @param value amount of token
     */
    function onERC1155Received(
        address /*operator*/,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata /*data*/
    ) external nonReentrant returns (bytes4) {
        require(tokens[msg.sender] == TokenType.ERC1155, "unknown token");
        uint256 offer_ = offer;
        require(address(this).balance >= offer_, "insufficient funds");

        _receiveERC1155(from, msg.sender, id, value);

        (bool sent, ) = payable(from).call{value: offer_}("");
        require(sent, "ether transfer failed");

        return this.onERC1155Received.selector;
    }

    /**
     * @notice handles receipt and purchase of an ERC1155 token batch
     * @param from address of token sender
     * @param ids array of token class ids
     * @param values array of token amounts (order and length must match ids array)
     */
    function onERC1155BatchReceived(
        address /*operator*/,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata /*data*/
    ) external nonReentrant returns (bytes4) {
        require(tokens[msg.sender] == TokenType.ERC1155, "unknown token");
        uint256 count = ids.length;
        uint256 offer_ = offer;
        require(address(this).balance >= count * offer_, "insufficient funds");
        require(count == values.length, "inconsistent id and value arrays");

        for (uint256 i; i < count; i++) {
            _receiveERC1155(from, msg.sender, ids[i], values[i]);
        }

        (bool sent, ) = payable(from).call{value: count * offer_}("");
        require(sent, "ether transfer failed");

        return this.onERC1155BatchReceived.selector;
    }

    /**
     * @dev private helper function to process a received erc1155 item
     * @param from address of token sender
     * @param token address of erc1155 contract
     * @param id token class id
     * @param value token amount
     */
    function _receiveERC1155(
        address from,
        address token,
        uint256 id,
        uint256 value
    ) private {
        // add item to inventory only if it doesn't already exist
        uint256 key = uint256(uint160(token));
        key |= uint256(id) << 160;
        if (!exists[key]) {
            inventory.push(Item(token, uint96(id)));
            exists[key] = true;
        }
        // emit
        emit Sell(from, token, uint16(TokenType.ERC1155), id, value);
    }

    // --- buy ----------------------------------------------------------------

    /**
     * @notice purchase the current token bundle on auction
     * @param seed_ the seed of the current auction (to verify transaction intent)
     */
    function buy(uint256 seed_) external payable nonReentrant {
        require(msg.value >= price(), "insufficient payment");
        uint256 t = start();
        require(t > nonce, "already purchased");
        uint256 avail = available;
        uint256 s = _seed(t, avail);
        require(seed_ == s, "stale transaction");
        uint256 bund = bundle;
        uint256 total = inventory.length;
        if (avail <= bund && total > bund) {
            avail = bund + 1; // we can auto bump to fixed value
        }
        require(avail > bund, "insufficient inventory");

        address[] memory addrs = new address[](bund);
        uint16[] memory types = new uint16[](bund);
        uint256[] memory ids = new uint256[](bund);
        uint256[] memory amounts = new uint256[](bund);

        // shuffle
        for (uint256 i; i < bund; i++) {
            // get item data
            uint256 r = s % (avail - i);
            addrs[i] = inventory[r].token;
            ids[i] = inventory[r].id;
            // backfill removed item
            inventory[r] = inventory[avail - i - 1];
            if (total > avail) {
                // reindex new pending items
                inventory[avail - i - 1] = inventory[total - i - 1];
            }
            inventory.pop();
        }
        available = uint192(total - bund);
        nonce = uint64(t);

        // send all
        for (uint256 i; i < bund; i++) {
            TokenType type_ = tokens[addrs[i]];
            types[i] = uint16(type_);
            if (type_ == TokenType.ERC721) {
                amounts[i] = 1;
                IERC721(addrs[i]).safeTransferFrom(
                    address(this),
                    msg.sender,
                    ids[i]
                );
            } else if (type_ == TokenType.ERC1155) {
                // get full balance
                IERC1155 tkn = IERC1155(addrs[i]);
                uint256 bal = tkn.balanceOf(address(this), ids[i]);
                amounts[i] = bal;
                // clear exists key
                uint256 key = uint256(uint160(addrs[i]));
                key |= uint256(ids[i]) << 160;
                exists[key] = false;
                // send all
                tkn.safeTransferFrom(
                    address(this),
                    msg.sender,
                    ids[i],
                    bal,
                    ""
                );
            }
            // else {} // pass if token no longer registered
        }
        emit Buy(msg.sender, addrs, types, ids, amounts);
    }

    /**
     * @notice get contents of current token bundle on auction
     */
    function preview()
        external
        view
        returns (
            address[] memory tokens_,
            uint16[] memory types,
            uint256[] memory ids,
            uint256[] memory amounts
        )
    {
        uint256 t = start();
        require(t > nonce, "already purchased");
        uint256 avail = available;
        uint256 s = _seed(t, avail);

        uint256 bund = bundle;
        if (avail <= bund && inventory.length > bund) {
            avail = bund + 1; // we can auto bump
        }
        require(avail > bund, "insufficient inventory");

        tokens_ = new address[](bund);
        types = new uint16[](bund);
        ids = new uint256[](bund);
        amounts = new uint256[](bund);

        // preview shuffle
        uint256[] memory rand = new uint256[](bund);

        for (uint256 i; i < bund; i++) {
            uint256 r = s % (avail - i);
            rand[i] = r;
            for (uint256 j = i; j > 0; j--) {
                // walk back through replacements
                if (r == rand[j - 1]) {
                    r = avail - j;
                }
            }
            Item storage item = inventory[r];
            TokenType type_ = tokens[item.token];
            tokens_[i] = item.token;
            types[i] = uint16(type_);
            ids[i] = item.id;
            if (type_ == TokenType.ERC721) {
                amounts[i] = 1;
            } else if (type_ == TokenType.ERC1155) {
                amounts[i] = IERC1155(item.token).balanceOf(
                    address(this),
                    item.id
                );
            }
            // else {} // pass if token no longer registered
        }
    }

    /**
     * @notice get the current dutch auction price
     */
    function price() public view returns (uint256) {
        uint256 m = max;
        uint256 d = duration;
        uint256 elapsed = block.timestamp % d;
        return m - ((m - min) * elapsed) / d;
    }

    /**
     * @notice get the current auction seed
     */
    function seed() public view returns (uint256) {
        return _seed(start(), available);
    }

    function _seed(
        uint256 start_,
        uint256 available_
    ) private pure returns (uint256) {
        return uint256(keccak256(abi.encodePacked(start_, available_)));
    }

    /**
     * @notice get the start epoch time of the current auction
     */
    function start() public view returns (uint256) {
        uint256 d = duration;
        return d * (block.timestamp / d);
    }

    // --- info ---------------------------------------------------------------

    function inventorySize() external view returns (uint256) {
        return inventory.length;
    }

    // --- configuration ------------------------------------------------------

    /**
     * @param offer_ new offer price (in wei) to sell a token to the protocol
     */
    function setOffer(uint256 offer_) external onlyController {
        require(offer_ > 0, "offer is zero");
        require(offer_ < min / bundle, "offer too high");
        offer = offer_;
        emit OfferUpdated(offer_);
    }

    /**
     * @notice update params for dutch auction resale
     * @param min_ new minimum price
     * @param max_ new maximum price
     * @param duration_ new auction duration
     */
    function setAuction(
        uint96 min_,
        uint96 max_,
        uint32 duration_
    ) external onlyController {
        require(min_ > bundle * offer, "min too low");
        require(min_ <= max_, "min is greater than max price");
        require(duration_ >= 60, "duration too low");
        min = min_;
        max = max_;
        duration = duration_;
        emit AuctionUpdated(min_, max_, duration_);
    }

    /**
     * @param bundle_ new bundle size for auction
     */
    function setBundle(uint8 bundle_) external onlyController {
        require(bundle_ > 0, "bundle size is zero");
        bundle = bundle_;
        emit BundleUpdated(bundle_);
    }

    /**
     * @param tokens_ addresses of tokens to update
     * @param types new token types
     */
    function setTokens(
        address[] calldata tokens_,
        uint16[] calldata types
    ) external onlyController {
        require(tokens_.length == types.length, "arrays not equal length");
        for (uint256 i; i < tokens_.length; i++) {
            require(tokens_[i] != address(0), "token is zero address");
            require(
                types[i] <= uint16(TokenType.ERC1155),
                "token type is invalid"
            );
            TokenType type_ = TokenType(types[i]);
            if (type_ == TokenType.ERC721) {
                require(
                    IERC721(tokens_[i]).supportsInterface(
                        type(IERC721).interfaceId
                    ),
                    "token does not support erc721 interface"
                );
            } else if (type_ == TokenType.ERC1155) {
                require(
                    IERC1155(tokens_[i]).supportsInterface(
                        type(IERC1155).interfaceId
                    ),
                    "token does not support erc1155 interface"
                );
            }

            tokens[tokens_[i]] = type_;
            emit TokenUpdated(tokens_[i], types[i]);
        }
    }

    /**
     * @param controller_ new controller address
     */
    function setController(address controller_) external onlyOwner {
        controller = controller_;
        emit ControllerUpdated(controller_);
    }

    /**
     * @notice update data to refresh inventory
     */
    function bump() external onlyController {
        available = uint192(inventory.length);
        emit InventoryUpdated(available);
    }

    /**
     * @notice fund the garage sale contract
     */
    function fund() external payable {
        require(msg.value > 0, "fund amount is zero");
        emit Funded(msg.value);
    }

    /**
     * @notice withdraw contract fees
     */
    function withdraw(uint256 amount) external onlyOwner {
        require(amount > 0, "withdraw amount is zero");
        require(amount <= address(this).balance, "insufficient balance");
        emit Withdrawn(amount);
        (bool sent, ) = payable(msg.sender).call{value: amount}("");
        require(sent, "ether withdraw failed");
    }
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

// File: lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

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

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

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

// File: lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol



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

pragma solidity ^0.8.20;

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

// File: lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

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

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

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

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

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

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

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

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

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

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

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

// File: lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol



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

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
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: lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of 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 value 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 a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * 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 `value` 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 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `values` 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 values,
        bytes calldata data
    ) external;
}

// File: lib/openzeppelin-contracts/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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: lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)

pragma solidity ^0.8.20;

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