creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/GlitchAuction.sol": {
        "content": "/**\n * Developed by\n *                        _       _             _ _\n *                       | |     | |           | (_)\n *     __ _ _ __ ___   __| |  ___| |_ _   _  __| |_  ___\n *    / _` | '__/ _ \\ / _` | / __| __| | | |/ _` | |/ _ \\\n *   | (_| | | | (_) | (_| |_\\__ \\ |_| |_| | (_| | | (_) |\n *    \\__,_|_|  \\___/ \\__,_(_)___/\\__|\\__,_|\\__,_|_|\\___/\n *\n *\n * @title English ranked auction with rebate contract\n * @author https://arod.studio/\n * @dev Overview\n * The top 50 bids will secure a unique piece of art. We encourage our collectors to engage actively,\n * as there is no limit to the number of bids you can place.\n * Additionally, the more you bid, the higher your chances of winning multiple pieces.\n *\n * Bidding\n * Please note that once you place a bid, it is final and cannot be altered.\n * We advise all our collectors to bid carefully and consider their choices thoughtfully.\n * This rule ensures fairness and integrity in the auction process.\n *\n * Rebate\n * In our auction, fairness is key. If you are among the top 50 winners and your bid exceeds the lowest winning bid in this group,\n * you will receive a rebate. This rebate equals the difference between your bid and the lowest winning bid,\n * ensuring that all winners pay the same final amount for their art pieces.\n *\n * Non-winning bids\n * At the conclusion of the auction, non-winning participants are eligible to claim a full refund of their bid amounts.\n * This process is straightforward and ensures that if you don't win, you can retrieve your investment without any hassle.\n *\n * @website https://glitch.mishaderidder.com/\n * SPDX-License-Identifier: MIT\n * @custom:security-contact arod.mail@proton.me\n */\n\npragma solidity 0.8.23;\n\nimport {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';\nimport {MerkleProof} from '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';\nimport {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol';\nimport {Pausable} from '@openzeppelin/contracts/utils/Pausable.sol';\nimport {Address} from '@openzeppelin/contracts/utils/Address.sol';\nimport {IGlitch} from './IGlitch.sol';\n\ncontract GlitchAuction is Ownable, ReentrancyGuard, Pausable {\n  using Address for address payable;\n\n  /**\n   * @dev Enum representing the type of discount applied to the bid.\n   * @custom:enum\n   */\n  enum DiscountType {\n    None,\n    FirstTier\n  }\n\n  /**\n   * @dev Represents a bid.\n   * @param bidder The address of the bidder.\n   * @param amount The amount of wei provided for the bid.\n   * @param discountType The type of discount applied to the bid.\n   */\n  struct Bid {\n    address bidder;\n    uint256 amount;\n    DiscountType discountType;\n  }\n\n  /// @dev Represents the auction configuration.\n  struct Config {\n    /// @notice The start time of the auction.\n    uint256 startTime;\n    /// @notice The end time of the auction.\n    uint256 endTime;\n    /// @notice The minimum value to increase the current bid in WEI.\n    uint256 minBidIncrementInWei;\n    /// @notice The starting amount in WEI.\n    uint256 startAmountInWei;\n  }\n\n  /// @dev Emitted when the amount of wei provided for a bid or starting bid is invalid. This usually means the amount is zero.\n  error InvalidAmountInWei();\n  /// @dev Emitted when the provided minimum bid increment value is invalid. This usually means the value is either zero.\n  error InvalidMinBidIncrementValue();\n  /// @dev Emitted when the provided start or end time for the auction is invalid. This usually means the start time is greater than the end time.\n  error InvalidStartEndTime(uint256 startTime, uint256 endTime);\n  error ConfigNotSet(); /// @dev Emitted when the config has not been set.\n  error OnlyOwner(); /// @dev Emitted when the caller is not the owner of the contract.\n  error InvalidAddress(); /// @dev Emitted when an invalid address is provided.\n  error BidTooLow(); /// @dev Emitted when the bid amount is too low.\n  error InsufficientFundsForBid(); /// @dev Emitted when caller does not have enough funds to bid.\n  error BidDoesNotQualifyForTopBids(); /// @dev Emitted when bid does not qualify for top bids.\n  error AuctionNotEnded(); /// @dev Emitted when the auction has not ended.\n  error AlreadyClaimed(); /// @dev Emitted when the NFT and refund has already been claimed.\n  error TransferFailed(); /// @dev Emitted when the NFT transfer has failed.\n\n  event BidPlaced(address indexed bidder, uint256 amount); /// @dev Emitted when a bid is placed.\n  event Outbidded(address indexed bidder, uint256 amount, uint256 lastBidPosition); /// @dev Emitted when a bid is outbidded.\n  event Claimed(address indexed to, uint256 nftAmount, uint256 refundAmount); /// @dev Emitted when the NFT and refund have been claimed.\n\n  /**\n   * @notice MAX_TOP_BIDS represents the maximum number of top bids that can be stored.\n   */\n  uint256 public constant MAX_TOP_BIDS = 50;\n\n  /// @dev The merkle root for discount. 15%\n  bytes32 public firstTierMerkleRoot;\n\n  /**\n   */\n  uint256 internal constant DISCOUNT_PERCENTAGE = 15;\n\n  /**\n   * @notice treasuryWallet stores the address of the treasury wallet where auction funds are sent.\n   */\n  address payable public treasuryWallet;\n\n  /**\n   * @notice withdrawn indicates whether the auction funds have been withdrawn post-auction.\n   */\n  bool public withdrawn;\n\n  /**\n   * @notice glitchAddress stores the address of the ERC721 token (Glitch NFT) being auctioned.\n   */\n  IGlitch public glitchAddress;\n\n  /**\n   * @notice topBids stores the top bids in the auction up to a maximum of MAX_TOP_BIDS.\n   */\n  Bid[MAX_TOP_BIDS] public topBids;\n\n  /**\n   * @notice bidBalances maps each bidder's address to their total bid amount in the auction.\n   */\n  mapping(address bidder => uint256 balance) public bidBalances;\n\n  /**\n   * @notice claimed maps each bidder's address to a boolean indicating whether they have claimed their NFT and/or refund.\n   */\n  mapping(address bidder => bool isClaimed) public claimed;\n\n  /**\n   * @dev _config stores the configuration of the auction, including start time, end time, and minimum bid increment.\n   */\n  Config private _config;\n\n  /**\n   * @dev Modifier to check if the configuration is valid.\n   * @dev Throws ConfigNotSet error if the start time is not set.\n   */\n  modifier validConfig() {\n    if (_config.startTime == 0) revert ConfigNotSet();\n    _;\n  }\n\n  /**\n   * @dev Modifier to check if the current block timestamp is within the specified start and end time.\n   * @dev Throws InvalidStartEndTime error if the current timestamp is not between the start and end time.\n   */\n  modifier validTime() {\n    if (block.timestamp >= _config.endTime || block.timestamp <= _config.startTime) revert InvalidStartEndTime(_config.startTime, _config.endTime);\n    _;\n  }\n\n  /**\n   * @dev Modifier to check if the caller is the owner\n   */\n  modifier _onlyOwner() {\n    if (_msgSender() != owner()) revert OnlyOwner();\n    _;\n  }\n\n  /**\n   * @dev Constructor to initialize the auction with the owner and the ERC721 address.\n   * @param _initialOwner The initial owner of the contract.\n   * @param _glitchAddress The address of the ERC721 token to be auctioned.\n   */\n  constructor(address _initialOwner, address _glitchAddress, address _treasuryWallet) Ownable(_initialOwner) {\n    glitchAddress = IGlitch(_glitchAddress);\n    treasuryWallet = payable(_treasuryWallet);\n  }\n\n  function _refundAndMint(address _to, bool _shouldMint) private returns (uint256 nftsMinted, uint256 amountSpent) {\n    if (block.timestamp <= _config.endTime) revert AuctionNotEnded();\n    if (claimed[_to]) revert AlreadyClaimed();\n\n    DiscountType discountType = DiscountType.None;\n    uint256 balance = bidBalances[_to];\n    claimed[_to] = true;\n\n    for (uint256 i; i < MAX_TOP_BIDS; ) {\n      if (topBids[i].bidder == _to) {\n        if (_shouldMint) glitchAddress.mint(_to, i + 1);\n        nftsMinted++;\n        amountSpent += topBids[i].amount;\n        if (topBids[i].discountType != DiscountType.None) {\n          discountType = topBids[i].discountType;\n        }\n      }\n      unchecked {\n        ++i;\n      }\n    }\n\n    uint256 refundAmount = balance + (amountSpent - (nftsMinted * getSettledPriceWithDiscount(discountType)));\n    if (refundAmount > 0) {\n      payable(_to).sendValue(refundAmount);\n    }\n    return (nftsMinted, amountSpent);\n  }\n\n  /**\n   * @dev Returns the tier discount type of an address.\n   * @param _merkleProof The merkle proof.\n   * @param _addressToCheck The address to check.\n   * @return The tier discount type.\n   */\n  function _getTierDiscount(bytes32[] calldata _merkleProof, address _addressToCheck) private view returns (DiscountType) {\n    if (checkMerkleProof(_merkleProof, _addressToCheck, firstTierMerkleRoot)) {\n      return DiscountType.FirstTier;\n    }\n\n    return DiscountType.None;\n  }\n\n  /**\n   * @dev Returns the last bid position.\n   * @return lastBidPosition The last bid position.\n   */\n  function _getLastBidPosition() private view returns (uint256 lastBidPosition) {\n    lastBidPosition = MAX_TOP_BIDS;\n\n    while (lastBidPosition > 0 && topBids[lastBidPosition - 1].amount == 0) {\n      --lastBidPosition;\n    }\n\n    --lastBidPosition;\n  }\n\n  /**\n   * @dev Internal function to process a bid.\n   * @param _bidder The address of the bidder.\n   * @param _amount The amount of the bid.\n   */\n  function processBid(address _bidder, uint256 _amount, DiscountType _discountType) private {\n    uint256 position;\n\n    // Find the position of the new bid in the top bids\n    while (position < MAX_TOP_BIDS && topBids[position].amount >= _amount) {\n      unchecked {\n        ++position;\n      }\n    }\n\n    if (position >= MAX_TOP_BIDS) revert BidDoesNotQualifyForTopBids();\n\n    // Remove the old top bid\n    Bid memory outbidded = topBids[MAX_TOP_BIDS - 1];\n    if (outbidded.bidder != address(0)) {\n      emit Outbidded(outbidded.bidder, outbidded.amount, position);\n      bidBalances[outbidded.bidder] = bidBalances[outbidded.bidder] + outbidded.amount;\n    }\n\n    // Insert the new bid\n    for (uint256 i = MAX_TOP_BIDS - 1; i > position; i--) {\n      topBids[i] = topBids[i - 1];\n    }\n    emit BidPlaced(_bidder, _amount);\n    topBids[position] = Bid(_bidder, _amount, _discountType);\n  }\n\n  /**\n   * @dev Allows the owner to pause the auction.\n   */\n  function pause() external onlyOwner {\n    _pause();\n  }\n\n  /**\n   * @dev Allows the owner to unpause the auction.\n   */\n  function unpause() external onlyOwner {\n    _unpause();\n  }\n\n  /**\n   * @notice Sets the configuration parameters for the auction.\n   * @dev This function can only be called by an admin. It can be used to set the start time, end time,\n   *  minimum bid increment in WEI, and starting bid amount.\n   * @param _startTime Auction start time\n   * @param _endTime Auction end time\n   * @param _minBidIncrementInWei Auction minimum bid increment in WEI\n   * @param _startAmountInWei Auction starting bid\n   */\n  function setConfig(uint256 _startTime, uint256 _endTime, uint256 _minBidIncrementInWei, uint256 _startAmountInWei) external _onlyOwner {\n    if (_startTime == 0 || _startTime >= _endTime) revert InvalidStartEndTime(_startTime, _endTime);\n    if (_startAmountInWei == 0) revert InvalidAmountInWei();\n\n    if (_minBidIncrementInWei == 0) revert InvalidMinBidIncrementValue();\n\n    _config = Config({startTime: _startTime, endTime: _endTime, minBidIncrementInWei: _minBidIncrementInWei, startAmountInWei: _startAmountInWei});\n  }\n\n  /**\n   * @dev Allows the owner to set a new treasury wallet address.\n   * @param _newWallet The new treasury wallet address.\n   */\n  function setTreasuryWallet(address _newWallet) external _onlyOwner {\n    if (_newWallet == address(0)) revert InvalidAddress();\n    treasuryWallet = payable(_newWallet);\n  }\n\n  /**\n   * @dev Allows the owner to set a new treasury wallet address.\n   * @param _glitchAddress The new treasury wallet address.\n   */\n  function setGlitchAddress(address _glitchAddress) external _onlyOwner {\n    if (_glitchAddress == address(0)) revert InvalidAddress();\n    glitchAddress = IGlitch(_glitchAddress);\n  }\n\n  /**\n   * @dev Allows the owner to set the first tier merkle root.\n   * @param _firstTierRoot The new first tier merkle root.\n   */\n  function setMerkleRoots(bytes32 _firstTierRoot) external onlyOwner {\n    firstTierMerkleRoot = _firstTierRoot;\n  }\n\n  /**\n   * @dev Allows users to place bids on the auction.\n   * @param _bidAmount The amount of the bid.\n   */\n  function bid(uint256 _bidAmount, bytes32[] calldata _merkleProof) external payable validConfig validTime whenNotPaused nonReentrant {\n    if (_bidAmount < getMinimumBid()) revert BidTooLow();\n    if (msg.value != _bidAmount) revert InsufficientFundsForBid();\n\n    processBid(_msgSender(), _bidAmount, _getTierDiscount(_merkleProof, _msgSender()));\n  }\n\n  /**\n   * @dev Allows users to claim their NFTs and any refunds after the auction ends.\n   * @param _to The claimer address.\n   */\n  function claimAll(address _to) external validConfig whenNotPaused nonReentrant {\n    (uint256 nftsMinted, uint256 refundAmount) = _refundAndMint(_to, true);\n    emit Claimed(_to, nftsMinted, refundAmount);\n  }\n\n  /**\n   * @dev Allows admin to force refund of users after the auction ends. It doesn't claim and mint the nfts.\n   * @notice use only in emergency case.\n   * @dev Only admin can force refund.\n   * @param _to The claimer address.\n   */\n  function forceRefund(address _to) external validConfig _onlyOwner nonReentrant {\n    _refundAndMint(_to, false);\n  }\n\n  /**\n   * @dev Allows the owner to mint the remaining NFTs after the auction ends.\n   * @param _recipient The recipient address.\n   */\n  function adminMintRemaining(address _recipient) external _onlyOwner validConfig {\n    if (block.timestamp <= _config.endTime) revert AuctionNotEnded();\n    uint256 lastBidPosition = _getLastBidPosition();\n    for (uint256 i = lastBidPosition + 1; i < MAX_TOP_BIDS; ) {\n      glitchAddress.mint(_recipient, i + 1);\n      unchecked {\n        ++i;\n      }\n    }\n  }\n\n  /**\n   * @dev Allows the owner to withdraw the sales amount after the auction ends.\n   */\n  function withdraw() external _onlyOwner nonReentrant {\n    if (block.timestamp <= _config.endTime) revert AuctionNotEnded();\n    if (withdrawn) revert AlreadyClaimed();\n    withdrawn = true;\n    uint256 givenFirstTierDiscount;\n    uint256 salesAmountWithoutDiscount;\n\n    for (uint256 i; i < MAX_TOP_BIDS; ) {\n      if (topBids[i].bidder == address(0)) {\n        break;\n      }\n      if (topBids[i].discountType == DiscountType.FirstTier) {\n        givenFirstTierDiscount++;\n      } else {\n        salesAmountWithoutDiscount++;\n      }\n      unchecked {\n        ++i;\n      }\n    }\n\n    uint256 salesAmountWithDiscount = getSettledPriceWithDiscount(DiscountType.FirstTier) * givenFirstTierDiscount;\n    uint256 salesAmount = getSettledPrice() * salesAmountWithoutDiscount;\n    treasuryWallet.sendValue(salesAmountWithDiscount + salesAmount);\n  }\n\n  /**\n   * @dev Checks if a merkle proof is valid.\n   * @param _merkleProof The merkle proof to be checked.\n   * @param _address The address to be checked.\n   * @param _root The merkle root.\n   */\n  function checkMerkleProof(bytes32[] calldata _merkleProof, address _address, bytes32 _root) public pure returns (bool) {\n    bytes32 leaf = keccak256(abi.encodePacked(_address));\n    return MerkleProof.verify(_merkleProof, _root, leaf);\n  }\n\n  /**\n   * @dev Returns the settled price of the auction.\n   * @return The price of the lowest winning bid.\n   */\n  function getSettledPrice() public view returns (uint256) {\n    uint256 lastBidPosition = _getLastBidPosition();\n    uint256 lastBidAmount = topBids[lastBidPosition].amount;\n    return lastBidAmount < _config.startAmountInWei ? _config.startAmountInWei : lastBidAmount;\n  }\n\n  /**\n   * @dev Returns the settled price of the auction with discount.\n   * @param _discountType The type of discount to apply.\n   * @return The price of the lowest winning bid.\n   */\n  function getSettledPriceWithDiscount(DiscountType _discountType) public view returns (uint256) {\n    if (_discountType == DiscountType.FirstTier) {\n      return (getSettledPrice() * (100 - DISCOUNT_PERCENTAGE)) / 100;\n    }\n    return getSettledPrice();\n  }\n  /**\n   * @dev Returns the minimum bid amount required to place a bid.\n   * @return The minimum bid amount.\n   */\n  function getMinimumBid() public view returns (uint256) {\n    uint256 lastBidAmount = topBids[MAX_TOP_BIDS - 1].amount;\n    return lastBidAmount < _config.startAmountInWei ? _config.startAmountInWei : lastBidAmount + _config.minBidIncrementInWei;\n  }\n  /**\n   * @dev Returns the current configuration of the auction.\n   * @return The auction configuration.\n   */\n  function getConfig() external view returns (Config memory) {\n    return _config;\n  }\n\n  /**\n   * @dev Returns the top bids of the auction.\n   * @return An array of the top bids.\n   */\n  function getTopBids() external view returns (Bid[MAX_TOP_BIDS] memory) {\n    return topBids;\n  }\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev These functions deal with verification of Merkle Tree proofs.\n *\n * The tree and the proofs can be generated using our\n * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\n * You will find a quickstart guide in the readme.\n *\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\n * hashing, or use a hash function other than keccak256 for hashing leaves.\n * This is because the concatenation of a sorted pair of internal nodes in\n * the Merkle tree could be reinterpreted as a leaf value.\n * OpenZeppelin's JavaScript library generates Merkle trees that are safe\n * against this attack out of the box.\n */\nlibrary MerkleProof {\n    /**\n     *@dev The multiproof provided is not valid.\n     */\n    error MerkleProofInvalidMultiproof();\n\n    /**\n     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n     * defined by `root`. For this, a `proof` must be provided, containing\n     * sibling hashes on the branch from the leaf to the root of the tree. Each\n     * pair of leaves and each pair of pre-images are assumed to be sorted.\n     */\n    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n        return processProof(proof, leaf) == root;\n    }\n\n    /**\n     * @dev Calldata version of {verify}\n     */\n    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {\n        return processProofCalldata(proof, leaf) == root;\n    }\n\n    /**\n     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n     * hash matches the root of the tree. When processing the proof, the pairs\n     * of leafs & pre-images are assumed to be sorted.\n     */\n    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = _hashPair(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Calldata version of {processProof}\n     */\n    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {\n        bytes32 computedHash = leaf;\n        for (uint256 i = 0; i < proof.length; i++) {\n            computedHash = _hashPair(computedHash, proof[i]);\n        }\n        return computedHash;\n    }\n\n    /**\n     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by\n     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     */\n    function multiProofVerify(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves\n    ) internal pure returns (bool) {\n        return processMultiProof(proof, proofFlags, leaves) == root;\n    }\n\n    /**\n     * @dev Calldata version of {multiProofVerify}\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     */\n    function multiProofVerifyCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32 root,\n        bytes32[] memory leaves\n    ) internal pure returns (bool) {\n        return processMultiProofCalldata(proof, proofFlags, leaves) == root;\n    }\n\n    /**\n     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n     * respectively.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n     */\n    function processMultiProof(\n        bytes32[] memory proof,\n        bool[] memory proofFlags,\n        bytes32[] memory leaves\n    ) internal pure returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofLen = proof.length;\n        uint256 totalHashes = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proofLen != totalHashes + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](totalHashes);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < totalHashes; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = _hashPair(a, b);\n        }\n\n        if (totalHashes > 0) {\n            if (proofPos != proofLen) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[totalHashes - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n\n    /**\n     * @dev Calldata version of {processMultiProof}.\n     *\n     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.\n     */\n    function processMultiProofCalldata(\n        bytes32[] calldata proof,\n        bool[] calldata proofFlags,\n        bytes32[] memory leaves\n    ) internal pure returns (bytes32 merkleRoot) {\n        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by\n        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n        // the Merkle tree.\n        uint256 leavesLen = leaves.length;\n        uint256 proofLen = proof.length;\n        uint256 totalHashes = proofFlags.length;\n\n        // Check proof validity.\n        if (leavesLen + proofLen != totalHashes + 1) {\n            revert MerkleProofInvalidMultiproof();\n        }\n\n        // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n        bytes32[] memory hashes = new bytes32[](totalHashes);\n        uint256 leafPos = 0;\n        uint256 hashPos = 0;\n        uint256 proofPos = 0;\n        // At each step, we compute the next hash using two values:\n        // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n        //   get the next hash.\n        // - depending on the flag, either another value from the \"main queue\" (merging branches) or an element from the\n        //   `proof` array.\n        for (uint256 i = 0; i < totalHashes; i++) {\n            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n            bytes32 b = proofFlags[i]\n                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])\n                : proof[proofPos++];\n            hashes[i] = _hashPair(a, b);\n        }\n\n        if (totalHashes > 0) {\n            if (proofPos != proofLen) {\n                revert MerkleProofInvalidMultiproof();\n            }\n            unchecked {\n                return hashes[totalHashes - 1];\n            }\n        } else if (leavesLen > 0) {\n            return leaves[0];\n        } else {\n            return proof[0];\n        }\n    }\n\n    /**\n     * @dev Sorts the pair (a, b) and hashes the result.\n     */\n    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {\n        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);\n    }\n\n    /**\n     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.\n     */\n    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, a)\n            mstore(0x20, b)\n            value := keccak256(0x00, 0x40)\n        }\n    }\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    uint256 private _status;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if (_status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        _status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == ENTERED;\n    }\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/utils/Pausable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n    bool private _paused;\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    constructor() {\n        _paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        return _paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        _paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        _paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert FailedInnerCall();\n        }\n    }\n}\n"
      },
      "src/IGlitch.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.23;\n\ninterface IGlitch {\n  error AddressInsufficientBalance(address account);\n  error ERC721EnumerableForbiddenBatchMint();\n  error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n  error ERC721InsufficientApproval(address operator, uint256 tokenId);\n  error ERC721InvalidApprover(address approver);\n  error ERC721InvalidOperator(address operator);\n  error ERC721InvalidOwner(address owner);\n  error ERC721InvalidReceiver(address receiver);\n  error ERC721InvalidSender(address sender);\n  error ERC721NonexistentToken(uint256 tokenId);\n  error ERC721OutOfBoundsIndex(address owner, uint256 index);\n  error FailedInnerCall();\n  error IdOutOfBounds();\n  error InvalidPrice();\n  error NotEnoughETH();\n  error OnlyMinter();\n  error OnlyOwner();\n  error OnlyTokenOwner();\n  error OwnableInvalidOwner(address owner);\n  error OwnableUnauthorizedAccount(address account);\n  error ReentrancyGuardReentrantCall();\n  error ZeroAddress();\n\n  event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n  event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n  event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n  event Burned(address indexed tokenOwner, uint256 indexed tokenId, uint256 indexed givenCode);\n  event MetadataUpdate(uint256 _tokenId);\n  event Minted(address indexed recipient, uint256 indexed tokenId);\n  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n  event TokenRefreshed(uint256 indexed tokenId, address refresherAddress);\n  event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n  function adminMint(address recipient, uint256[] memory _ids) external;\n  function approve(address to, uint256 tokenId) external;\n  function balanceOf(address owner) external view returns (uint256);\n  function burnToReedem(uint256 _tokenId, uint256 _givenCode) external;\n  function fundsReceiverAddress() external view returns (address payable);\n  function getAllTokensVersion() external view returns (string[] memory versions);\n  function getApproved(uint256 tokenId) external view returns (address);\n  function getTokenVersion(uint256 tokenId) external view returns (string memory versionStr);\n  function getTokensByOwner(address _owner) external view returns (uint256[] memory tokenIds);\n  function isApprovedForAll(address owner, address operator) external view returns (bool);\n  function mint(address recipient, uint256 _id) external;\n  function minterContractAddress() external view returns (address);\n  function name() external view returns (string memory);\n  function owner() external view returns (address);\n  function ownerOf(uint256 tokenId) external view returns (address);\n  function refreshToken(uint256 _tokenId) external payable;\n  function refreshTokenPrice() external view returns (uint256);\n  function renounceOwnership() external;\n  function safeTransferFrom(address from, address to, uint256 tokenId) external;\n  function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) external;\n  function setApprovalForAll(address operator, bool approved) external;\n  function setBaseURI(string memory newBaseURI) external;\n  function setFundsReceiverAddress(address newFundsReceiverAddress) external;\n  function setMinterContractAddress(address newMinterContractAddress) external;\n  function setRefreshTokenPrice(uint256 newRefreshTokenPriceInWei) external;\n  function supportsInterface(bytes4 interfaceId) external view returns (bool);\n  function symbol() external view returns (string memory);\n  function tokenByIndex(uint256 index) external view returns (uint256);\n  function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n  function tokenURI(uint256 tokenId) external view returns (string memory);\n  function totalSupply() external view returns (uint256);\n  function transferFrom(address from, address to, uint256 tokenId) external;\n  function transferOwnership(address newOwner) external;\n}\n"
      },
      "node_modules_link/@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@openzeppelin/contracts/=node_modules_link/@openzeppelin/contracts/",
        "@prb/test/=node_modules_link/@prb/test/",
        "forge-std/=node_modules_link/forge-std/",
        "murky-merkle/=node_modules_link/murky-merkle/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 10000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "none",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": false,
      "libraries": {}
    }
  }}